Advertisement
Myros27

loaderBot

May 27th, 2025 (edited)
630
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 11.99 KB | None | 0 0
  1. --[[
  2.     loaderBot Script v1.0
  3.     - Downloads and runs a specific script from Pastebin on startup.
  4.     - Responds to "@all" with its name.
  5.     - Handles the "@loader ***" command to run a specified script (default: cloud.lua) with arguments.
  6. ]]
  7.  
  8. --#region Configuration
  9. local CHAT_BOX_PERIPHERAL_NAME = "chatBox" -- Set to your chat box peripheral name if different
  10.  
  11. local COMMAND_PREFIX = "@loader"
  12. local CHAT_BOT_NAME = "loaderBot"
  13. local CHAT_BOT_BRACKETS = "[]"
  14. local CHAT_BOT_BRACKET_COLOR = "&b" -- Light Blue for brackets
  15.  
  16. -- Startup Script Configuration
  17. local PASTEBIN_SCRIPT_ID = "gG1K1c8D"  -- The Pastebin ID (e.g., XyZ123AB) for the script to download and run at startup.
  18. local PASTEBIN_TARGET_FILENAME = "startup_prog.lua" -- The filename to save the downloaded startup script as.
  19.                                                   -- If the startup script IS cloud.lua, you can set this to "cloud.lua".
  20.  
  21. -- @loader Command Configuration
  22. local COMMAND_HANDLER_SCRIPT = "cloud.lua -t80x30" -- The script that the "@loader ***" command will execute.
  23.  
  24. local DEBUG_MODE = false -- Set to true for detailed logging
  25. local DEBUG_LOG_FILE = "loaderbot.log"
  26. --#endregion
  27.  
  28. --#region Peripherals
  29. local chatBox = peripheral.find(CHAT_BOX_PERIPHERAL_NAME)
  30. --#endregion
  31.  
  32. --#region Debug Logger
  33. local function logDebug(message)
  34.     if not DEBUG_MODE then return end
  35.     local logMessage = string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), message)
  36.     local file, err = fs.open(DEBUG_LOG_FILE, "a")
  37.     if file then
  38.         file.write(logMessage)
  39.         file.close()
  40.     else
  41.         print("DEBUG LOG ERROR: Could not open " .. DEBUG_LOG_FILE .. ": " .. (err or "unknown error"))
  42.     end
  43. end
  44. --#endregion
  45.  
  46. --#region Minecraft JSON Text Component Colors
  47. local COLORS = {
  48.     BLACK = "black", DARK_BLUE = "dark_blue", DARK_GREEN = "dark_green", DARK_AQUA = "dark_aqua",
  49.     DARK_RED = "dark_red", DARK_PURPLE = "dark_purple", GOLD = "gold", GRAY = "gray",
  50.     DARK_GRAY = "dark_gray", BLUE = "blue", GREEN = "green", AQUA = "aqua", RED = "red",
  51.     LIGHT_PURPLE = "light_purple", YELLOW = "yellow", WHITE = "white", RESET = "reset"
  52. }
  53. --#endregion
  54.  
  55. --#region Helper Functions
  56. local function sendFormattedChat(messageComponents, recipientUsername)
  57.     logDebug("Attempting to send formatted chat. Recipient: " .. (recipientUsername or "ALL"))
  58.     if not chatBox then
  59.         local plainText = ""
  60.         for _, comp in ipairs(messageComponents) do plainText = plainText .. (comp.text or "") end
  61.         local noChatMsg = "[" .. CHAT_BOT_NAME .. "-NoChatBox" .. (recipientUsername and (" to " .. recipientUsername) or "") .. "] " .. plainText
  62.         print(noChatMsg)
  63.         logDebug("ChatBox not found. Printed to console: " .. noChatMsg)
  64.         return
  65.     end
  66.  
  67.     local jsonMessage = textutils.serialiseJSON(messageComponents)
  68.     if not jsonMessage then
  69.         local fallbackMsg = "Error: Could not serialize message for formatted sending."
  70.         logDebug("JSON Serialization Error. Fallback: " .. fallbackMsg .. " Data: " .. textutils.serialize(messageComponents, {max_depth=2}))
  71.         if recipientUsername then
  72.             chatBox.sendMessageToPlayer(fallbackMsg, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  73.         else
  74.             chatBox.sendMessage(fallbackMsg, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  75.         end
  76.         return
  77.     end
  78.  
  79.     local success, err
  80.     if recipientUsername then
  81.         success, err = pcall(chatBox.sendFormattedMessageToPlayer, jsonMessage, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  82.     else
  83.         success, err = pcall(chatBox.sendFormattedMessage, jsonMessage, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  84.     end
  85.  
  86.     if not success then
  87.         logDebug("Error sending formatted message: " .. (err or "Unknown error") .. ". Attempting fallback to plain text.")
  88.         local plainText = ""
  89.         for _, comp in ipairs(messageComponents) do plainText = plainText .. (comp.text or "") end
  90.         if recipientUsername then
  91.             chatBox.sendMessageToPlayer(plainText, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  92.         else
  93.             chatBox.sendMessage(plainText, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  94.         end
  95.     else
  96.         logDebug("Formatted message sent successfully.")
  97.     end
  98.     os.sleep(0.2) -- Small delay
  99. end
  100.  
  101. local function announce(messageComponents)
  102.     sendFormattedChat(messageComponents)
  103. end
  104.  
  105. -- Helper function to trim leading/trailing whitespace (Lua 5.1 compatible)
  106. local function trimString(s)
  107.     if not s then return "" end
  108.     return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
  109. end
  110. --#endregion
  111.  
  112. --#region Startup Script Execution
  113. local function runStartupScript()
  114.     logDebug("Attempting to run startup script from Pastebin...")
  115.     logDebug("Pastebin ID: " .. PASTEBIN_SCRIPT_ID .. ", Target Filename: " .. PASTEBIN_TARGET_FILENAME)
  116.  
  117.     if PASTEBIN_SCRIPT_ID == "PUT_PASTEBIN_ID_HERE" or PASTEBIN_SCRIPT_ID == "" then
  118.         logDebug("PASTEBIN_SCRIPT_ID is not set. Skipping Pastebin script execution.")
  119.         print("Warning: PASTEBIN_SCRIPT_ID is not configured. Startup script will not be run.")
  120.         announce({{text="Startup script not configured (Pastebin ID missing).", color=COLORS.YELLOW}})
  121.         return
  122.     end
  123.    
  124.     local successPCall, shellRunResultOrError = pcall(function()
  125.         local ranOk = shell.run("pastebin", "run", PASTEBIN_SCRIPT_ID, PASTEBIN_TARGET_FILENAME)
  126.         if not ranOk then
  127.             error("pastebin command reported failure (e.g. ID not found, or downloaded script failed).")
  128.         end
  129.         return true
  130.     end)
  131.  
  132.     if successPCall and shellRunResultOrError == true then
  133.         logDebug("Startup script '" .. PASTEBIN_TARGET_FILENAME .. "' (ID: " .. PASTEBIN_SCRIPT_ID .. ") initiated successfully via pastebin.")
  134.         announce({{text="Startup script ", color=COLORS.GREEN}, {text=PASTEBIN_TARGET_FILENAME, color=COLORS.AQUA}, {text=" initiated.", color=COLORS.GREEN}})
  135.     else
  136.         local errMsg = successPCall == false and tostring(shellRunResultOrError) or "Unknown issue with pastebin execution."
  137.         logDebug("Failed to run startup script. Error: " .. errMsg)
  138.         print("Error running startup script from Pastebin: " .. errMsg)
  139.         announce({{text="Failed to run startup script ", color=COLORS.RED}, {text=PASTEBIN_TARGET_FILENAME, color=COLORS.YELLOW}, {text=" (ID: "..PASTEBIN_SCRIPT_ID.."). Error: "..errMsg, color=COLORS.RED}})
  140.     end
  141.     logDebug("Startup script execution attempt finished.")
  142. end
  143. --#endregion
  144.  
  145. --#region Main Loop
  146. local function run()
  147.     term.clear()
  148.     term.setCursorPos(1, 1)
  149.  
  150.     if DEBUG_MODE then
  151.         local file, ferr = fs.open(DEBUG_LOG_FILE, "w")
  152.         if file then
  153.             file.write(string.format("[%s] %s Script Initializing - DEBUG MODE ENABLED\n", os.date("%Y-%m-%d %H:%M:%S"), CHAT_BOT_NAME))
  154.             file.write("======================================================================\n")
  155.             file.close()
  156.         else
  157.             print("DEBUG LOG ERROR: Could not clear/initialize " .. DEBUG_LOG_FILE .. ": " .. (ferr or "unknown error"))
  158.         end
  159.     end
  160.     logDebug("Script run() started.")
  161.  
  162.     if not chatBox then
  163.         logDebug("WARNING: Chat Box peripheral ('" .. CHAT_BOX_PERIPHERAL_NAME .. "') not found! Chat features will be printed to console only.")
  164.         print("WARNING: Chat Box ('" .. CHAT_BOX_PERIPHERAL_NAME .. "') not found! Chat features will be limited.")
  165.     end
  166.  
  167.     runStartupScript()
  168.    
  169.     logDebug(CHAT_BOT_NAME .. " is now fully online.")
  170.     print(CHAT_BOT_NAME .. " online. Awaiting commands.")
  171.     if chatBox then
  172.         announce({{text = CHAT_BOT_NAME .. " online!", color = COLORS.GREEN, bold = true}})
  173.         announce({{text = "Type '", color = COLORS.GRAY}, {text = "@all", color = COLORS.AQUA},
  174.                   {text = "' or '", color = COLORS.GRAY}, {text = COMMAND_PREFIX .. " <arguments>", color = COLORS.AQUA},
  175.                   {text = "' to interact.", color = COLORS.GRAY}})
  176.     end
  177.  
  178.     local lowerCommandPrefix = string.lower(COMMAND_PREFIX)
  179.  
  180.     while true do
  181.         local eventData = {os.pullEvent()}
  182.         local eventType = eventData[1]
  183.         logDebug("Event: " .. eventType .. " Data: " .. textutils.serialize(eventData, {compact = true, max_depth = 2}))
  184.  
  185.         if eventType == "chat" then
  186.             local eUsername, eMessage, _, eIsHidden = eventData[2], eventData[3], eventData[4], eventData[5]
  187.             if not eIsHidden and eMessage then
  188.                 local lowerMessage = string.lower(eMessage)
  189.  
  190.                 if lowerMessage == "@all" then
  191.                     logDebug("@all command received from " .. eUsername)
  192.                     announce({{text = CHAT_BOT_NAME .. " present!", color = COLORS.AQUA}})
  193.                
  194.                 elseif string.sub(lowerMessage, 1, #lowerCommandPrefix) == lowerCommandPrefix then
  195.                     local commandPart = string.sub(eMessage, 1, #COMMAND_PREFIX)
  196.                     local tailingPart = string.sub(eMessage, #COMMAND_PREFIX + 1)
  197.  
  198.                     if commandPart == COMMAND_PREFIX and (tailingPart == "" or string.sub(tailingPart, 1, 1) == " ") then
  199.                         local argsString = trimString(tailingPart) -- MODIFIED LINE
  200.  
  201.                         logDebug(COMMAND_PREFIX .. " command from " .. eUsername .. ". Args: '" .. argsString .. "'. Target: " .. COMMAND_HANDLER_SCRIPT)
  202.                         announce({{text="Executing: ", color=COLORS.YELLOW}, {text=COMMAND_HANDLER_SCRIPT .. (argsString == "" and "" or (" " .. argsString)), color=COLORS.AQUA}})
  203.  
  204.                         local argsTable = {}
  205.                         if argsString ~= "" then
  206.                             for arg in string.gmatch(argsString, "[^%s]+") do
  207.                                 table.insert(argsTable, arg)
  208.                             end
  209.                         end
  210.  
  211.                         local successPCall, shellRunResultOrError
  212.                         if #argsTable > 0 then
  213.                             successPCall, shellRunResultOrError = pcall(shell.run, COMMAND_HANDLER_SCRIPT, table.unpack(argsTable))
  214.                         else
  215.                             successPCall, shellRunResultOrError = pcall(shell.run, COMMAND_HANDLER_SCRIPT)
  216.                         end
  217.                        
  218.                         if successPCall then
  219.                             if shellRunResultOrError == true then
  220.                                 logDebug(COMMAND_HANDLER_SCRIPT .. " executed successfully.")
  221.                                 announce({{text=COMMAND_HANDLER_SCRIPT .. " command finished.", color=COLORS.GREEN}})
  222.                             else
  223.                                 logDebug(COMMAND_HANDLER_SCRIPT .. " executed but reported an error or non-zero exit code.")
  224.                                 announce({{text=COMMAND_HANDLER_SCRIPT .. " command finished with an issue.", color=COLORS.YELLOW}})
  225.                             end
  226.                         else
  227.                             logDebug("Error trying to execute " .. COMMAND_HANDLER_SCRIPT .. ": " .. tostring(shellRunResultOrError))
  228.                             announce({{text="Error executing '", color=COLORS.RED}, {text=COMMAND_HANDLER_SCRIPT, color=COLORS.YELLOW},
  229.                                       {text="'. Is it available? Error: ", color=COLORS.RED}, {text=tostring(shellRunResultOrError), color=COLORS.YELLOW}})
  230.                         end
  231.                     end
  232.                 end
  233.             end
  234.         elseif eventType == "terminate" then
  235.             logDebug("Terminate event received. Shutting down.")
  236.             if chatBox then
  237.                 announce({{text = CHAT_BOT_NAME .. " shutting down...", color = COLORS.YELLOW, bold = true}})
  238.             end
  239.             logDebug("Script terminated.")
  240.             print(CHAT_BOT_NAME .. " terminated.")
  241.             return
  242.         end
  243.     end
  244. end
  245.  
  246. run()
  247. --#endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement