Myros27

farmBot

May 19th, 2025 (edited)
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 31.00 KB | None | 0 0
  1. --[[
  2.     FarmBot v1.1.1 - Cooperative Farming Robot with SuckUp (Chat Fix)
  3.     - Reverted sendFormattedChat and announce to DefragBot v1.8.3 version.
  4.     - Executes automata.useOnBlock() based on commands.
  5.     - Sucks up items on script start.
  6.     - Sucks up items every 64 useOnBlock actions during farming.
  7.     - Supports fast and slow farming modes.
  8.     - IS_MASTER_BOT flag controls @all and @farm help responses.
  9.     - Includes Movement Library for potential utility.
  10. ]]
  11.  
  12. --#region Configuration
  13. local AUTOMATA_PERIPHERAL_NAME = "endAutomata" -- IMPORTANT: Set your End Automata peripheral name
  14. local CHAT_BOX_PERIPHERAL_NAME = "chatBox"
  15.  
  16. local IS_MASTER_BOT = true -- Set to true for ONE bot to handle global help/all commands
  17.  
  18. local COMMAND_PREFIX = "@farm"
  19. local CHAT_BOT_NAME = "FarmBot"
  20. local CHAT_BOT_BRACKETS = "[]"
  21. local CHAT_BOT_BRACKET_COLOR = "&a" -- Green
  22.  
  23. local SUCKUP_INTERVAL = 64 -- How many useOnBlock calls before a suckUp
  24.  
  25. local DEBUG_LOGGING_ENABLED = true
  26. local LOG_FILE_NAME = "farmbot.log"
  27. --#endregion
  28.  
  29. --#region Global State
  30. local automata = nil
  31. local chatBox = nil
  32. local chatBoxFunctional = true
  33.  
  34. local isFarming = false
  35. local farmMode = "fast" -- "fast" or "slow"
  36. local farmCoroutine = nil
  37. --#endregion
  38.  
  39. --#region Logger Setup
  40. 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
  41. local function botLog(msg)local fm="["..CHAT_BOT_NAME.."-Debug] "..msg; print(fm); writeToLogFile(fm)end
  42. local function moveLog(msg)local fm="[MoveLib-Debug] "..msg; print(fm); writeToLogFile(fm)end
  43. --#endregion
  44.  
  45. --#region Movement Library Code (Copied from FarmBot v1.0)
  46. local ML_POSITION_FILE="turtle_pos_farmbot.json";local ML_REFUEL_SLOT=16;local ML_FUEL_ITEM_NAME_PART="coal";local ml_automata_ref=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(ML_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(ML_POSITION_FILE)then local f,e=fs.open(ML_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 ml_automata_ref then ml_automata_ref=peripheral.find(AUTOMATA_PERIPHERAL_NAME);if not ml_automata_ref then moveLog("Err: EndAuto ('"..AUTOMATA_PERIPHERAL_NAME.."') miss for MoveLib home.");return false end end;moveLog("Warp home...");local s,r=pcall(function()return ml_automata_ref.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(ML_REFUEL_SLOT);local iBFS=turtle.getItemCount(ML_REFUEL_SLOT);local iD=turtle.getItemDetail(ML_REFUEL_SLOT);local iN="";if iD and iD.name then iN=string.lower(iD.name)else moveLog("Fuel slot "..ML_REFUEL_SLOT.." empty/no name.")end;if iBFS>0 and string.find(iN,ML_FUEL_ITEM_NAME_PART)then moveLog("Refuel from slot "..ML_REFUEL_SLOT.." ("..(iD.name or"Unk Fuel").." x"..iBFS..")");if turtle.refuel(0)then local iAFS=turtle.getItemCount(ML_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 "..ML_REFUEL_SLOT.." init empty.")end;local iTS=64-turtle.getItemCount(ML_REFUEL_SLOT);local sTC=0;if iTS>0 then moveLog("Suck "..iTS.." to replenish fuel slot...");for _=1,iTS do if turtle.getItemCount(ML_REFUEL_SLOT)>=64 then break end;local cSD=turtle.getItemDetail(ML_REFUEL_SLOT);local cSN="";if cSD and cSD.name then cSN=string.lower(cSD.name)end;if turtle.getItemCount(ML_REFUEL_SLOT)>0 and not string.find(cSN,ML_FUEL_ITEM_NAME_PART)then moveLog("Slot "..ML_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 for FarmBot...");ml_automata_ref=peripheral.find(AUTOMATA_PERIPHERAL_NAME);if not ml_automata_ref then moveLog("CRIT WARN: EndAuto ('"..AUTOMATA_PERIPHERAL_NAME.."') miss for MoveLib. 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};
  47. --#endregion End of Integrated Movement Library
  48.  
  49. --#region FarmBot Peripherals and Helpers
  50. -- VVVVVV THIS IS THE CHAT FUNCTION FROM DefragBot v1.8.3 VVVVVV
  51. local function sendFormattedChat(messageComponents) -- Simplified, always global
  52.     local plainText = ""
  53.     if type(messageComponents) == "table" then
  54.         for _,c_comp in ipairs(messageComponents) do
  55.             plainText = plainText .. (type(c_comp) == "table" and c_comp.text or tostring(c_comp) or "")
  56.         end
  57.     elseif messageComponents ~= nil then plainText = tostring(messageComponents)
  58.     else plainText = "nil_message_components_to_sendFormattedChat" end
  59.    
  60.     if not chatBox then -- Check if chatBox was found at startup
  61.         botLog("[NoChat] " .. plainText);
  62.         return false
  63.     end
  64.    
  65.     local jsonMessage_success, jsonMessage = pcall(textutils.serialiseJSON, messageComponents)
  66.     if not jsonMessage_success then
  67.         botLog("!!! textutils.serialiseJSON FAILED: " .. tostring(jsonMessage) .. " -- Original: " .. textutils.serialize(messageComponents,{compact=true,max_depth=2}))
  68.         print("ERROR: Could not serialize chat message!"); return false
  69.     end
  70.  
  71.     local peripheral_call_success, peripheral_error = pcall(function()
  72.         return chatBox.sendFormattedMessage(jsonMessage, CHAT_BOT_NAME, CHAT_BOT_BRACKETS, CHAT_BOT_BRACKET_COLOR)
  73.     end)
  74.    
  75.     if not peripheral_call_success then
  76.         botLog("!!! chatBox.sendFormattedMessage FAILED: " .. tostring(peripheral_error) .. " -- JSON was: " .. jsonMessage)
  77.         print("ERROR: Failed to send formatted message via chatBox: " .. tostring(peripheral_error))
  78.         return false
  79.     end
  80.     return true
  81. end
  82.  
  83. local function announce(messageComponents)
  84.     local success = sendFormattedChat(messageComponents)
  85.     if not success then
  86.         botLog("Announce: sendFormattedChat failed.")
  87.     end
  88.     sleep(0.3) -- Using the DefragBot sleep time, adjust if FarmBot needs faster/slower announcements
  89.     return success
  90. end
  91. -- ^^^^^^ END OF CHAT FUNCTION FROM DefragBot v1.8.3 ^^^^^^
  92.  
  93.  
  94. local COLORS = {GOLD="gold",AQUA="aqua",GRAY="gray",RED="red",GREEN="green",YELLOW="yellow",WHITE="white",DARK_RED="dark_red",DARK_GRAY="dark_gray", LIGHT_PURPLE="light_purple", BLUE="blue"}
  95. --#endregion
  96.  
  97. --#region FarmBot Core Logic: Farming Loop
  98. local function farmingLoop()
  99.     botLog("Farming coroutine started in '" .. farmMode .. "' mode.")
  100.     local useOnBlockCount = 0
  101.     local totalUsesOverall = 0
  102.  
  103.     while isFarming do
  104.         if not automata then
  105.             botLog("Farming loop: End Automata not found! Stopping farm.", true)
  106.             if IS_MASTER_BOT then announce({{text="CRITICAL: End Automata ('"..AUTOMATA_PERIPHERAL_NAME.."') not found on a FarmBot! Farming stopped.", color=COLORS.RED, bold=true}}) end
  107.             isFarming = false
  108.             break
  109.         end
  110.  
  111.         local success, err = pcall(automata.useOnBlock)
  112.         totalUsesOverall = totalUsesOverall + 1
  113.  
  114.         if not success then
  115.             botLog("automata.useOnBlock() failed: " .. tostring(err), true)
  116.         else
  117.             useOnBlockCount = useOnBlockCount + 1
  118.         end
  119.  
  120.         if useOnBlockCount >= SUCKUP_INTERVAL then
  121.             botLog("Reached " .. SUCKUP_INTERVAL .. " useOnBlock actions. Performing turtle.suckUp().")
  122.             local suckedUp, suckErr = pcall(turtle.suckUp)
  123.             if not suckedUp then
  124.                 botLog("turtle.suckUp() failed: " .. tostring(suckErr), true)
  125.             else
  126.                 botLog("turtle.suckUp() successful.")
  127.             end
  128.             useOnBlockCount = 0
  129.         end
  130.  
  131.         if farmMode == "slow" then
  132.             sleep(1)
  133.         elseif farmMode == "fast" then
  134.             sleep(0)
  135.         else
  136.             botLog("Farming loop: Unknown farmMode '" .. farmMode .. "'. Defaulting to fast and yielding.", true)
  137.             sleep(0)
  138.         end
  139.     end
  140.     botLog("Farming coroutine ended. Total useOnBlock actions: " .. totalUsesOverall)
  141.     farmCoroutine = nil
  142. end
  143.  
  144. local function startFarming(newMode)
  145.     if not automata then
  146.         botLog("Cannot start farming: End Automata ('"..AUTOMATA_PERIPHERAL_NAME.."') not found.", true)
  147.         if IS_MASTER_BOT then announce({{text="Error: End Automata ('"..AUTOMATA_PERIPHERAL_NAME.."') not found. Cannot start farming.", color=COLORS.RED}}) end
  148.         return
  149.     end
  150.  
  151.     if isFarming and farmCoroutine then
  152.         if farmMode == newMode then
  153.             if IS_MASTER_BOT then announce({{text="FarmBot already farming in '", color=COLORS.YELLOW},{text=newMode, color=COLORS.AQUA},{text="' mode.", color=COLORS.YELLOW}}) end
  154.             return
  155.         else
  156.             botLog("Switching farm mode from '"..farmMode.."' to '"..newMode.."'")
  157.             farmMode = newMode
  158.             if IS_MASTER_BOT then announce({{text="FarmBot switching to '", color=COLORS.GREEN},{text=newMode, color=COLORS.AQUA},{text="' farming mode.", color=COLORS.GREEN}}) end
  159.             return
  160.         end
  161.     end
  162.  
  163.     isFarming = true
  164.     farmMode = newMode
  165.     if farmCoroutine then botLog("Warning: farmCoroutine was not nil before starting a new one.", true) end
  166.     farmCoroutine = coroutine.create(farmingLoop)
  167.     local status, err = coroutine.resume(farmCoroutine)
  168.     if not status then
  169.         botLog("Failed to start/resume farmingLoop coroutine: " .. tostring(err), true)
  170.         isFarming = false; farmCoroutine = nil;
  171.         if IS_MASTER_BOT then announce({{text="CRITICAL ERROR: Failed to start farming task!", color=COLORS.RED, bold=true}}) end
  172.     else
  173.         if IS_MASTER_BOT then announce({{text="FarmBot started in '", color=COLORS.GREEN},{text=farmMode, color=COLORS.AQUA},{text="' mode.", color=COLORS.GREEN}}) end
  174.     end
  175. end
  176.  
  177. local function stopFarming()
  178.     if not isFarming then
  179.         if IS_MASTER_BOT then announce({{text="FarmBot is not currently farming.", color=COLORS.YELLOW}}) end
  180.         return
  181.     end
  182.     isFarming = false
  183.     if not farmCoroutine then botLog("Warning: stopFarming called, isFarming true, but farmCoroutine nil.", true) end
  184.     botLog("Farming stop signal sent.")
  185.     if IS_MASTER_BOT then announce({{text="FarmBot stopping...", color=COLORS.YELLOW}}) end
  186. end
  187. --#endregion
  188.  
  189. --#region FarmBot Command Handlers
  190. local commandHandlers = {}
  191.  
  192. commandHandlers.help = function(user, args)
  193.     if not IS_MASTER_BOT then return end
  194.     announce({{text="--- FarmBot Cmds ("..COMMAND_PREFIX..") v1.1.1 ---",c=COLORS.GREEN,b=true}})
  195.     announce({{text=COMMAND_PREFIX.." help",c=COLORS.AQUA},{text=" - Shows this help message.",c=COLORS.GRAY}})
  196.     announce({{text=COMMAND_PREFIX.." start",c=COLORS.AQUA},{text=" - Starts farming (fast mode).",c=COLORS.GRAY}})
  197.     announce({{text=COMMAND_PREFIX.." stop",c=COLORS.AQUA},{text=" - Stops farming.",c=COLORS.GRAY}})
  198.     announce({{text=COMMAND_PREFIX.." fast",c=COLORS.AQUA},{text=" - Starts/Switches to fast farming.",c=COLORS.GRAY}})
  199.     announce({{text=COMMAND_PREFIX.." slow",c=COLORS.AQUA},{text=" - Starts/Switches to slow farming.",c=COLORS.GRAY}})
  200.     announce({{text="--- Movement Commands (Master Only for Help) ---",c=COLORS.GOLD,b=true}})
  201.     announce({{text=COMMAND_PREFIX.." pos",c=COLORS.AQUA},{text=" - Current position/direction.",c=COLORS.GRAY}})
  202.     announce({{text=COMMAND_PREFIX.." fuel",c=COLORS.AQUA},{text=" - Current fuel.",c=COLORS.GRAY}})
  203.     announce({{text=COMMAND_PREFIX.." unstuck",c=COLORS.AQUA},{text=" - Warp home, reset pos.",c=COLORS.GRAY}})
  204.     announce({{text=COMMAND_PREFIX.." cmd help",c=COLORS.AQUA},{text=" - Help for raw Lua command execution.",c=COLORS.GRAY}})
  205.     announce({{text=COMMAND_PREFIX.." cmd <lua>",c=COLORS.AQUA},{text=" - Execute Lua (e.g., ml.forward()).",c=COLORS.GRAY}})
  206.     announce({{text=COMMAND_PREFIX.." mult <seq>",c=COLORS.AQUA},{text=" - Seq l,r,f,b,u,d,a.",c=COLORS.GRAY}})
  207. end
  208.  
  209. commandHandlers.start = function(user, args) botLog(user .. " commanded START farming."); startFarming("fast") end
  210. commandHandlers.stop = function(user, args) botLog(user .. " commanded STOP farming."); stopFarming() end
  211. commandHandlers.fast = function(user, args) botLog(user .. " commanded FAST farming."); startFarming("fast") end
  212. commandHandlers.slow = function(user, args) botLog(user .. " commanded SLOW farming."); startFarming("slow") end
  213.  
  214. commandHandlers.cmd = function(u,a)
  215.     if #a == 0 then if IS_MASTER_BOT 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}}) end; return end
  216.     if #a == 1 and string.lower(a[1]) == "help" then
  217.         if IS_MASTER_BOT then announce({{text="--- @farm 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 Lua. Use 'ml.' for Movement Library.",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 ml.getFuelLevel()",c=COLORS.WHITE}}); announce({{text="Note: Lua code is case-sensitive (e.g., 'ml.moveTo').",c=COLORS.YELLOW}}) end; return
  218.     end
  219.     local cs=table.concat(a," "); botLog("User "..u.." executing raw command: "..cs)
  220.     local fn,e=load("return "..cs,"raw_user_command","t",{ml=ml, turtle=turtle, peripheral=peripheral, os=os, fs=fs, textutils=textutils, http=http, parallel=parallel, term=term, sleep=sleep, print=print})
  221.     if not fn then if IS_MASTER_BOT then announce({{text="Error parsing command: ",c=COLORS.RED},{text=tostring(e),c=COLORS.YELLOW}}) end; botLog("Parse error for raw command '"..cs.."': "..tostring(e)); return end
  222.     local s,r=pcall(fn)
  223.     if s then if IS_MASTER_BOT then announce({{text="Cmd executed. Result: ",c=COLORS.GREEN},{text=tostring(r),c=COLORS.WHITE}}) end; botLog("Raw command '"..cs.."' result: "..tostring(r))
  224.     else if IS_MASTER_BOT then announce({{text="Error executing command: ",c=COLORS.RED},{text=tostring(r),c=COLORS.YELLOW}}) end; botLog("Execution error for raw command '"..cs.."': "..tostring(r)) end
  225. end
  226. commandHandlers.mult = function(u,a)
  227.     if #a~=1 or type(a[1])~="string"then if IS_MASTER_BOT then announce({{text="Usage: "..COMMAND_PREFIX.." mult <seq>",c=COLORS.YELLOW}});announce({{text="Seq: lrfbuda. Ex: lffr",c=COLORS.GRAY}}) end; return end
  228.     local sq=string.lower(a[1]);botLog("Usr "..u.." mult: "..sq);if IS_MASTER_BOT then announce({{text="Executing sequence: ",c=COLORS.AQUA},{text=sq,c=COLORS.WHITE}}) end; local sc=true
  229.     for i=1,#sq do
  230.         local mc=string.sub(sq,i,i);local mf=nil
  231.         if mc=="l"then mf=ml.l elseif mc=="r"then mf=ml.r elseif mc=="f"then mf=ml.f elseif mc=="b"then mf=ml.b
  232.         elseif mc=="u"then mf=ml.u elseif mc=="d"then mf=ml.d elseif mc=="a"then mf=ml.a end
  233.         if mf then
  234.             if IS_MASTER_BOT then announce({{text="Exec: ",c=COLORS.GRAY},{text=mc,c=COLORS.YELLOW}}) end
  235.             local ms=mf()
  236.             if not ms then if IS_MASTER_BOT then announce({{text="Move '",c=COLORS.RED},{text=mc,c=COLORS.YELLOW},{text="' failed. Stopping sequence.",c=COLORS.RED}}) end; if turtle.getFuelLevel()<10 and turtle.getFuelLimit()~=0 and IS_MASTER_BOT then announce({{text="CRITICAL: Fuel low ("..turtle.getFuelLevel()..")!",c=COLORS.DARK_RED,b=true}}) end; sc=false;break end
  237.         else if IS_MASTER_BOT then announce({{text="Unknown char '",c=COLORS.RED},{text=mc,c=COLORS.YELLOW},{text="' in sequence. Stopping.",c=COLORS.RED}}) end; sc=false;break end
  238.     end
  239.     if sc and IS_MASTER_BOT then announce({{text="Sequence finished.",c=COLORS.GREEN}})end
  240. end
  241. commandHandlers.pos = function(u,_) if not IS_MASTER_BOT then return end; 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
  242. commandHandlers.fuel = function(u,_) if not IS_MASTER_BOT then return end; 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
  243. commandHandlers.unstuck = function(u,_) if not IS_MASTER_BOT then return end; announce({{text="Unstuck: Attempting to warp home and reset position...",c=COLORS.YELLOW}});botLog(u.." used unstuck command."); if ml.h()then announce({{text="Warped home and position reset successfully.",c=COLORS.GREEN}}) else announce({{text="Failed to warp home.",c=COLORS.RED}})end end
  244. --#endregion
  245.  
  246. --#region FarmBot Main Loop
  247. local function run()
  248.     if DEBUG_LOGGING_ENABLED then
  249.         local file, err = fs.open(LOG_FILE_NAME, "w")
  250.         if file then file.write(string.format("[%s] %s Log Initialized (v1.1.1).\n", os.date("%Y-%m-%d %H:%M:%S"), CHAT_BOT_NAME)); file.write("============================================================\n"); file.close()
  251.         else print("LOGGING ERROR: Could not initialize "..LOG_FILE_NAME..": "..tostring(err)) end
  252.     end
  253.     term.clear();term.setCursorPos(1,1)
  254.  
  255.     automata = peripheral.find(AUTOMATA_PERIPHERAL_NAME)
  256.     chatBox = peripheral.find(CHAT_BOX_PERIPHERAL_NAME)
  257.  
  258.     botLog(CHAT_BOT_NAME .. " initializing...")
  259.     botLog("End Automata peripheral ('"..AUTOMATA_PERIPHERAL_NAME.."') check: " .. tostring(automata))
  260.     botLog("ChatBox peripheral ('"..CHAT_BOX_PERIPHERAL_NAME.."') check: " .. tostring(chatBox))
  261.  
  262.     if not automata then
  263.         print("FATAL: End Automata ('"..AUTOMATA_PERIPHERAL_NAME.."') not found! FarmBot cannot function.")
  264.         botLog("FATAL: End Automata not found. Script will not operate farm logic.", true)
  265.     end
  266.  
  267.     if chatBox and chatBox.sendFormattedMessage then chatBoxFunctional = true; botLog("ChatBox determined to be FUNCTIONAL.")
  268.     else chatBoxFunctional = false; botLog("ChatBox peripheral IS NIL or lacks sendFormattedMessage. Chat console/log only.", true); if chatBox then print("WARNING: ChatBox found but missing key methods.") else print("WARNING: ChatBox not found.") end
  269.     end
  270.  
  271.     ml.init()
  272.     botLog(CHAT_BOT_NAME.." online. MoveLib init complete.")
  273.     print(CHAT_BOT_NAME.." online. '"..COMMAND_PREFIX.." help' (if master).")
  274.  
  275.     botLog("Performing initial turtle.suckUp().")
  276.     local suckedUpInitial, suckErrInitial = pcall(turtle.suckUp)
  277.     if not suckedUpInitial then botLog("Initial turtle.suckUp() failed: " .. tostring(suckErrInitial), true)
  278.     else botLog("Initial turtle.suckUp() successful.") end
  279.  
  280.     if IS_MASTER_BOT then
  281.         local initial_announce_success = announce({{text=CHAT_BOT_NAME.." Master online (v1.1.1)! Ready to farm.",c=COLORS.GREEN, b=true}})
  282.         if not initial_announce_success then botLog("Initial online announcement FAILED.") end
  283.     else
  284.         botLog(CHAT_BOT_NAME .. " (Worker) online and awaiting commands.")
  285.     end
  286.  
  287.     while true do
  288.         local eventData={os.pullEvent()}
  289.         local eventType=eventData[1]
  290.  
  291.         if eventType=="chat"then
  292.             local eU,eM=eventData[2],eventData[3]
  293.             if eM then
  294.                 if IS_MASTER_BOT and string.lower(eM)=="@all"then
  295.                     botLog("@all from "..eU)
  296.                     announce({{text=CHAT_BOT_NAME,c=COLORS.GREEN,b=true},{text=" (Master): Use '",c=COLORS.GRAY},{text=COMMAND_PREFIX.." help",c=COLORS.AQUA},{text="' for commands.",c=COLORS.GRAY}})
  297.                 elseif string.sub(eM,1,#COMMAND_PREFIX)==COMMAND_PREFIX then
  298.                     botLog("FarmBot Chat cmd from "..eU..": "..eM)
  299.                     local p={};for pt in string.gmatch(eM,"[^%s]+")do table.insert(p,pt)end
  300.                     local cn=""; if p[2]then cn=string.lower(p[2])end
  301.                     local ca={};for i=3,#p do table.insert(ca,p[i])end
  302.  
  303.                     if commandHandlers[cn]then commandHandlers[cn](eU,ca)
  304.                     elseif cn~="" and IS_MASTER_BOT then
  305.                         if p[2] and string.find(p[2], "%(") and string.find(p[2], "%)") then announce({{text="Unknown Command: '",c=COLORS.RED},{text=p[2],c=COLORS.YELLOW},{text="'. Try: '",c=COLORS.RED},{text=COMMAND_PREFIX.." cmd "..p[2],c=COLORS.AQUA},{text="'",c=COLORS.RED}})
  306.                         else announce({{text="Unknown Command: '",c=COLORS.RED},{text=cn,c=COLORS.YELLOW},{text="'. Try '",c=COLORS.RED},{text=COMMAND_PREFIX .. " help",c=COLORS.AQUA},{text="'.",c=COLORS.RED}}) end
  307.                     elseif cn~="" and not IS_MASTER_BOT then botLog("Worker bot received unknown command '"..cn.."', ignoring as not master.") end
  308.                 end
  309.             end
  310.         elseif eventType=="terminate"then
  311.             botLog("Terminate event received. Shutting down " .. CHAT_BOT_NAME .. ".", true)
  312.             isFarming = false
  313.             if farmCoroutine and coroutine.status(farmCoroutine) ~= "dead" then botLog("Waiting for farming coroutine to self-terminate..."); sleep(0.5) end
  314.             if IS_MASTER_BOT and chatBoxFunctional then announce({{text=CHAT_BOT_NAME.." shutting down.",c=COLORS.YELLOW, b=true}}) end
  315.             return
  316.         end
  317.     end
  318. end
  319.  
  320. run()
  321. --#endregion
Add Comment
Please, Sign In to add comment