Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- CC-Tweaked Remote Control Turtle Script
- -- Player: Myros27
- -- Configuration
- local owner_name = "Myros27"
- local turtle_name_file = ".turtle_name" -- Hidden file for storing the turtle's name
- local my_name -- Will be set during setup
- -- Peripherals
- local chat = peripheral.find("chatBox")
- local automata = peripheral.find("endAutomata") -- Accessible in commands as 'automata'
- -- Scare messages for unauthorized users
- local scare_messages = {
- "Self-destruction sequence initiated!",
- "Unauthorized access detected. Engaging countermeasures.",
- "Warning: Tampering with this unit is ill-advised.",
- "My circuits are tingling with... annoyance. Please desist.",
- "Access denied. This unit only responds to its registered master.",
- "SECURITY ALERT! Unauthorized command attempt by: " -- Appends sender's name
- }
- -- Cooldown for chat messages (seconds)
- local last_message_time = 0
- local chat_cooldown = 1.1 -- Slightly above 1s to be safe with ChatBox API
- --------------------------------------------------------------------------------
- -- HELPER FUNCTIONS
- --------------------------------------------------------------------------------
- -- Custom printWarn if not available (CC:Tweaked usually has it)
- if not printWarn then
- _G.printWarn = function(...)
- local old_color_fg, old_color_bg = term.getTextColor(), term.getBackgroundColor()
- term.setTextColor(colors.orange)
- io.stderr:write(table.concat({...}, "\t"))
- io.stderr:write("\n")
- term.setTextColor(old_color_fg)
- term.setBackgroundColor(old_color_bg)
- end
- end
- -- Save turtle name to file
- local function save_turtle_name(name_to_save)
- local file = fs.open(turtle_name_file, "w")
- if file then
- file.write(name_to_save)
- file.close()
- return true
- end
- printError("Failed to write turtle name to " .. turtle_name_file)
- return false
- end
- -- Load turtle name from file
- local function load_turtle_name()
- if fs.exists(turtle_name_file) then
- local file = fs.open(turtle_name_file, "r")
- if file then
- local name_from_file = file.readLine()
- file.close()
- -- Check not nil and not just whitespace
- if name_from_file and name_from_file:gsub("%s+", "") ~= "" then
- return name_from_file:match("^%s*(.-)%s*$") -- Trim whitespace
- end
- else
- printError("Failed to open " .. turtle_name_file .. " for reading.")
- end
- end
- return nil
- end
- -- Prompt user for turtle name if not set, and load/save it
- local function setup_turtle_name()
- local existing_name = load_turtle_name()
- if existing_name then
- term.setTextColor(colors.white)
- term.write("Resuming with name: ")
- term.setTextColor(colors.yellow)
- print(existing_name)
- term.setTextColor(colors.white)
- return existing_name
- end
- term.setTextColor(colors.white)
- term.write("Enter a unique name for this turtle: ")
- term.setTextColor(colors.yellow)
- local new_name_input = read()
- term.setTextColor(colors.white)
- if new_name_input and new_name_input:gsub("%s+", "") ~= "" then
- new_name_input = new_name_input:match("^%s*(.-)%s*$") -- Trim
- if save_turtle_name(new_name_input) then
- print("Turtle name set to: " .. new_name_input)
- return new_name_input
- else
- printError("Failed to save turtle name. Using 'default_turtle'.")
- return "default_turtle" -- Fallback
- end
- else
- print("No valid name entered. Using 'default_turtle'.")
- return "default_turtle" -- Fallback
- end
- end
- -- Send a message to global chat via ChatBox
- local function say(message_content)
- if not my_name then my_name = "UnnamedTurtle" end -- Safety net
- if chat then
- local current_time = os.time()
- local time_since_last = current_time - last_message_time
- if time_since_last < chat_cooldown then
- local wait_duration = chat_cooldown - time_since_last
- if wait_duration > 0 then
- -- Optional: print("Chat cooldown: waiting " .. string.format("%.2f", wait_duration) .. "s")
- os.sleep(wait_duration)
- end
- end
- chat.sendMessage(message_content, my_name) -- Turtle's name as prefix
- last_message_time = os.time()
- else
- local prefix = "[" .. my_name
- if not chat then prefix = prefix .. " Chat Disabled" end
- prefix = prefix .. "]"
- print(prefix .. " " .. message_content)
- end
- end
- -- Format results of command execution for chat output
- local function format_command_output(...)
- local results_pack = {...}
- local n = select("#", ...)
- if n == 0 then
- return "Command executed (produced no return values)."
- end
- local parts = {}
- for i = 1, n do
- local v = results_pack[i]
- if v == nil then
- table.insert(parts, "nil")
- elseif type(v) == "table" then
- table.insert(parts, textutils.serialize(v))
- elseif type(v) == "function" then
- table.insert(parts, "function:"..tostring(v))
- else
- table.insert(parts, tostring(v))
- end
- end
- return "Output: " .. table.concat(parts, ", ")
- end
- -- Execute a Lua command string
- local function execute_command(command_str, sender_name)
- say("Received command from " .. sender_name .. ": " .. command_str)
- -- The environment for the loaded command will be _G (this script's global environment)
- local func_env = _G
- local func, compile_err = load(command_str, "ChatCmd@" .. my_name, "t", func_env)
- if not func then
- say("Compilation Error for command from " .. sender_name .. ": " .. tostring(compile_err))
- return
- end
- local pcall_results = {pcall(func)}
- local success = pcall_results[1]
- table.remove(pcall_results, 1) -- Remove status, keep only actual results or error message
- if success then
- say(format_command_output(table.unpack(pcall_results)))
- else
- say("Execution Error for command from " .. sender_name .. ": " .. tostring(pcall_results[1]))
- end
- end
- --------------------------------------------------------------------------------
- -- INITIALIZATION
- --------------------------------------------------------------------------------
- term.clear()
- term.setCursorPos(1,1)
- print("===================================")
- print(" Remote Control Turtle Script ")
- print("===================================")
- -- Setup Turtle Name
- my_name = setup_turtle_name()
- print("-----------------------------------")
- print("My Name: " .. my_name)
- print("Owner: " .. owner_name)
- -- Check for ChatBox
- if not chat then
- printError("ChatBox peripheral NOT FOUND.")
- printError("Chat command functionality will be disabled.")
- else
- print("ChatBox peripheral: Found")
- end
- -- Check for EndAutomata
- if not automata then
- printWarn("EndAutomata peripheral NOT FOUND.")
- else
- print("EndAutomata peripheral: Found")
- end
- print("-----------------------------------")
- print("Listening for chat commands...")
- --------------------------------------------------------------------------------
- -- MAIN EVENT LOOP
- --------------------------------------------------------------------------------
- while true do
- local event_data = {os.pullEvent()}
- local event_type = event_data[1]
- if event_type == "chat" then
- if chat then -- Only process if chatBox is available
- local sender_name = event_data[2]
- local message = event_data[3]
- -- local uuid = event_data[4]
- -- local isHidden = event_data[5]
- -- Parse message format: @target_name command_text
- local target_name_match, command_text_match = message:match("^@([^%s]+)%s+(.+)$")
- if target_name_match then
- if target_name_match == my_name or target_name_match == "all" then
- if sender_name == owner_name then
- -- Command from owner, execute it
- execute_command(command_text_match, sender_name)
- else
- -- Command from someone else, send a scare message
- local random_index = math.random(#scare_messages)
- local scare_msg_template = scare_messages[random_index]
- local final_scare_msg = scare_msg_template
- -- If message template ends with ": ", append sender's name
- if scare_msg_template:sub(-2) == ": " then
- final_scare_msg = final_scare_msg .. sender_name
- end
- say(sender_name .. ", " .. final_scare_msg)
- say("This unit is under exclusive control. Please do not interfere.")
- end
- end
- end
- end
- elseif event_type == "terminate" then
- say("Shutting down...")
- print("Termination signal received. Exiting.")
- break
- end
- -- Add other event handlers here if needed (e.g., "turtle_inventory")
- end
- print("Script ended.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement