Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- loaderBot Script v1.0
- - Downloads and runs a specific script from Pastebin on startup.
- - Responds to "@all" with its name.
- - Handles the "@loader ***" command to run a specified script (default: cloud.lua) with arguments.
- ]]
- --#region Configuration
- local CHAT_BOX_PERIPHERAL_NAME = "chatBox" -- Set to your chat box peripheral name if different
- local COMMAND_PREFIX = "@loader"
- local CHAT_BOT_NAME = "loaderBot"
- local CHAT_BOT_BRACKETS = "[]"
- local CHAT_BOT_BRACKET_COLOR = "&b" -- Light Blue for brackets
- -- Startup Script Configuration
- local PASTEBIN_SCRIPT_ID = "gG1K1c8D" -- The Pastebin ID (e.g., XyZ123AB) for the script to download and run at startup.
- local PASTEBIN_TARGET_FILENAME = "startup_prog.lua" -- The filename to save the downloaded startup script as.
- -- If the startup script IS cloud.lua, you can set this to "cloud.lua".
- -- @loader Command Configuration
- local COMMAND_HANDLER_SCRIPT = "cloud.lua -t80x30" -- The script that the "@loader ***" command will execute.
- local DEBUG_MODE = false -- Set to true for detailed logging
- local DEBUG_LOG_FILE = "loaderbot.log"
- --#endregion
- --#region Peripherals
- local chatBox = peripheral.find(CHAT_BOX_PERIPHERAL_NAME)
- --#endregion
- --#region Debug Logger
- local function logDebug(message)
- if not DEBUG_MODE then return end
- local logMessage = string.format("[%s] %s\n", os.date("%Y-%m-%d %H:%M:%S"), message)
- local file, err = fs.open(DEBUG_LOG_FILE, "a")
- if file then
- file.write(logMessage)
- file.close()
- else
- print("DEBUG LOG ERROR: Could not open " .. DEBUG_LOG_FILE .. ": " .. (err or "unknown error"))
- end
- end
- --#endregion
- --#region Minecraft JSON Text Component Colors
- local COLORS = {
- BLACK = "black", DARK_BLUE = "dark_blue", DARK_GREEN = "dark_green", DARK_AQUA = "dark_aqua",
- DARK_RED = "dark_red", DARK_PURPLE = "dark_purple", GOLD = "gold", GRAY = "gray",
- DARK_GRAY = "dark_gray", BLUE = "blue", GREEN = "green", AQUA = "aqua", RED = "red",
- LIGHT_PURPLE = "light_purple", YELLOW = "yellow", WHITE = "white", RESET = "reset"
- }
- --#endregion
- --#region Helper Functions
- local function sendFormattedChat(messageComponents, recipientUsername)
- logDebug("Attempting to send formatted chat. Recipient: " .. (recipientUsername or "ALL"))
- if not chatBox then
- local plainText = ""
- for _, comp in ipairs(messageComponents) do plainText = plainText .. (comp.text or "") end
- local noChatMsg = "[" .. CHAT_BOT_NAME .. "-NoChatBox" .. (recipientUsername and (" to " .. recipientUsername) or "") .. "] " .. plainText
- print(noChatMsg)
- logDebug("ChatBox not found. Printed to console: " .. noChatMsg)
- return
- end
- local jsonMessage = textutils.serialiseJSON(messageComponents)
- if not jsonMessage then
- local fallbackMsg = "Error: Could not serialize message for formatted sending."
- logDebug("JSON Serialization Error. Fallback: " .. fallbackMsg .. " Data: " .. textutils.serialize(messageComponents, {max_depth=2}))
- if recipientUsername then
- chatBox.sendMessageToPlayer(fallbackMsg, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- else
- chatBox.sendMessage(fallbackMsg, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- end
- return
- end
- local success, err
- if recipientUsername then
- success, err = pcall(chatBox.sendFormattedMessageToPlayer, jsonMessage, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- else
- success, err = pcall(chatBox.sendFormattedMessage, jsonMessage, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- end
- if not success then
- logDebug("Error sending formatted message: " .. (err or "Unknown error") .. ". Attempting fallback to plain text.")
- local plainText = ""
- for _, comp in ipairs(messageComponents) do plainText = plainText .. (comp.text or "") end
- if recipientUsername then
- chatBox.sendMessageToPlayer(plainText, recipientUsername, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- else
- chatBox.sendMessage(plainText, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- end
- else
- logDebug("Formatted message sent successfully.")
- end
- os.sleep(0.2) -- Small delay
- end
- local function announce(messageComponents)
- sendFormattedChat(messageComponents)
- end
- -- Helper function to trim leading/trailing whitespace (Lua 5.1 compatible)
- local function trimString(s)
- if not s then return "" end
- return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
- end
- --#endregion
- --#region Startup Script Execution
- local function runStartupScript()
- logDebug("Attempting to run startup script from Pastebin...")
- logDebug("Pastebin ID: " .. PASTEBIN_SCRIPT_ID .. ", Target Filename: " .. PASTEBIN_TARGET_FILENAME)
- if PASTEBIN_SCRIPT_ID == "PUT_PASTEBIN_ID_HERE" or PASTEBIN_SCRIPT_ID == "" then
- logDebug("PASTEBIN_SCRIPT_ID is not set. Skipping Pastebin script execution.")
- print("Warning: PASTEBIN_SCRIPT_ID is not configured. Startup script will not be run.")
- announce({{text="Startup script not configured (Pastebin ID missing).", color=COLORS.YELLOW}})
- return
- end
- local successPCall, shellRunResultOrError = pcall(function()
- local ranOk = shell.run("pastebin", "run", PASTEBIN_SCRIPT_ID, PASTEBIN_TARGET_FILENAME)
- if not ranOk then
- error("pastebin command reported failure (e.g. ID not found, or downloaded script failed).")
- end
- return true
- end)
- if successPCall and shellRunResultOrError == true then
- logDebug("Startup script '" .. PASTEBIN_TARGET_FILENAME .. "' (ID: " .. PASTEBIN_SCRIPT_ID .. ") initiated successfully via pastebin.")
- announce({{text="Startup script ", color=COLORS.GREEN}, {text=PASTEBIN_TARGET_FILENAME, color=COLORS.AQUA}, {text=" initiated.", color=COLORS.GREEN}})
- else
- local errMsg = successPCall == false and tostring(shellRunResultOrError) or "Unknown issue with pastebin execution."
- logDebug("Failed to run startup script. Error: " .. errMsg)
- print("Error running startup script from Pastebin: " .. errMsg)
- 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}})
- end
- logDebug("Startup script execution attempt finished.")
- end
- --#endregion
- --#region Main Loop
- local function run()
- term.clear()
- term.setCursorPos(1, 1)
- if DEBUG_MODE then
- local file, ferr = fs.open(DEBUG_LOG_FILE, "w")
- if file then
- file.write(string.format("[%s] %s Script Initializing - DEBUG MODE ENABLED\n", os.date("%Y-%m-%d %H:%M:%S"), CHAT_BOT_NAME))
- file.write("======================================================================\n")
- file.close()
- else
- print("DEBUG LOG ERROR: Could not clear/initialize " .. DEBUG_LOG_FILE .. ": " .. (ferr or "unknown error"))
- end
- end
- logDebug("Script run() started.")
- if not chatBox then
- logDebug("WARNING: Chat Box peripheral ('" .. CHAT_BOX_PERIPHERAL_NAME .. "') not found! Chat features will be printed to console only.")
- print("WARNING: Chat Box ('" .. CHAT_BOX_PERIPHERAL_NAME .. "') not found! Chat features will be limited.")
- end
- runStartupScript()
- logDebug(CHAT_BOT_NAME .. " is now fully online.")
- print(CHAT_BOT_NAME .. " online. Awaiting commands.")
- if chatBox then
- announce({{text = CHAT_BOT_NAME .. " online!", color = COLORS.GREEN, bold = true}})
- announce({{text = "Type '", color = COLORS.GRAY}, {text = "@all", color = COLORS.AQUA},
- {text = "' or '", color = COLORS.GRAY}, {text = COMMAND_PREFIX .. " <arguments>", color = COLORS.AQUA},
- {text = "' to interact.", color = COLORS.GRAY}})
- end
- local lowerCommandPrefix = string.lower(COMMAND_PREFIX)
- while true do
- local eventData = {os.pullEvent()}
- local eventType = eventData[1]
- logDebug("Event: " .. eventType .. " Data: " .. textutils.serialize(eventData, {compact = true, max_depth = 2}))
- if eventType == "chat" then
- local eUsername, eMessage, _, eIsHidden = eventData[2], eventData[3], eventData[4], eventData[5]
- if not eIsHidden and eMessage then
- local lowerMessage = string.lower(eMessage)
- if lowerMessage == "@all" then
- logDebug("@all command received from " .. eUsername)
- announce({{text = CHAT_BOT_NAME .. " present!", color = COLORS.AQUA}})
- elseif string.sub(lowerMessage, 1, #lowerCommandPrefix) == lowerCommandPrefix then
- local commandPart = string.sub(eMessage, 1, #COMMAND_PREFIX)
- local tailingPart = string.sub(eMessage, #COMMAND_PREFIX + 1)
- if commandPart == COMMAND_PREFIX and (tailingPart == "" or string.sub(tailingPart, 1, 1) == " ") then
- local argsString = trimString(tailingPart) -- MODIFIED LINE
- logDebug(COMMAND_PREFIX .. " command from " .. eUsername .. ". Args: '" .. argsString .. "'. Target: " .. COMMAND_HANDLER_SCRIPT)
- announce({{text="Executing: ", color=COLORS.YELLOW}, {text=COMMAND_HANDLER_SCRIPT .. (argsString == "" and "" or (" " .. argsString)), color=COLORS.AQUA}})
- local argsTable = {}
- if argsString ~= "" then
- for arg in string.gmatch(argsString, "[^%s]+") do
- table.insert(argsTable, arg)
- end
- end
- local successPCall, shellRunResultOrError
- if #argsTable > 0 then
- successPCall, shellRunResultOrError = pcall(shell.run, COMMAND_HANDLER_SCRIPT, table.unpack(argsTable))
- else
- successPCall, shellRunResultOrError = pcall(shell.run, COMMAND_HANDLER_SCRIPT)
- end
- if successPCall then
- if shellRunResultOrError == true then
- logDebug(COMMAND_HANDLER_SCRIPT .. " executed successfully.")
- announce({{text=COMMAND_HANDLER_SCRIPT .. " command finished.", color=COLORS.GREEN}})
- else
- logDebug(COMMAND_HANDLER_SCRIPT .. " executed but reported an error or non-zero exit code.")
- announce({{text=COMMAND_HANDLER_SCRIPT .. " command finished with an issue.", color=COLORS.YELLOW}})
- end
- else
- logDebug("Error trying to execute " .. COMMAND_HANDLER_SCRIPT .. ": " .. tostring(shellRunResultOrError))
- announce({{text="Error executing '", color=COLORS.RED}, {text=COMMAND_HANDLER_SCRIPT, color=COLORS.YELLOW},
- {text="'. Is it available? Error: ", color=COLORS.RED}, {text=tostring(shellRunResultOrError), color=COLORS.YELLOW}})
- end
- end
- end
- end
- elseif eventType == "terminate" then
- logDebug("Terminate event received. Shutting down.")
- if chatBox then
- announce({{text = CHAT_BOT_NAME .. " shutting down...", color = COLORS.YELLOW, bold = true}})
- end
- logDebug("Script terminated.")
- print(CHAT_BOT_NAME .. " terminated.")
- return
- end
- end
- end
- run()
- --#endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement