Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- DisenchantBot v1.1 - Removed parallel.call
- Implements the disenchanting loop as specified, using main event loop for cycle management.
- ]]
- --#region Configuration
- local CHAT_BOX_PERIPHERAL_NAME = "chatBox"
- local COMMAND_PREFIX = "@disenchant"
- local CHAT_BOT_NAME = "DisenchantBot"
- local CHAT_BOT_BRACKETS = "[]"
- local CHAT_BOT_BRACKET_COLOR = "&3" -- Cyan
- local DEBUG_LOGGING_ENABLED = true
- local LOG_FILE_NAME = "disenchant.log"
- --#endregion
- --#region Global State
- local chatBox = nil
- local chatBoxFunctional = true
- local isDisenchantRunning = false
- local fuelWarningSent = false
- --#endregion
- --#region Logger Setup
- local function writeToLogFile(message) if not DEBUG_LOGGING_ENABLED then return end; local f,e=fs.open(LOG_FILE_NAME,"a"); if f then f.write(string.format("[%s] %s\n",os.date("%Y-%m-%d %H:%M:%S"),message));f.close() else print("LOG ERR: "..tostring(e))end end
- local function botLog(msg)local fm="["..CHAT_BOT_NAME.."-Debug] "..msg; print(fm); writeToLogFile(fm)end
- local function moveLog(msg)local fm="[MoveLib-Debug] "..msg; print(fm); writeToLogFile(fm)end
- --#endregion
- --#region Movement Library Code (Integrated - Assumed same as v1.7 from DefragBot)
- local AUTOMATA_PERIPHERAL_NAME="endAutomata";local POSITION_FILE="turtle_pos.json";local REFUEL_SLOT=16;local FUEL_ITEM_NAME_PART="coal";local automata=nil;local current_pos={x=nil,y=nil,z=nil};local current_dir=nil;local DIR_VECTORS={[0]={x=0,y=0,z=1},[1]={x=1,y=0,z=0},[2]={x=0,y=0,z=-1},[3]={x=-1,y=0,z=0}};local DIR_NAMES={[0]="North (+Z)",[1]="East (+X)",[2]="South (-Z)",[3]="West (-X)"};local function savePosition()if current_pos.x==nil or current_dir==nil then moveLog("No save, state unknown.");return end;local d={x=current_pos.x,y=current_pos.y,z=current_pos.z,dir=current_dir};local f,e=fs.open(POSITION_FILE,"w");if f then f.write(textutils.serialiseJSON(d));f.close();moveLog("Pos saved: X:"..d.x.." Y:"..d.y.." Z:"..d.z.." Dir:"..(DIR_NAMES[d.dir]or"Unk"))else moveLog("Err save pos: "..(e or"unk"))end end;local function loadPosition()if fs.exists(POSITION_FILE)then local f,e=fs.open(POSITION_FILE,"r");if f then local sD=f.readAll();f.close();local s,d=pcall(textutils.unserialiseJSON,sD);if s and d and d.x~=nil and d.y~=nil and d.z~=nil and d.dir~=nil then current_pos.x=d.x;current_pos.y=d.y;current_pos.z=d.z;current_dir=d.dir;moveLog("Pos loaded: X:"..current_pos.x.." Y:"..current_pos.y.." Z:"..current_pos.z.." Dir:"..(DIR_NAMES[current_dir]or"Unk"));return true else moveLog("Fail parse pos file: "..tostring(d))end else moveLog("Err open pos file: "..(e or"unk"))end else moveLog("Pos file not found.")end;return false end;local function dirNameToNumber(n)n=string.lower(n or"");if n=="n"or n=="north"then return 0 elseif n=="e"or n=="east"then return 1 elseif n=="s"or n=="south"then return 2 elseif n=="w"or n=="west"then return 3 end;moveLog("Warn: Invalid dir '"..(n or"nil").."'. Default N.");return 0 end;local function turnLeft()if current_dir==nil then moveLog("No turn: dir unk.");return false end;if turtle.turnLeft()then current_dir=(current_dir-1+4)%4;moveLog("Left. Dir:"..(DIR_NAMES[current_dir]or"Unk"));savePosition();return true else moveLog("Fail L turn.");return false end end;local function turnRight()if current_dir==nil then moveLog("No turn: dir unk.");return false end;if turtle.turnRight()then current_dir=(current_dir+1)%4;moveLog("Right. Dir:"..(DIR_NAMES[current_dir]or"Unk"));savePosition();return true else moveLog("Fail R turn.");return false end end;local function turnAround()if current_dir==nil then moveLog("No turn around: dir unk.");return false end;moveLog("Turn around...");if turnRight()and turnRight()then moveLog("Around. Dir:"..(DIR_NAMES[current_dir]or"Unk"));return true else moveLog("Fail turn around.");return false end end;local function forward()if current_pos.x==nil then moveLog("No move: pos unk.");return false end;if turtle.getFuelLevel()<1 and turtle.getFuelLimit()~=0 then moveLog("Fwd: <1 fuel.");return false end;if turtle.forward()then local v=DIR_VECTORS[current_dir];current_pos.x=current_pos.x+v.x;current_pos.y=current_pos.y+v.y;current_pos.z=current_pos.z+v.z;moveLog("Fwd. Pos: X:"..current_pos.x.." Y:"..current_pos.y.." Z:"..current_pos.z);savePosition();return true else moveLog("Fail fwd (block).");return false end end;local function back()if current_pos.x==nil then moveLog("No move: pos unk.");return false end;if turtle.getFuelLevel()<1 and turtle.getFuelLimit()~=0 then moveLog("Back: <1 fuel.");return false end;if turtle.back()then local v=DIR_VECTORS[current_dir];current_pos.x=current_pos.x-v.x;current_pos.y=current_pos.y-v.y;current_pos.z=current_pos.z-v.z;moveLog("Back. Pos: X:"..current_pos.x.." Y:"..current_pos.y.." Z:"..current_pos.z);savePosition();return true else moveLog("Fail back (block).");return false end end;local function up()if current_pos.y==nil then moveLog("No up: Y pos unk.");return false end;if turtle.getFuelLevel()<1 and turtle.getFuelLimit()~=0 then moveLog("Up: <1 fuel.");return false end;if turtle.up()then current_pos.y=current_pos.y+1;moveLog("Up. Pos: X:"..current_pos.x.." Y:"..current_pos.y.." Z:"..current_pos.z);savePosition();return true else moveLog("Fail up (block/no fuel).");return false end end;local function down()if current_pos.y==nil then moveLog("No down: Y pos unk.");return false end;if turtle.down()then current_pos.y=current_pos.y-1;moveLog("Down. Pos: X:"..current_pos.x.." Y:"..current_pos.y.." Z:"..current_pos.z);savePosition();return true else moveLog("Fail down (block).");return false end end;local function home()if not automata then automata=peripheral.find(AUTOMATA_PERIPHERAL_NAME);if not automata then moveLog("Err: EndAuto ('"..AUTOMATA_PERIPHERAL_NAME.."') miss.");return false end end;moveLog("Warp home...");local s,r=pcall(function()return automata.warpToPoint("home")end);if s and r then moveLog("Warp home OK.");current_pos.x=0;current_pos.y=0;current_pos.z=0;current_dir=0;moveLog("Pos reset home (000N).");savePosition();return true else moveLog("Fail warp home: "..tostring(r or"pcall err"));return false end end;local function refuel()moveLog("Refuel...");turtle.select(REFUEL_SLOT);local iBFS=turtle.getItemCount(REFUEL_SLOT);local iD=turtle.getItemDetail(REFUEL_SLOT);local iN="";if iD and iD.name then iN=string.lower(iD.name)else moveLog("Fuel slot "..REFUEL_SLOT.." empty/no name.")end;if iBFS>0 and string.find(iN,FUEL_ITEM_NAME_PART)then moveLog("Refuel from slot "..REFUEL_SLOT.." ("..(iD.name or"Unk Fuel").." x"..iBFS..")");if turtle.refuel(0)then local iAFS=turtle.getItemCount(REFUEL_SLOT);local cI=iBFS-iAFS;if cI>0 then moveLog("Refueled OK. Consumed "..cI.." "..(iD.name or"fuel")..".")else moveLog("Refueled, 0 consumed. Fuel: "..turtle.getFuelLevel())end else moveLog("turtle.refuel(0) fail. Fuel: "..turtle.getFuelLevel())end elseif iBFS>0 then moveLog("Item in fuel slot not fuel: "..(iD and iD.name or"Unk"))else moveLog("Fuel slot "..REFUEL_SLOT.." init empty.")end;local iTS=64-turtle.getItemCount(REFUEL_SLOT);local sTC=0;if iTS>0 then moveLog("Suck "..iTS.." to replenish fuel slot...");for _=1,iTS do if turtle.getItemCount(REFUEL_SLOT)>=64 then break end;local cSD=turtle.getItemDetail(REFUEL_SLOT);local cSN="";if cSD and cSD.name then cSN=string.lower(cSD.name)end;if turtle.getItemCount(REFUEL_SLOT)>0 and not string.find(cSN,FUEL_ITEM_NAME_PART)then moveLog("Slot "..REFUEL_SLOT.." has non-fuel ("..(cSD.name or"Unk").."). Stop suck.");break end;if turtle.suck()then sTC=sTC+1 else moveLog("Fail suck/chest empty after "..sTC.." items.");break end;sleep(0.1)end;if sTC>0 then moveLog("Sucked "..sTC.." items to replenish.")end else moveLog("Fuel slot full/non-fuel, no suck.")end;moveLog("Refuel finish. Fuel: "..turtle.getFuelLevel());return true end;local function setPos(x,y,z,dir)if type(x)~="number"or type(y)~="number"or type(z)~="number"then moveLog("Err: setPos xyz num.");return false end;current_pos.x=x;current_pos.y=y;current_pos.z=z;if type(dir)=="number"then current_dir=dir%4 else current_dir=dirNameToNumber(dir)end;moveLog("Pos set: X:"..x.." Y:"..y.." Z:"..z.." Dir:"..(DIR_NAMES[current_dir]or"Unk"));savePosition();return true end;local function turnToDir(td)if current_dir==nil then moveLog("No turnToDir: dir unk.");return false end;if current_dir==td then return true end;moveLog("Turn to dir: "..(DIR_NAMES[td]or"Unk"));local df=(td-current_dir+4)%4;if df==1 then return turnRight()elseif df==2 then return turnAround()elseif df==3 then return turnLeft()end;return false end;local function moveTo(tx,ty,tz,tdir)if current_pos.x==nil then moveLog("No moveTo: pos unk.");return false end;if turtle.getFuelLevel()<10 and turtle.getFuelLimit()~=0 then if ty>current_pos.y then moveLog("moveTo: Low fuel ("..turtle.getFuelLevel()..") need up.")end end;moveLog(string.format("MoveTo: Tgt X%s Y%s Z%s Dir%s",tostring(tx),tostring(ty),tostring(tz),tostring(tdir)));local tdn;if type(tdir)=="number"then tdn=tdir%4 else tdn=dirNameToNumber(tdir)end;local att=0;local max_att=100;local max_stuck_ax=3;while(current_pos.x~=tx or current_pos.y~=ty or current_pos.z~=tz)and att<max_att do att=att+1;local moved=false;local cur_ax_stuck=0;if current_pos.y<ty then if up()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block UP("..cur_ax_stuck..")");if(current_pos.x~=tx or current_pos.z~=tz)and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir(math.random(0,3))and forward()then moved=true end else moveLog("moveTo: Stuck Y(up). Abort Y.");ty=current_pos.y end end elseif current_pos.y>ty then if down()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block DOWN("..cur_ax_stuck..")");if(current_pos.x~=tx or current_pos.z~=tz)and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir(math.random(0,3))and forward()then moved=true end else moveLog("moveTo: Stuck Y(down). Abort Y.");ty=current_pos.y end end end;if moved then goto continue_main_loop end;cur_ax_stuck=0;if current_pos.x<tx then if turnToDir(1)and forward()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block EAST("..cur_ax_stuck..")");if current_pos.z~=tz and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir((math.random(0,1)*2))and forward()then moved=true end else moveLog("moveTo: Stuck X(east). Abort X.");tx=current_pos.x end end elseif current_pos.x>tx then if turnToDir(3)and forward()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block WEST("..cur_ax_stuck..")");if current_pos.z~=tz and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir((math.random(0,1)*2))and forward()then moved=true end else moveLog("moveTo: Stuck X(west). Abort X.");tx=current_pos.x end end end;if moved then goto continue_main_loop end;cur_ax_stuck=0;if current_pos.z<tz then if turnToDir(0)and forward()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block NORTH("..cur_ax_stuck..")");if current_pos.x~=tx and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir((math.random(0,1)*2)+1)and forward()then moved=true end else moveLog("moveTo: Stuck Z(north). Abort Z.");tz=current_pos.z end end elseif current_pos.z>tz then if turnToDir(2)and forward()then moved=true else cur_ax_stuck=cur_ax_stuck+1;moveLog("moveTo: Block SOUTH("..cur_ax_stuck..")");if current_pos.x~=tx and cur_ax_stuck<max_stuck_ax then elseif cur_ax_stuck<max_stuck_ax then if turnToDir((math.random(0,1)*2)+1)and forward()then moved=true end else moveLog("moveTo: Stuck Z(south). Abort Z.");tz=current_pos.z end end end;if moved then goto continue_main_loop end;if not moved then moveLog("moveTo: No move. Att: "..att);if cur_ax_stuck>=max_stuck_ax then break end end;::continue_main_loop::;sleep(0.05)end;if att>=max_att then moveLog("moveTo: Max att.")end;if not turnToDir(tdn)then moveLog("moveTo: Fail final turn.")end;local s=current_pos.x==tx and current_pos.y==ty and current_pos.z==tz and current_dir==tdn;if s then moveLog("moveTo: OK.")else moveLog(string.format("moveTo: Finish. Pos X%s Y%s Z%s Dir%s.",tostring(current_pos.x),tostring(current_pos.y),tostring(current_pos.z),(DIR_NAMES[current_dir]or"Unk")))end;return s end;local function initMoveLibrary()moveLog("Init MoveLib...");automata=peripheral.find(AUTOMATA_PERIPHERAL_NAME);if not automata then moveLog("CRIT WARN: EndAuto ('"..AUTOMATA_PERIPHERAL_NAME.."') miss. Home warp fail.")end;if not loadPosition()then moveLog("Pos unk/load fail. Warp home & set default.");if home()then moveLog("Init home OK.")else moveLog("CRIT: Fail init home. Pos unk.");current_pos.x=nil;current_pos.y=nil;current_pos.z=nil;current_dir=nil end end;moveLog("MoveLib Init. Pos: X:"..tostring(current_pos.x).." Y:"..tostring(current_pos.y).." Z:"..tostring(current_pos.z).." Dir:"..(current_dir and DIR_NAMES[current_dir]or"Unk"))end;local function getPosition()return current_pos end;local function getDirection()return current_dir end;local function getDirectionName()return current_dir and DIR_NAMES[current_dir]or"Unknown"end;local ml={l=turnLeft,turnLeft=turnLeft,r=turnRight,turnRight=turnRight,f=forward,forward=forward,b=back,back=back,a=turnAround,turnAround=turnAround,u=up,up=up,d=down,down=down,h=home,home=home,refuel=refuel,setPos=setPos,m=moveTo,moveTo=moveTo,getPosition=getPosition,getDirection=getDirection,getDirectionName=getDirectionName,init=initMoveLibrary};initMoveLibrary();
- --#endregion End of Integrated Movement Library
- --#region DisenchantBot Peripherals and Helpers
- local function sendFormattedChat(messageComponents)
- local plainText = ""
- if type(messageComponents) == "table" then
- for _,c_comp in ipairs(messageComponents) do
- plainText = plainText .. (type(c_comp) == "table" and c_comp.text or tostring(c_comp) or "")
- end
- elseif messageComponents ~= nil then plainText = tostring(messageComponents)
- else plainText = "nil_message_components_to_sendFormattedChat" end
- if not chatBoxFunctional or not chatBox then
- botLog("[NoChat] " .. plainText);
- return false
- end
- local jsonMessage_success, jsonMessage = pcall(textutils.serialiseJSON, messageComponents)
- if not jsonMessage_success then
- botLog("!!! textutils.serialiseJSON FAILED: " .. tostring(jsonMessage) .. " -- Original: " .. textutils.serialize(messageComponents,{compact=true,max_depth=2}))
- print("ERROR: Could not serialize chat message!"); return false
- end
- local peripheral_call_success, peripheral_error = pcall(function()
- return chatBox.sendFormattedMessage(jsonMessage, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
- end)
- if not peripheral_call_success then
- botLog("!!! chatBox.sendFormattedMessage FAILED: " .. tostring(peripheral_error) .. " -- JSON was: " .. jsonMessage)
- print("ERROR: Failed to send formatted message via chatBox: " .. tostring(peripheral_error))
- return false
- end
- return true
- end
- local function announce(messageComponents)
- local success = sendFormattedChat(messageComponents)
- if not success then
- botLog("Announce: sendFormattedChat failed for: " .. textutils.serialize(messageComponents, {compact=true, max_depth=2}))
- end
- sleep(0.3)
- return success
- end
- local COLORS={GOLD="gold",AQUA="aqua",GRAY="gray",RED="red",GREEN="green",YELLOW="yellow",WHITE="white",DARK_RED="dark_red",DARK_GRAY="dark_gray"}
- local function critical_error_handler(message, doTurnLeft)
- announce({{text = "CRITICAL ERROR: " .. message .. " Halting " .. CHAT_BOT_NAME .. ".", c = COLORS.DARK_RED, b = true}})
- botLog("CRITICAL ERROR: " .. message)
- if doTurnLeft then
- ml.turnLeft()
- end
- isDisenchantRunning = false
- end
- local function check_stop_signal()
- if not isDisenchantRunning then
- botLog("Stop signal detected during cycle.")
- return true
- end
- sleep(0) -- Yield to allow main event loop to process commands
- return false
- end
- --#endregion
- --#region DisenchantBot Command Handlers
- local commandHandlers = {}
- commandHandlers.help = function(u,_)
- announce({{text="--- "..CHAT_BOT_NAME.." Cmds ("..COMMAND_PREFIX..") ---",c=COLORS.GOLD,b=true}})
- announce({{text=COMMAND_PREFIX.." help",c=COLORS.AQUA},{text=" - Shows this help message.",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." start",c=COLORS.AQUA},{text=" - Starts the disenchanting loop.",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." stop",c=COLORS.AQUA},{text=" - Stops the current disenchanting loop.",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." cmd <lua_code>",c=COLORS.AQUA},{text=" - Executes Lua code (e.g., ml.forward()).",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." pos",c=COLORS.AQUA},{text=" - Shows current position and direction.",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." fuel",c=COLORS.AQUA},{text=" - Shows current fuel level.",c=COLORS.GRAY}})
- announce({{text=COMMAND_PREFIX.." unstuck",c=COLORS.AQUA},{text=" - Warps home and resets position (stops current cycle).",c=COLORS.GRAY}})
- end
- commandHandlers.cmd = function(u,a)
- if #a == 0 then
- announce({{text="Usage: "..COMMAND_PREFIX.." cmd <lua_code_to_run>",c=COLORS.YELLOW}})
- announce({{text="Try '",c=COLORS.GRAY},{text=COMMAND_PREFIX.." cmd help",c=COLORS.AQUA},{text="' for more info.",c=COLORS.GRAY}})
- return
- end
- if #a == 1 and string.lower(a[1]) == "help" then
- announce({{text="--- "..COMMAND_PREFIX.." cmd Help ---",c=COLORS.GOLD,b=true}})
- announce({{text="Usage: ",c=COLORS.AQUA},{text=COMMAND_PREFIX.." cmd <lua_code_to_run>",c=COLORS.WHITE}})
- announce({{text="Executes the provided Lua code. You can use 'ml.' to access Movement Library functions.",c=COLORS.GRAY}})
- announce({{text="Examples:",c=COLORS.AQUA}})
- announce({{text=" "..COMMAND_PREFIX.." cmd ml.moveTo(0,0,0,'N')",c=COLORS.WHITE}})
- announce({{text=" "..COMMAND_PREFIX.." cmd ml.turnRight()",c=COLORS.WHITE}})
- announce({{text=" "..COMMAND_PREFIX.." cmd return turtle.getFuelLevel()",c=COLORS.WHITE}})
- announce({{text=" "..COMMAND_PREFIX.." cmd turtle.dig()",c=COLORS.WHITE}})
- announce({{text="Note: The Lua code itself is case-sensitive.",c=COLORS.YELLOW}})
- announce({{text="The command must return a value to see a result in chat, otherwise it's 'nil'.",c=COLORS.GRAY}})
- return
- end
- local cs=table.concat(a," ")
- botLog("User "..u.." executing raw command: "..cs)
- local fn,e=load("return "..cs,"raw_user_command","t",{ml=ml, turtle=turtle, peripheral=peripheral, os=os, fs=fs, textutils=textutils, sleep=sleep, print=print, announce=announce, COLORS=COLORS})
- if not fn then
- announce({{text="Error parsing command: ",c=COLORS.RED},{text=tostring(e),c=COLORS.YELLOW}})
- botLog("Parse error for raw command '"..cs.."': "..tostring(e))
- return
- end
- local s,r=pcall(fn)
- if s then
- announce({{text="Cmd executed. Result: ",c=COLORS.GREEN},{text=tostring(r),c=COLORS.WHITE}})
- botLog("Raw command '"..cs.."' result: "..tostring(r))
- else
- announce({{text="Error executing command: ",c=COLORS.RED},{text=tostring(r),c=COLORS.YELLOW}})
- botLog("Execution error for raw command '"..cs.."': "..tostring(r))
- end
- end
- commandHandlers.pos = function(u,_)
- local pD=ml.getPosition(); local dNS=ml.getDirectionName()
- if pD and pD.x~=nil then announce({{text="Position: ",c=COLORS.AQUA},{text="X:"..tostring(pD.x).." Y:"..tostring(pD.y).." Z:"..tostring(pD.z),c=COLORS.WHITE},{text=" Facing: "..dNS,c=COLORS.WHITE}})
- else announce({{text="Position unknown.",c=COLORS.YELLOW}})end
- end
- commandHandlers.fuel = function(u,_)
- local l,lm=turtle.getFuelLevel(),turtle.getFuelLimit()
- announce({{text="Fuel: ",c=COLORS.AQUA},{text=tostring(l)..(lm>0 and(" / "..tostring(lm))or" (Unlimited)"),c=COLORS.WHITE}})
- end
- commandHandlers.unstuck = function(u,_)
- announce({{text="Unstuck: Attempting to warp home and reset position...",c=COLORS.YELLOW}});botLog(u.." used unstuck command.")
- isDisenchantRunning = false
- if ml.home()then announce({{text="Warped home and position reset successfully.",c=COLORS.GREEN}})
- else announce({{text="Failed to warp home. Manual assistance may be required.",c=COLORS.RED}})end
- end
- --#endregion
- --#region DisenchantBot Core Logic
- function performSingleDisenchantCycle()
- botLog("== Starting new Disenchant Cycle ==")
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 1: Warping home.")
- if not ml.home() then critical_error_handler("Failed to warp home at cycle start.", false); return "error" end
- announce({{text="Warped home. Current orientation: North.", c=COLORS.GRAY}})
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 2: Dropping all inventory items.")
- for i = 1, 16 do
- turtle.select(i)
- if turtle.getItemCount(i) > 0 then
- botLog("Dropping items from slot " .. i)
- turtle.drop()
- end
- end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 3: Checking fuel.")
- local fuelLevel = turtle.getFuelLevel()
- local fuelLimit = turtle.getFuelLimit()
- if fuelLimit > 0 and (fuelLevel / fuelLimit) < 0.50 then
- announce({{text="Fuel under 50% ("..fuelLevel.."/"..fuelLimit.."). Refueling...", c=COLORS.YELLOW}})
- botLog("Fuel low. Attempting to suck, refuel, drop excess.")
- turtle.select(1)
- if not turtle.suck() then
- announce({{text="Failed to suck fuel item.", c=COLORS.RED}})
- botLog("Failed to suck fuel from below.")
- else
- botLog("Sucked an item, attempting to refuel.")
- if not turtle.refuel() then
- announce({{text="Refuel failed with sucked item. Item might not be fuel.", c=COLORS.RED}})
- botLog("turtle.refuel() failed.")
- else
- botLog("Refuel successful. Current Fuel: " .. turtle.getFuelLevel())
- end
- turtle.drop()
- botLog("Dropped item from slot 1 after refuel attempt.")
- end
- else
- botLog("Fuel is OK ("..fuelLevel.."/"..fuelLimit.."). Skipping refuel step.")
- end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 4: Turning right (to East).")
- if not ml.turnRight() then critical_error_handler("Failed to turn right.", false); return "error" end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 5: Sucking up to 16 items (1 by 1) from East.")
- local itemsSuckedInStep5 = 0
- for i = 1, 16 do
- local emptySlotFound = false
- local originalSlot = turtle.getSelectedSlot()
- for slotIdx = 1, 16 do
- if turtle.getItemCount(slotIdx) == 0 then
- turtle.select(slotIdx)
- emptySlotFound = true
- break
- end
- end
- if not emptySlotFound then botLog("No empty slot to suck item into."); break end
- if turtle.suck(1) then itemsSuckedInStep5 = itemsSuckedInStep5 + 1; botLog("Sucked item " .. itemsSuckedInStep5 .. " into slot " .. turtle.getSelectedSlot())
- else turtle.select(originalSlot); botLog("Failed to suck more items after " .. itemsSuckedInStep5 .. " items."); break end
- end
- announce({{text="Sucked "..itemsSuckedInStep5.." item(s) for processing.", c=COLORS.GRAY}})
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 6: Checking inventory for non-stackable items.")
- local slotsWithNonStackableItems = {}
- for slot = 1, 16 do
- turtle.select(slot)
- if turtle.getItemCount(slot) > 0 then
- local space = turtle.getItemSpace(slot)
- if space == 0 then table.insert(slotsWithNonStackableItems, slot); botLog("Slot " .. slot .. ": Non-stackable item found.")
- elseif space == 64 then critical_error_handler("Inventory check contradiction in slot " .. slot .. ".", true); return "error"
- else critical_error_handler("Inventory check: Slot " .. slot .. " has unexpected item (space=" .. space .. ").", true); return "error"
- end
- end
- end
- local expectedNonStackableCount = #slotsWithNonStackableItems
- botLog("Found " .. expectedNonStackableCount .. " non-stackable item(s) in slots: " .. table.concat(slotsWithNonStackableItems, ", "))
- if expectedNonStackableCount == 0 then
- if itemsSuckedInStep5 > 0 then announce({{text="No valid items out of "..itemsSuckedInStep5.." sucked. Restarting.", c=COLORS.YELLOW}})
- else announce({{text="No items found to process. Restarting.", c=COLORS.YELLOW}}) end
- if not ml.turnLeft() then critical_error_handler("Failed to turn left before wait.", false); return "error" end
- botLog("Waiting 60 seconds as no items to process.")
- for _=1,60 do if check_stop_signal() then return "stopped_by_user" end; sleep(1) end
- return "continue_looping"
- end
- announce({{text="Processing "..expectedNonStackableCount.." non-stackable item(s).", c=COLORS.AQUA}})
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 7: Turning right (to South) to face 'tryOutputchest'.")
- if not ml.turnRight() then critical_error_handler("Failed to turn right towards tryOutputchest.", false); return "error" end
- botLog("Dropping " .. expectedNonStackableCount .. " items into tryOutputchest.")
- for _, slotIdx in ipairs(slotsWithNonStackableItems) do
- turtle.select(slotIdx)
- if turtle.getItemCount(slotIdx) > 0 then
- if not turtle.drop() then critical_error_handler("Failed to drop item from slot " .. slotIdx .. " into tryOutputchest.", false); return "error" end
- end
- end
- slotsWithNonStackableItems = {}
- botLog("Waiting 5 seconds after dropping items.")
- for _=1,5 do if check_stop_signal() then return "stopped_by_user" end; sleep(1) end
- local itemsLeftToProcessCount = expectedNonStackableCount
- local itemsSuccessfullyProcessedFlag = false
- botLog("Starting extractor check loop. Expecting " .. itemsLeftToProcessCount .. " items back initially.")
- while itemsLeftToProcessCount > 0 do
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Attempting to suck back up to " .. itemsLeftToProcessCount .. " item(s).")
- local itemsSuckedThisPass = 0
- local currentPassSuckedSlots = {}
- for _ = 1, itemsLeftToProcessCount do
- local emptySlotFound = false; local originalSlot = turtle.getSelectedSlot()
- for slotIdx = 1, 16 do if turtle.getItemCount(slotIdx) == 0 then turtle.select(slotIdx); emptySlotFound = true; break end end
- if not emptySlotFound then botLog("Extractor loop: Inventory full."); turtle.select(originalSlot); break end
- if turtle.suck(1) then itemsSuckedThisPass = itemsSuckedThisPass + 1; table.insert(currentPassSuckedSlots, turtle.getSelectedSlot()); botLog("Extractor loop: Sucked item " .. itemsSuckedThisPass .. " into slot " .. turtle.getSelectedSlot())
- else turtle.select(originalSlot); botLog("Extractor loop: Failed to suck more after " .. itemsSuckedThisPass .. " items."); break end
- end
- local validNonStackableItemsAfterSuck = 0; local slotsWithValidItemsThisPass = {}
- for _, slotIdx in ipairs(currentPassSuckedSlots) do
- turtle.select(slotIdx)
- if turtle.getItemCount(slotIdx) > 0 and turtle.getItemSpace(slotIdx) == 0 then validNonStackableItemsAfterSuck = validNonStackableItemsAfterSuck + 1; table.insert(slotsWithValidItemsThisPass, slotIdx)
- elseif turtle.getItemCount(slotIdx) > 0 then botLog("Warning: Extractor returned stackable/partial to slot " .. slotIdx); validNonStackableItemsAfterSuck = validNonStackableItemsAfterSuck + 1; table.insert(slotsWithValidItemsThisPass, slotIdx) end
- end
- botLog("Extractor loop: Got back " .. validNonStackableItemsAfterSuck .. " valid non-stackable items this pass.")
- if validNonStackableItemsAfterSuck < itemsLeftToProcessCount then
- itemsSuccessfullyProcessedFlag = true
- local processedCountThisPass = itemsLeftToProcessCount - validNonStackableItemsAfterSuck
- announce({{text="Extractor processed "..processedCountThisPass.." item(s). " .. validNonStackableItemsAfterSuck .. " remaining.", c=COLORS.GRAY}})
- botLog("Dropping remaining " .. validNonStackableItemsAfterSuck .. " items.")
- for _, slotIdx in ipairs(slotsWithValidItemsThisPass) do turtle.select(slotIdx); if turtle.getItemCount(slotIdx) > 0 then turtle.drop() end end
- botLog("Waiting 20 seconds.")
- for _=1,20 do if check_stop_signal() then return "stopped_by_user" end; sleep(1) end
- itemsLeftToProcessCount = validNonStackableItemsAfterSuck
- if itemsLeftToProcessCount == 0 then announce({{text="All items processed by extractor.", c=COLORS.GREEN}}); botLog("All items processed."); break end
- else
- if validNonStackableItemsAfterSuck > itemsLeftToProcessCount then announce({{text="Warning: Got "..validNonStackableItemsAfterSuck.." items, expected "..itemsLeftToProcessCount..".", c=COLORS.YELLOW}}); botLog("Warning: Extractor returned more than expected.") end
- announce({{text="Extractor did not process " .. itemsLeftToProcessCount .. " item(s). Assuming unprocessable.", c=COLORS.YELLOW}})
- botLog("Extractor loop: No items lost. Items in turtle: " .. validNonStackableItemsAfterSuck); break
- end
- end
- if check_stop_signal() then return "stopped_by_user" end
- if itemsSuccessfullyProcessedFlag then
- botLog("Step 8: Items processed. Waiting 15 seconds.")
- for _=1,15 do if check_stop_signal() then return "stopped_by_user" end; sleep(1) end
- else botLog("Step 8: No items processed. Skipping 15s wait.") end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 9: Sucking up to 17 times from tryOutputchest (South).")
- local itemsSuckedInStep9 = 0
- for i = 1, 17 do
- if turtle.suck() then itemsSuckedInStep9 = itemsSuckedInStep9 + 1; botLog("Final suck op "..i.." successful.")
- else botLog("Final suck: Chest empty/inventory full after " .. itemsSuckedInStep9 .. " ops."); break end
- end
- botLog("Finished final suck from tryOutputchest.")
- botLog("Turning right (to West) after final suck.")
- if not ml.turnRight() then critical_error_handler("Failed to turn right after final suck.", false); return "error" end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 10: Final inventory check (expecting " .. expectedNonStackableCount .. " non-stackable items).")
- local finalNonStackableSlotsCount = 0
- for slot = 1, 16 do
- turtle.select(slot)
- if turtle.getItemCount(slot) > 0 then
- if turtle.getItemSpace(slot) == 0 then finalNonStackableSlotsCount = finalNonStackableSlotsCount + 1
- else botLog("Slot " .. slot .. " contains stackable/partial. Not counted.") end
- end
- end
- botLog("Final count of non-stackable items/slots: " .. finalNonStackableSlotsCount)
- if finalNonStackableSlotsCount ~= expectedNonStackableCount then
- critical_error_handler("Final item count (" .. finalNonStackableSlotsCount .. ") != initial (" .. expectedNonStackableCount .. ").", false) -- Error handler does not turnLeft. Original said turnRight.
- ml.turnRight() -- Specific turn for this error as per prompt
- return "error"
- end
- announce({{text="Final item count matches expected. Proceeding.", c=COLORS.GREEN}})
- if check_stop_signal() then return "stopped_by_user" end
- botLog("Step 11: Turning right (to North) for dropUp.")
- if not ml.turnRight() then critical_error_handler("Failed to turn right for dropUp.", false); return "error" end
- botLog("Dropping items up (16 times).")
- for i = 1, 16 do
- turtle.select(i)
- if turtle.getItemCount(i) > 0 then
- if turtle.dropUp() then botLog("Dropped up from slot " .. i)
- else botLog("Failed to dropUp from slot " .. i) end
- end
- end
- if check_stop_signal() then return "stopped_by_user" end
- botLog("== Disenchant Cycle Iteration Complete ==")
- announce({{text="Disenchant cycle iteration finished.",c=COLORS.GRAY}})
- return "continue_looping"
- end
- commandHandlers.start = function(u,a)
- if isDisenchantRunning then
- announce({{text=CHAT_BOT_NAME.." is already running.",c=COLORS.YELLOW}})
- return
- end
- isDisenchantRunning = true
- fuelWarningSent = false
- announce({{text="Starting "..CHAT_BOT_NAME.." loop...",c=COLORS.GOLD,b=true}})
- botLog(u.." initiated "..CHAT_BOT_NAME.." start.")
- -- The main run() loop will now pick up the actual execution
- end
- commandHandlers.stop = function(u,a)
- if not isDisenchantRunning then
- announce({{text=CHAT_BOT_NAME.." is not currently running.",c=COLORS.GRAY}})
- return
- end
- announce({{text="Stop signal sent to "..CHAT_BOT_NAME..". Will stop soon.",c=COLORS.YELLOW}})
- botLog(u.." initiated "..CHAT_BOT_NAME.." stop.")
- isDisenchantRunning = false
- end
- --#endregion
- --#region DisenchantBot Main Loop (Event Handling)
- local function run()
- if DEBUG_LOGGING_ENABLED then
- local file, err = fs.open(LOG_FILE_NAME, "w")
- if file then file.write(string.format("[%s] %s Log Initialized.\n", os.date("%Y-%m-%d %H:%M:%S"), CHAT_BOT_NAME)); file.write("============================================================\n"); file.close()
- else print("LOGGING ERROR: Could not initialize "..LOG_FILE_NAME..": "..tostring(err)) end
- end
- term.clear();term.setCursorPos(1,1);
- chatBox = peripheral.find(CHAT_BOX_PERIPHERAL_NAME)
- botLog(CHAT_BOT_NAME .. " initializing...")
- botLog("Initial ChatBox peripheral check: " .. tostring(chatBox))
- if chatBox and chatBox.sendFormattedMessage then
- chatBoxFunctional = true
- botLog("ChatBox determined to be FUNCTIONAL.")
- else
- chatBoxFunctional = false
- botLog("ChatBox IS NIL or missing key methods. Marking as non-functional.")
- end
- botLog(CHAT_BOT_NAME.." online. Movement Library init complete.")
- print(CHAT_BOT_NAME.." online. Use '"..COMMAND_PREFIX.." help'.")
- if not announce({{text=CHAT_BOT_NAME.." online, ready for disenchanting duties!",c=COLORS.GREEN}}) then
- botLog("Initial online announcement FAILED (ChatBox non-functional or error).")
- end
- while true do
- local event, p1, p2, p3, p4, p5
- if isDisenchantRunning then
- event, p1, p2, p3, p4, p5 = os.pullEventRaw()
- if not event then
- sleep(0.05) -- Small yield if no event, to prevent tight loop when running
- end
- else
- event, p1, p2, p3, p4, p5 = os.pullEvent() -- Block if not running
- end
- if event then
- if event == "chat" then
- local user, message = p1, p2
- if message then
- if string.lower(message) == "@all" then
- botLog("@all from "..user)
- announce({{text="Use '",c=COLORS.GREEN},{text=COMMAND_PREFIX.." help",c=COLORS.AQUA},{text="' for my commands.",c=COLORS.GREEN}})
- elseif string.sub(message,1,#COMMAND_PREFIX) == COMMAND_PREFIX then
- botLog("Chat cmd from "..user..": "..message)
- local params={};for pt in string.gmatch(message,"[^%s]+")do table.insert(params,pt)end
- local cmdName=""; if params[2]then cmdName=string.lower(params[2])end
- local cmdArgs={};for i=3,#params do table.insert(cmdArgs,params[i])end
- if commandHandlers[cmdName]then
- commandHandlers[cmdName](user,cmdArgs)
- elseif cmdName ~= "" then
- announce({{text="Unknown Command: '",c=COLORS.RED},{text=cmdName,c=COLORS.YELLOW},{text="'. Try '",c=COLORS.RED},{text=COMMAND_PREFIX .. " help",c=COLORS.AQUA},{text="'.",c=COLORS.RED}})
- end
- end
- end
- elseif event == "terminate" then
- botLog("Terminate event received. Shutting down.")
- isDisenchantRunning = false
- if chatBoxFunctional then announce({{text=CHAT_BOT_NAME.." shutting down.",c=COLORS.YELLOW}}) end
- return
- end
- end
- if isDisenchantRunning then
- if not isDisenchantRunning then -- Check if a command just set it to false
- announce({{text=CHAT_BOT_NAME.." loop stopping (command processed).",c=COLORS.YELLOW}})
- botLog(CHAT_BOT_NAME.." processing stopped by command processed in this iteration.")
- else
- local cycleStatus = performSingleDisenchantCycle()
- if cycleStatus == "error" then
- botLog(CHAT_BOT_NAME .." loop terminated due to error reported by cycle.")
- isDisenchantRunning = false
- elseif cycleStatus == "stopped_by_user" then
- botLog(CHAT_BOT_NAME .." loop iteration cut short by internal stop signal detection.")
- isDisenchantRunning = false
- elseif cycleStatus == "continue_looping" then
- botLog("Disenchant cycle iteration completed. Will continue if flag is set.")
- end
- if not isDisenchantRunning then
- announce({{text=CHAT_BOT_NAME.." loop has now fully stopped.",c=COLORS.GOLD}})
- botLog(CHAT_BOT_NAME.." processing has completely stopped.")
- end
- end
- end
- end
- end
- run()
- --#endregion
Add Comment
Please, Sign In to add comment