Advertisement
Myros27

RemoteTurtleAccessTool

May 17th, 2025
405
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 9.31 KB | None | 0 0
  1. -- CC-Tweaked Remote Control Turtle Script
  2. -- Player: Myros27
  3.  
  4. -- Configuration
  5. local owner_name = "Myros27"
  6. local turtle_name_file = ".turtle_name" -- Hidden file for storing the turtle's name
  7. local my_name -- Will be set during setup
  8.  
  9. -- Peripherals
  10. local chat = peripheral.find("chatBox")
  11. local automata = peripheral.find("endAutomata") -- Accessible in commands as 'automata'
  12.  
  13. -- Scare messages for unauthorized users
  14. local scare_messages = {
  15.     "Self-destruction sequence initiated!",
  16.     "Unauthorized access detected. Engaging countermeasures.",
  17.     "Warning: Tampering with this unit is ill-advised.",
  18.     "My circuits are tingling with... annoyance. Please desist.",
  19.     "Access denied. This unit only responds to its registered master.",
  20.     "SECURITY ALERT! Unauthorized command attempt by: " -- Appends sender's name
  21. }
  22.  
  23. -- Cooldown for chat messages (seconds)
  24. local last_message_time = 0
  25. local chat_cooldown = 1.1 -- Slightly above 1s to be safe with ChatBox API
  26.  
  27. --------------------------------------------------------------------------------
  28. -- HELPER FUNCTIONS
  29. --------------------------------------------------------------------------------
  30.  
  31. -- Custom printWarn if not available (CC:Tweaked usually has it)
  32. if not printWarn then
  33.     _G.printWarn = function(...)
  34.         local old_color_fg, old_color_bg = term.getTextColor(), term.getBackgroundColor()
  35.         term.setTextColor(colors.orange)
  36.         io.stderr:write(table.concat({...}, "\t"))
  37.         io.stderr:write("\n")
  38.         term.setTextColor(old_color_fg)
  39.         term.setBackgroundColor(old_color_bg)
  40.     end
  41. end
  42.  
  43. -- Save turtle name to file
  44. local function save_turtle_name(name_to_save)
  45.     local file = fs.open(turtle_name_file, "w")
  46.     if file then
  47.         file.write(name_to_save)
  48.         file.close()
  49.         return true
  50.     end
  51.     printError("Failed to write turtle name to " .. turtle_name_file)
  52.     return false
  53. end
  54.  
  55. -- Load turtle name from file
  56. local function load_turtle_name()
  57.     if fs.exists(turtle_name_file) then
  58.         local file = fs.open(turtle_name_file, "r")
  59.         if file then
  60.             local name_from_file = file.readLine()
  61.             file.close()
  62.             -- Check not nil and not just whitespace
  63.             if name_from_file and name_from_file:gsub("%s+", "") ~= "" then
  64.                 return name_from_file:match("^%s*(.-)%s*$") -- Trim whitespace
  65.             end
  66.         else
  67.             printError("Failed to open " .. turtle_name_file .. " for reading.")
  68.         end
  69.     end
  70.     return nil
  71. end
  72.  
  73. -- Prompt user for turtle name if not set, and load/save it
  74. local function setup_turtle_name()
  75.     local existing_name = load_turtle_name()
  76.     if existing_name then
  77.         term.setTextColor(colors.white)
  78.         term.write("Resuming with name: ")
  79.         term.setTextColor(colors.yellow)
  80.         print(existing_name)
  81.         term.setTextColor(colors.white)
  82.         return existing_name
  83.     end
  84.  
  85.     term.setTextColor(colors.white)
  86.     term.write("Enter a unique name for this turtle: ")
  87.     term.setTextColor(colors.yellow)
  88.     local new_name_input = read()
  89.     term.setTextColor(colors.white)
  90.  
  91.     if new_name_input and new_name_input:gsub("%s+", "") ~= "" then
  92.         new_name_input = new_name_input:match("^%s*(.-)%s*$") -- Trim
  93.         if save_turtle_name(new_name_input) then
  94.             print("Turtle name set to: " .. new_name_input)
  95.             return new_name_input
  96.         else
  97.             printError("Failed to save turtle name. Using 'default_turtle'.")
  98.             return "default_turtle" -- Fallback
  99.         end
  100.     else
  101.         print("No valid name entered. Using 'default_turtle'.")
  102.         return "default_turtle" -- Fallback
  103.     end
  104. end
  105.  
  106. -- Send a message to global chat via ChatBox
  107. local function say(message_content)
  108.     if not my_name then my_name = "UnnamedTurtle" end -- Safety net
  109.  
  110.     if chat then
  111.         local current_time = os.time()
  112.         local time_since_last = current_time - last_message_time
  113.        
  114.         if time_since_last < chat_cooldown then
  115.             local wait_duration = chat_cooldown - time_since_last
  116.             if wait_duration > 0 then
  117.                 -- Optional: print("Chat cooldown: waiting " .. string.format("%.2f", wait_duration) .. "s")
  118.                 os.sleep(wait_duration)
  119.             end
  120.         end
  121.        
  122.         chat.sendMessage(message_content, my_name) -- Turtle's name as prefix
  123.         last_message_time = os.time()
  124.     else
  125.         local prefix = "[" .. my_name
  126.         if not chat then prefix = prefix .. " Chat Disabled" end
  127.         prefix = prefix .. "]"
  128.         print(prefix .. " " .. message_content)
  129.     end
  130. end
  131.  
  132. -- Format results of command execution for chat output
  133. local function format_command_output(...)
  134.     local results_pack = {...}
  135.     local n = select("#", ...)
  136.  
  137.     if n == 0 then
  138.         return "Command executed (produced no return values)."
  139.     end
  140.  
  141.     local parts = {}
  142.     for i = 1, n do
  143.         local v = results_pack[i]
  144.         if v == nil then
  145.             table.insert(parts, "nil")
  146.         elseif type(v) == "table" then
  147.             table.insert(parts, textutils.serialize(v))
  148.         elseif type(v) == "function" then
  149.             table.insert(parts, "function:"..tostring(v))
  150.         else
  151.             table.insert(parts, tostring(v))
  152.         end
  153.     end
  154.     return "Output: " .. table.concat(parts, ", ")
  155. end
  156.  
  157. -- Execute a Lua command string
  158. local function execute_command(command_str, sender_name)
  159.     say("Received command from " .. sender_name .. ": " .. command_str)
  160.    
  161.     -- The environment for the loaded command will be _G (this script's global environment)
  162.     local func_env = _G
  163.     local func, compile_err = load(command_str, "ChatCmd@" .. my_name, "t", func_env)
  164.  
  165.     if not func then
  166.         say("Compilation Error for command from " .. sender_name .. ": " .. tostring(compile_err))
  167.         return
  168.     end
  169.  
  170.     local pcall_results = {pcall(func)}
  171.     local success = pcall_results[1]
  172.     table.remove(pcall_results, 1) -- Remove status, keep only actual results or error message
  173.  
  174.     if success then
  175.         say(format_command_output(table.unpack(pcall_results)))
  176.     else
  177.         say("Execution Error for command from " .. sender_name .. ": " .. tostring(pcall_results[1]))
  178.     end
  179. end
  180.  
  181. --------------------------------------------------------------------------------
  182. -- INITIALIZATION
  183. --------------------------------------------------------------------------------
  184.  
  185. term.clear()
  186. term.setCursorPos(1,1)
  187. print("===================================")
  188. print("   Remote Control Turtle Script    ")
  189. print("===================================")
  190.  
  191. -- Setup Turtle Name
  192. my_name = setup_turtle_name()
  193. print("-----------------------------------")
  194. print("My Name: " .. my_name)
  195. print("Owner: " .. owner_name)
  196.  
  197. -- Check for ChatBox
  198. if not chat then
  199.     printError("ChatBox peripheral NOT FOUND.")
  200.     printError("Chat command functionality will be disabled.")
  201. else
  202.     print("ChatBox peripheral: Found")
  203. end
  204.  
  205. -- Check for EndAutomata
  206. if not automata then
  207.     printWarn("EndAutomata peripheral NOT FOUND.")
  208. else
  209.     print("EndAutomata peripheral: Found")
  210. end
  211. print("-----------------------------------")
  212. print("Listening for chat commands...")
  213.  
  214. --------------------------------------------------------------------------------
  215. -- MAIN EVENT LOOP
  216. --------------------------------------------------------------------------------
  217.  
  218. while true do
  219.     local event_data = {os.pullEvent()}
  220.     local event_type = event_data[1]
  221.  
  222.     if event_type == "chat" then
  223.         if chat then -- Only process if chatBox is available
  224.             local sender_name = event_data[2]
  225.             local message = event_data[3]
  226.             -- local uuid = event_data[4]
  227.             -- local isHidden = event_data[5]
  228.  
  229.             -- Parse message format: @target_name command_text
  230.             local target_name_match, command_text_match = message:match("^@([^%s]+)%s+(.+)$")
  231.  
  232.             if target_name_match then
  233.                 if target_name_match == my_name or target_name_match == "all" then
  234.                     if sender_name == owner_name then
  235.                         -- Command from owner, execute it
  236.                         execute_command(command_text_match, sender_name)
  237.                     else
  238.                         -- Command from someone else, send a scare message
  239.                         local random_index = math.random(#scare_messages)
  240.                         local scare_msg_template = scare_messages[random_index]
  241.                         local final_scare_msg = scare_msg_template
  242.                        
  243.                         -- If message template ends with ": ", append sender's name
  244.                         if scare_msg_template:sub(-2) == ": " then
  245.                             final_scare_msg = final_scare_msg .. sender_name
  246.                         end
  247.  
  248.                         say(sender_name .. ", " .. final_scare_msg)
  249.                         say("This unit is under exclusive control. Please do not interfere.")
  250.                     end
  251.                 end
  252.             end
  253.         end
  254.     elseif event_type == "terminate" then
  255.         say("Shutting down...")
  256.         print("Termination signal received. Exiting.")
  257.         break
  258.     end
  259.     -- Add other event handlers here if needed (e.g., "turtle_inventory")
  260. end
  261.  
  262. print("Script ended.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement