# Puniko bots scripting API (Lua 5.4) Page: https://growbgl.com/docs?app=puniko Plain text: https://growbgl.com/puniko-docs.txt Write a Lua script in the Puniko Scripts tab, pick the bots to run it on (or PC only), and press Run, or Test to try it safely. A script works on one bot and getBots() reaches the whole fleet. Scripts can also show forms, live progress, result tables and alerts on growbgl.com. Open Puniko > Scripts to write and run scripts on your bots. ## Rules for writing a script - Plain Lua 5.4. Use only the functions, fields, events and option keys in this file. Never guess a name. If something is not here, say it cannot be done yet. - A script runs once on each bot the user picks, with the global bot set to that bot. On "PC only" bot is nil. - A script that loops over getBots() must run on one bot or PC only, or every running copy repeats it. - Put sleep(ms) in every loop and give each loop a limit or a way out. - Before placing or breaking a tile, check hasAccess(x, y) > 0, and act only on tiles in reach of the bot. - Give the whole script in one Lua code block, then one or two lines on what to pick before pressing Run. ## Getting started A Puniko script is plain Lua 5.4. Pick the bots to run it on and it runs once on each of them, with the global bot set to that bot. Read the world with the get* functions, act with bot:..., and reach every bot on the PC with getBots(). ### your first script `bot · print · sleep` Everything acts on this run's bot. print writes to the Output console; sleep pauses the script, not the bot. ```lua print("Hi, I am " .. bot.name) bot:say("online!") sleep(1000) bot:warp("BUYWORLD") ``` ### PC only (no bot) `bot == nil` Run a script on "PC only" (no bot picked) and bot is nil, so every bot:... line stops with an error and shortcuts like getTile() return nil. Reach your bots with getBot(name) or getBots() instead. ```lua if not bot then for _, b in ipairs(getBots()) do print(b.name, b.status) end return end ``` ### the whole fleet `getBots()` getBots() returns every bot on this PC, each a full bot object. Run a fleet script like this on ONE bot or on PC only, or every running copy repeats the actions. ```lua for _, b in ipairs(getBots()) do b:warp("MYFARM") b:say("here!") end ``` ### loops that survive `while · sleep · hasAccess` Sleep inside every loop, give it a limit, and act only on tiles next to the bot. Before you place or break, check hasAccess(x, y) > 0, which means you may build there. ```lua local x, y = bot.x + 1, bot.y if hasAccess(x, y) > 0 then for i = 1, 20 do local t = getTile(x, y) if not t or t.fg == 0 then break end bot:hit(x, y) sleep(300) end end ``` ### make it a tool `settings{} · ui.progress · ui.table · notify` Ask for settings in a form on growbgl.com, show progress, list what you found in a table people can sort and export, and send an alert when done. Nobody has to open the code. ```lua local s = settings{ title = "Vend check", ui.world("world", "World", "BUYWORLD") } bot:goTo(s.world) local vends = bot:findTiles(function(t) return t.extraType == 24 end) local t = ui.table{ title = "Vends in " .. s.world, columns = { "Item:item", "Price:price", "Reachable:yesno" } } for i, v in ipairs(vends) do local e = v:getExtra() t:add{ e.id, e.price, bot:isReachable(v.x, v.y) } ui.progress("Vends", i, #vends) end notify("Checked " .. #vends .. " vends", "good") ``` ### test run `Scripts tab > Test` Press Test instead of Run to try a script safely: it reads the live world, but actions are printed instead of sent, and web calls, files and bot or proxy changes are blocked. Forms use their defaults, questions get their first button (ui.confirm is true), alerts are not sent, and it stops after 5 minutes with a summary. ```lua bot:place(5, 6, "Dirt") -- the Test panel shows: would place Dirt at (5, 6) ``` ## The bot This run's bot: its live fields, account, connection, switches and look. Every bot:... call works the same on any other bot object, e.g. b:connect(). ### bot `bot.name · status · world · online · x · y · gems · level · ping` Live fields, read fresh each time. bot.x / bot.y are the TILE it stands on; compare bot.status with BotStatus.*. ```lua if bot.online and bot.world == "BUYWORLD" then print(bot.name, "has", bot.gems, "gems") end ``` ### more fields `bot.id · custom_status · ingame · posx · posy · netid · userid · auto` bot.id is the record id that getBot(id) and removeBot take, and custom_status is the status line on the page (you can set it). ingame is true once it has entered the game after login, posx / posy are pixels, and auto says what its automations are doing. ```lua bot.custom_status = "farming" print(bot.id, bot.ingame, bot.posx, bot.posy) ``` ### getUsername / getLogin `getUsername() / bot:getLogin()` The GrowID of this run's bot, same as bot.name. ```lua print("running on", getUsername()) ``` ### getLocal `getLocal()` This bot as a player: .name .netid .userid .x .y (tile) .posx .posy (pixels). nil when the bot is not on this PC. ```lua local me = getLocal() if me then print("at tile", me.x, me.y) end ``` ### where it is `bot:isInWorld([name]) / isInTile(x, y) / getPosition() / getPing()` isInWorld() is true in any world, or in the named one (names in capitals); isInTile(x, y) checks the tile it stands on. getPosition() returns its tile x, y and getPing() its ping in ms. ```lua if bot:isInWorld("MYFARM") then local x, y = bot:getPosition() print("at", x, y, "ping", bot:getPing()) end ``` ### getGems / getLevel `bot:getGems() / bot:getLevel()` The gem count (-1 when the bot is not on this PC) and the level last seen. checkLevel() reads the level fresh. ```lua print(bot:getGems(), "gems, level", bot:getLevel()) ``` ### profile `bot:getProfile([fresh]) / checkLevel() / checkAge() / checkPlaytime()` The bot wrenches itself (it must be in a world) and reads its level, account age in days and hours played, or returns nil, why. getProfile gives { level, age, playtime, name, fresh } and getProfile(false) the last read; checkMyLevel / checkMyAge / checkMyPlaytime are the same. ```lua local lvl, why = bot:checkLevel() if lvl then print("level", lvl) else print(why) end ``` ### account info `bot:getAge() / getPlaytime() / getActiveTime() / getProxy() / askLevel()` Age in days and hours played from the last profile read, seconds connected this session, and the proxy it connected through (host:port, empty when direct). askLevel() only sends the self-wrench, without waiting. ```lua print(bot:getAge() .. "d old,", bot:getPlaytime() .. "h played, via", bot:getProxy()) ``` ### connect / disconnect `bot:connect() / bot:disconnect()` Bring a bot online, or drop its link. With Auto reconnect on, a disconnected bot comes back after the reconnect delay. ```lua if not bot.online then bot:connect() end ``` ### setOption `bot:setOption(key, value) / bot:getOption(key)` Read or set one of the bot's switches, saved on the site. Values are strings, "1" / "0" for on / off; the common ones also work as properties. getOption gives nil for a switch that was never set (its default applies), so read Auto reconnect as bot.auto_reconnect (true / false). ```lua bot:setOption("reconnect", "1") -- Auto reconnect on bot:setOption("range", "6") -- collect radius bot.auto_collect = true -- same as setOption("collect", "1") print(bot:getOption("modleave")) ``` ### option keys `reconnect · collect · range · direct · loginpx · rcmin · rcmax · autoaccept` reconnect (Auto reconnect, on by default), collect (auto-collect drops, off by default), range (collect radius 1-8, default 2), direct (never use a proxy), loginpx (log in through the Login proxies), rcmin / rcmax (random reconnect delay, 3-300 s), autoaccept (accept World Lock access offers by itself). Properties: bot.auto_reconnect, bot.auto_collect, bot.range, bot.direct, bot.modleave. A value the page would not allow is not saved. loginpin (which login proxy) can be read, but only the page sets it. ```lua bot:setOption("rcmin", "10") bot:setOption("rcmax", "30") bot.range = 4 ``` ### mod rules `modleave · mldc · mldcall · mlnr · mlback` What the bot does when a moderator joins its world. modleave leaves the world (on by default). mldc also disconnects the bot; with mldc on, mldcall disconnects every bot, mlnr turns Auto reconnect off, and mlback turns it back on after that many minutes (0-1440, 0 = stay off). ```lua bot:setOption("modleave", "1") bot:setOption("mldc", "1") bot:setOption("mlnr", "1") bot:setOption("mlback", "30") -- back on after 30 min ``` ### stop rules `rcblock` Which login answers stop Auto reconnect instead of trying again, as one number. Add up: 1 Wrong password, 2 Account banned, 4 Account suspended, 8 Game update needed, 16 IP limited, 32 Login failed, 64 Invalid account, 128 Maintenance, 256 Too many logins. The default 79 stops on wrong password, banned, suspended, update needed and invalid account. ```lua bot:setOption("rcblock", tostring(79 + 128)) -- also stop on Maintenance ``` ### token refresh `tokenrf · tokenrfh · tokenrfrc` Token bots only. tokenrf turns Auto refresh token on, tokenrfh is how many hours apart (1-24, default 6), tokenrfrc reconnects after each refresh (off by default). getOption("tokenrfat") is the last refresh (unix seconds) and getOption("tokenrfst") how it went: ok, dead, ip, noproxy or fail. ```lua bot:setOption("tokenrf", "1") bot:setOption("tokenrfh", "12") print(bot:getOption("tokenrfst")) ``` ### getInterval / setInterval `bot:getInterval(Action.x) / bot:setInterval(Action.x, seconds)` Seconds between two actions of that kind in the built-in automations (see Action under Enums). setInterval changes one bot until Puniko restarts, 0 goes back to the account value; your own script actions are never slowed. ```lua print(bot:getInterval(Action.harvest)) bot:setInterval(Action.harvest, 0.3) ``` ### setStatus `bot:setStatus(text)` Set the custom status line shown on the page, same as bot.custom_status = text. Handy as a per-bot flag your other scripts can read. ```lua bot:setStatus("farming lvl " .. bot.level) ``` ### console `bot:getConsole() / bot:getLog()` The bot's game console: getConsole().contents is the list of lines, getLog().content the same lines as one text. Both have :append(text) and :clear(). It keeps the last 200 lines, oldest first, colour codes kept; to catch new lines use on(Event.console, fn) instead of counting lines. ```lua for _, line in ipairs(bot:getConsole().contents) do if line:find("world is locked") then bot:leave() end end ``` ### updateBot `bot:updateBot(mac, rid)` Set the device mac + rid and reconnect in one call, so the bot logs back in with the new fingerprint. It does NOT change the GrowID or password. ```lua bot:updateBot(oneMac, oneRid) sleep(15000) print(oneMac, bot.status) ``` ### setSkin `bot:setSkin(n)` Change the skin colour, everyone sees it at once. n = 1..8 for the basic tones (1 darkest, 8 lightest), or a raw colour number. ```lua bot:setSkin(8) -- lightest ``` ### login fields `bot:setCountry(code) / setMac(mac) / setRid(rid) / setPlatform(platform)` The flag country, the device fingerprint and the login platform ("windows", "android", "ios" or "macos"). They apply on the next reconnect; a token bot keeps the platform its token was made on. ```lua bot:setCountry("tr") bot:setMac("AA:BB:CC:DD:EE:FF") bot:setPlatform("android") bot:disconnect(); bot:connect() ``` ## World and players What the bot sees, live. Reads are instant and never send a packet. x / y are always TILE coords. In a fleet script, read from the bot you mean (b:getTile), not the shortcut. ### getWorld `getWorld()` The bot's world, or nil when it is not in one: .name, .x (width), .y (height), .tile_count. ```lua local w = getWorld() if w then print("in", w.name, w.x .. "x" .. w.y) end ``` ### world object `w:getTile(x, y) / getTiles() / getPlayer(key) / getPlayers() / getObject(uid) / getObjects() / getLocal() / hasAccess(x, y) / isValidPosition(x, y)` The same reads on the world object. isValidPosition is true when x, y is inside the world; w.tiles, w.objects and w.players are the lists as fields. ```lua local w = getWorld() if w and w:isValidPosition(x, y) then print(w:getTile(x, y).fg) end ``` ### growscan `w.growscan.getTiles() / w.growscan.getObjects()` Counts by item id: blocks placed in the world, and items lying on the floor. ```lua local placed = getWorld().growscan.getTiles() print("World Locks placed:", placed[242] or 0) ``` ### getTile `getTile(x, y)` The tile at x, y, or nil. Fields: .fg / .foreground (0 = empty), .bg / .background, .flags, .label, .extraType (0 none, 1 door, 2 sign, 3 lock, 4 tree, 24 vend...), and on trees .grownSeconds / .seedFruit; methods :getExtra(), :hasExtra(), :hasFlag(f), :canHarvest(). ```lua local t = getTile(50, 30) if t and t.fg ~= 0 then print("block here:", getInfo(t.fg).name) end ``` ### tile:getExtra `tile:getExtra()` The data on a lock, vend or door tile, or nil: .type, .owner (user id), .id (the item in a vend or display), .price (vend: WL each, negative = items per WL, 0 = no price), .amount (the count in a MagPlant, Gaia or Unstable Tesseract; always 0 on a vend, because the world data has no vend stock), .access (a lock's admin user ids). ```lua local t = getTile(20, 25) local e = t and t:getExtra() if e and e.type == 24 then print(getInfo(e.id).name, "@", e.price) end ``` ### canHarvest `tile:canHarvest()` True when the tree on that tile has grown long enough to harvest. ```lua local t = getTile(bot.x + 1, bot.y) if t and t:canHarvest() then bot:harvest(t.x, t.y) end ``` ### getTiles `getTiles() / getTilesSafe()` Every tile in the world as a list (getTilesSafe is the same). Big worlds are large, so scan now and then, not in a tight loop. ```lua local locks = 0 for _, t in ipairs(getTiles()) do if t.extraType == 3 then locks = locks + 1 end end print("locks:", locks) ``` ### hasAccess `hasAccess(x, y)` Tile build access as a NUMBER: 0 = no access, 1 = you have access (your lock or its admin list), 2 = public. hasAccess(x, y) > 0 means you may build there. ```lua if hasAccess(x, y) > 0 then bot:place(x, y, 2) end ``` ### getPlayers `getPlayers() / getPlayer(name | netid)` Players in the world now, or one of them: .name .netid .userid .x .y (tile) .posx .posy .country .isModerator .isSuperModerator. getPlayer(name) matches the exact name (colours removed, case counts). ```lua for _, p in ipairs(getPlayers()) do if p.isModerator then bot:leave() end end ``` ### getObjects `getObjects() / getObject(uid) / bot:getDrops()` Items lying on the floor. Each has .uid (also .oid, used by collectObject), .id (item id), .count, .tilex, .tiley. ```lua for _, d in ipairs(getObjects()) do if d.id == 242 then bot:collectObject(d.uid) end end ``` ### findTiles / findObjects `bot:findTiles(item | fn) / findTile / countTiles / findObjects([item | fn]) / nearestObject` Tiles holding a block (front or back), or floor items, nearest first. Pass an item (id or name) or a function that picks; findTile and nearestObject give the first one. ```lua local vends = bot:findTiles(function(t) return t.extraType == 24 end) print(#vends, "vends") ``` ### getReadyTrees `bot:getReadyTrees([seed])` Trees ready to harvest (of that seed when given), nearest first. ```lua for _, t in ipairs(bot:getReadyTrees()) do bot:harvest(t.x, t.y) end ``` ### world owner `bot:getWorldOwner() / ownsWorld() / isWorldLocked()` The world lock's owner (user id) and its tile, whether this bot owns the world, and whether there is a world lock at all. ```lua if bot:ownsWorld() then print("my world") end ``` ### canBuild / inReach / distance `bot:canBuild(x, y) / bot:inReach(x, y[, range]) / bot:distance(x, y)` canBuild is hasAccess(x, y) > 0 as true / false. inReach is true within punch reach (about 2 tiles) or range tiles; distance is in tiles. ```lua if bot:canBuild(x, y) and bot:inReach(x, y) then bot:hit(x, y) end ``` ### isReachable `bot:isReachable(x, y)` Could a visiting player walk and jump from the main door to that tile, or next to it? true / false, or nil, why when it can not tell. Use it for "can a buyer get here"; bot:getPath is the bot's own route. ```lua for _, t in ipairs(bot:findTiles(function(t) return t.extraType == 24 end)) do print(t.x, t.y, bot:isReachable(t.x, t.y) and "reachable" or "blocked") end ``` ## Moving and actions Do things in the world. Each call is queued on that bot's own connection and sends the real client's packet. place, hit and wrench only land within about 2 tiles, so walk next to the tile first. ### warp / leave `bot:warp(world[, timeout]) / bot:leave()` Warp to a world (name in quotes), or "WORLD|DOORID" for a door. It waits and returns true, "entered" or false, why; a timeout in seconds limits the wait and 0 sends it without waiting. leave() (or leaveWorld()) goes back to EXIT. ```lua local ok, why = bot:warp("BUYWORLD") if not ok then print("warp failed:", why) end for _, b in ipairs(getBots()) do b:warp("MYFARM", 0) end -- no wait ``` ### goTo / walkNear `bot:goTo(world[, x, y]) / bot:walkNear(x, y) / bot:walkTo(x, y)` goTo warps when the bot is not in that world yet, then walks to the tile. walkNear walks to the tile, or to the nearest free tile in reach when it is solid; walkTo is findPath. ```lua bot:goTo("MYFARM", 20, 30) bot:walkNear(vendX, vendY) ``` ### findPath / getPath `bot:findPath(x, y) / bot:getPath(x, y)` findPath walks to the tile around blocks and returns true once there, or false, why. getPath returns the route as a list of { x, y } without moving. ```lua local ok, why = bot:findPath(50, 30) print("steps:", #bot:getPath(10, 20)) ``` ### move `bot:move(dir) / moveTo(dx, dy) / moveLeft([n]) / moveRight / moveUp / moveDown / moveTile(x, y)` Step one tile ("left", "right", "up", "down"), by an offset, n tiles one way, or straight toward tile x, y. These do not go around blocks; findPath does. ```lua bot:move("right") bot:moveRight(3) bot:moveTile(20, 24) ``` ### face `bot:face("left" | "right") / bot:setDirection(faceLeft)` Turn without moving; setDirection(true) faces left. Drops land on the tile the bot faces. ```lua bot:face("left") bot:drop(242, 1) ``` ### say `bot:say(text)` Send a chat message or a /command. ```lua bot:say("selling dls cheap!") bot:say("/who") ``` ### place `bot:place(x, y, item)` Place an item from the bag on a tile. The tile must be in reach and empty, and you need build access. ```lua if hasAccess(bot.x, bot.y - 1) > 0 then bot:place(bot.x, bot.y - 1, 2) -- Dirt above end ``` ### hit `bot:hit(x, y) / punch(x, y) / breakTile(x, y)` Punch the tile at x, y once with the Fist. Blocks take several hits; breakBlock does the whole job. ```lua bot:hit(bot.x + 1, bot.y) ``` ### breakBlock `bot:breakBlock(x, y[, maxHits])` Checks access, walks near and punches until the block (or the background when there is no block) is gone. Returns true, "broken" or false, why. ```lua local ok, why = bot:breakBlock(10, 24) if not ok then print("could not break:", why) end ``` ### harvest / harvestAll `bot:harvest(x, y) / bot:harvestAll([seed][, collect])` Harvest one ready tree, or every ready tree (of one seed when given) and then pick up the drops; collect = false skips that. harvest walks near the tree, checks access and waits: true, "harvested" or false, why. harvestAll returns how many it harvested. ```lua local n = bot:harvestAll("Dirt Seed") print("harvested", n) ``` ### plant `bot:plant(x, y, seed)` Plant a seed (id or name) on a tile. Waits for the server and returns ok, why. ```lua bot:plant(bot.x + 1, bot.y, "Dirt Seed") ``` ### wrench / active `bot:wrench(x, y) / bot:wrenchPlayer(netid) / bot:active(x, y)` wrench opens a tile's or a player's menu, which arrives as a game dialog (see Game dialogs). active (or activate) taps a tile, like a player clicking it. ```lua bot:wrench(57, 23) bot:active(30, 24) ``` ### enter / useTile `bot:enter([password]) / bot:useTile() / bot:enterDoor()` Enter the door the bot stands on, with the password for a password door. useTile and enterDoor use the tile under the bot. ```lua bot:enter() bot:enter("letmein") ``` ### respawn `bot:respawn()` Go back to the world's checkpoint. A dead bot also respawns by itself, so do not loop this. ```lua bot:respawn() ``` ### confirmed actions `confirmActions(true) / bot:place(x, y, item, true)` By default an action returns true as soon as it is sent. Ask for the server's answer and it waits and returns ok, why, where why is the game's own words when it refused. ```lua confirmActions(true) -- place, hit, drop, trash, collect, buy, retrieve now wait local ok, why = bot:place(x, y, 2) if not ok then print(why) end bot:hit(x, y, 0) -- 0: this call never waits bot:place(x, y, 2, 5) -- wait up to 5 s for this one ``` ### automations `bot:startAuto(name[, options]) / stopAuto([name]) / autoStatus()` Switch the Automations tab's jobs on and off from a script: harvest, plant, transfer, fish, farm, clear, spam or message. Options use the tab's own names; stopAuto() with no name stops them all. ```lua bot:startAuto("harvest", { seed = 15 }) print(bot:autoStatus()) ``` ## Inventory and items The bag, item info, and moving items in and out: pick up, drop, trash, buy, retrieve and wear. ### getInventory `getInventory()` The bag: .known (false until it first arrives), .itemcount, .slotcount, :getItems() (each .id .count), :getItem(id | name), :getItemCount(id | name) (or :findItem) and :canCollect(id). ```lua local inv = getInventory() if inv.known then for _, it in ipairs(inv:getItems()) do print(getInfo(it.id).name, it.count) end end ``` ### bag checks `bot:getItemCount(item) / hasItem(item[, n]) / countItem(item) / freeSlots() / isBagFull() / canHold(item[, n])` Quick checks by id or name. freeSlots is nil until the bag is known; canHold says whether n more fit. ```lua if bot:isBagFull() then bot:dropAll("Dirt") end print(bot:countItem("World Lock")) ``` ### getLocks `bot:getLocks()` The bag's lock value in World Locks, then the World, Diamond and Blue Gem Lock counts. getWorldLocks is the same. ```lua local total, wl, dl, bgl = bot:getLocks() print("worth", total, "WL") ``` ### getInfo / getInfos `getInfo(id | name) / getInfos()` One item's entry from items.dat: .id .name .rarity .max_amount .grow_time and more; a name must match exactly, any case. A block's seed is its id + 1. getInfos() is every item as a list. ```lua local seed = getInfo("Dirt Seed") print(seed.id, "grows in", seed.grow_time, "s") ``` ### collect `bot:collect([range]) / collectObject(uid[, range]) / collectOne(uid[, range])` Pick up every floor item within range tiles (2 by default, 10 at most), or one item by its .uid from getObjects. ```lua bot:collect(5) ``` ### collectItem / collectAll `bot:collectItem(item[, most]) / bot:collectAll([fn][, most])` Walk to each floor pile of that item (or every pile, or the ones fn picks) and pick it up. Returns how many it got. ```lua bot:collectItem("World Lock") ``` ### drop / trash `bot:drop(id, count) / trash(id, count) / fastDrop / fastTrash` Drop items on the tile the bot faces, or trash them; count 0 = the whole stack. fastDrop and fastTrash are the same calls. ```lua bot:face("left") bot:drop(242, 0) ``` ### dropAll / trashAll `bot:dropAll(item) / bot:trashAll(item)` Drop or trash the whole stack (id or name) and wait for the server: ok, why. ```lua local ok, why = bot:trashAll("Rock") ``` ### dropTidy `bot:dropTidy(item[, count]) / dropTidy(item[, count])` Like a drop, but when the faced tile is a wall or full it walks beside the nearest free spot and drops there. count defaults to the whole stack; returns ok, why, count. ```lua local ok, why = bot:dropTidy("Dirt") ``` ### buy `bot:buy(x, y, count)` Buy count items from the vending machine at that tile; the buy and confirm dialogs are handled for you. ```lua bot:buy(20, 25, 10) ``` ### retrieve `bot:retrieve(x, y[, amount])` Take items out of a Gaia's Beacon, Unstable Tesseract or MagPlant at that tile. No amount takes all. ```lua bot:retrieve(30, 28) ``` ### wear / use `bot:wear(id) / use(id) / unwear(id)` Wear an item, use a consumable, or take a worn item off. ```lua bot:wear(1420) ``` ### buyBackpack `bot:buyBackpack()` Buy the next backpack upgrade (more bag slots). ```lua if bot:freeSlots() == 0 then bot:buyBackpack() end ``` ## Game dialogs The dialogs the game opens on a bot (a vend, a lock, a shop NPC, a player). Read them, fill them in and press their buttons. ### getDialog `getDialog():get() / bot:getDialog():get()` The open game dialog, parsed: .name (its end_dialog name), .text (all its text), .buttons (each .name and .label), .inputs and .checks by field name. :size() is 0 when none is open. ```lua local d = getDialog():get() if d:size() > 0 then print(d.name, d.text) for _, b in ipairs(d.buttons) do print("button", b.name, b.label) end end ``` ### wait for one `getDialog():wait([name][, seconds]) / bot:waitDialog / bot:wrenchDialog(x, y[, seconds]) / bot:wrenchPlayerDialog(netid[, seconds])` Wait for the next dialog (with that name, or any; 5 s by default). wrenchDialog wrenches a tile and waits for its dialog, wrenchPlayerDialog does it for a player; each returns the dialog, or nil, why. ```lua local d, why = bot:wrenchDialog(20, 25) if d then print("opened", d.name) else print(why) end ``` ### answer it `d:set(name, value) / d:check(name[, on]) / d:fill(values) / d:click(button[, waitSecs]) / d:submit([waitSecs]) / d:close()` Fill text boxes and checkboxes, then press a button by its name or its text. With waitSecs, click and submit wait for the next dialog and return it. ```lua local d = bot:wrenchDialog(20, 25) if d and d:has("Are you sure") then d:click("OK") elseif d then d:close() end ``` ### look inside `d:has(text) / d:button(key) / d:get(key) / d:getInt(key) / d:find(key) / d:getParams(key) / d:contains(key) / d:dump()` has searches the text (any case) and button finds a button by name or text. get / getInt (or getLong) read one raw line's value, find and getParams return the first or every line starting with key (split at |), contains says if one exists, dump is the raw markup. ```lua local d = getDialog():get() print(d:get("end_dialog")) for _, p in ipairs(d:getParams("add_button")) do print(p[2]) end ``` ### shortcuts `getDialog():clear() / :click(button) / :submit() / :has(text)` The same calls straight on the dialog that is open now; clear closes it. ```lua getDialog():click("Buy") ``` ### parseDialog `parseDialog(text[, bot])` The same dialog object from markup you already have, e.g. the text an Event.dialog handler got. ```lua on(Event.dialog, function(name, text) local d = parseDialog(text) print(name, #d.buttons, "buttons") end) ``` ## Events and waiting React to what the server sends a bot. Prefer on() and waitFor(): they need no listenEvents and work on any bot. addEvent is the older way and still works. For anything a player gave or paid, trust the system console, never world chat. ### on / once / off `on(kind, fn) / once(kind, fn) / off(h)` Call fn for every event of that kind (once: only the next one) in the background while the script goes on. Returns a handle; h:off() or off(h) stops it, and bot:on / bot:once do the same for another bot. ```lua local h = on(Event.mod_enter, function(name) notify("Mod " .. name .. " in " .. bot.world, "warn") bot:leave() end) ``` ### waitFor `waitFor(kind[, filter][, seconds])` Wait right here for the next matching event (30 s by default) and get its values, or nil, "timed out after N s". A filter is a name (player or item), a number (an id), part of a text, or a function; bot:waitFor waits on another bot. ```lua bot:warp("BUYWORLD", 0) local world = waitFor(Event.world_enter, 15) local p = waitFor(Event.player_join, "MyFriend", 60) ``` ### ready-made events `Event.world_enter / player_join / mod_enter / console / inventory / drop_added / tile_changed / dialog / disconnected / ...` Already decoded, the handler gets plain values: world_enter(world), world_exit(world), warp_failed(text), player_join(player, already), player_leave(player), mod_enter(name, player, already), console(text, raw), inventory(id, old, new), gems(old, new), level(old, new), drop_added(object), drop_removed(object, netid), drop_changed(object, oldCount), tile_changed(x, y, fg, bg, oldFg, oldBg), dialog(name, text), trade_open(name, netid), disconnected(reason). ```lua on(Event.inventory, function(id, old, new) if id == 242 and new > old then print("got", new - old, "WL") end end) ``` ### payments `Event.console` The safe signal for donations and vend sales: match the real system line in the console and read the name and amount from it. Players can fake chat, never trust it for a payment. ```lua on(Event.console, function(text) if text:find("into the Donation Box") then print("donation:", text) -- parse name + amount here end end) ``` ### listenEvents `listenEvents([seconds])` Start receiving events for addEvent. With seconds it blocks and handles events for that long; without, it runs in the background. ```lua listenEvents() -- background listenEvents(10) -- or block for 10 s ``` ### addEvent `addEvent(kind, fn)` The older handler, needs listenEvents(). A text kind calls fn(message, netid) with the text; a call kind calls fn(ev, netid); Event.any calls fn(ev, netid); the ready-made kinds get their plain values. ```lua addEvent(Event.text, function(msg) print("chat:", msg) end) listenEvents() ``` ### raw kinds `Event.text · chat · game_message · generic_text / Event.call · callfunction · variantlist · consoleMessage / Event.any · packet · update_packet · track_packet` text, chat, game_message and generic_text are the server's raw text packets (action|log and the like), never player chat, and their netid is 0. For world chat see player chat below. callfunction, variantlist and consoleMessage are call events (every OnXxx, check ev.fn yourself), and packet / update_packet see everything, like any. ```lua on(Event.call, function(ev) if ev.fn == "OnConsoleMessage" then print(ev:get(1):getString()) end end) ``` ### player chat `on(Event.call, fn) · ev.fn == "OnTalkBubble"` World chat arrives as a call event: ev:get(1):getInt() is the speaker's netid and ev:get(2):getString() the text, colour codes kept. Your own bot's bubbles and the game's notes over its head come through too. Never trust chat for payments, check the console. ```lua on(Event.call, function(ev) if ev.fn ~= "OnTalkBubble" then return end local p = getPlayer(ev:get(1):getInt()) local text = removeColor(ev:get(2):getString()) if p and p.name ~= bot.name and text == "!hi" then bot:say("hi " .. p.name) end end) ``` ### ev `ev.type / ev.text / ev.netid / ev.fn / ev:get(i) / ev:size() / ev:print()` A raw event: its kind, its text, who it is about and the call-function name. ev:get(i):getString() / getInt() / getFloat() / getType() reads value i (0 is the function name), size counts them, print joins them as text. ```lua on(Event.any, function(ev) print(ev.type, ev.fn or ev.text or "") end) ``` ### stop listening `removeEvent(kind) / removeEvents() / stopEvents() / unlistenEvents()` Drop the addEvent handlers for one kind or all of them, or stop listening (unlistenEvents is the same as stopEvents). ```lua removeEvents(); stopEvents() ``` ## Raw packets For power users: send any packet the game understands. The named actions cover the everyday jobs; a bad packet just gets the bot kicked. ### sendPacket `bot:sendPacket(type, body) / sendText(s) / sendMessage(s)` Send a raw TEXT packet: type 2 = generic text (action|...), 3 = game message. sendText(s) is sendPacket(2, s) and sendMessage(s) is sendPacket(3, s). ```lua bot:sendText("action|respawn\n") bot:sendPacket(2, "action|dialog_return\ndialog_name|x\nbuttonClicked|ok") ``` ### GameUpdatePacket `GameUpdatePacket.new()` A blank BINARY game packet to fill and send with bot:sendRaw. Fields (all 0): type, object_type, count1, count2, netid, item, flags, float_var, int_data, pos_x, pos_y, pos2_x, pos2_y, particle_rotation, int_x, int_y. ```lua local p = GameUpdatePacket.new() p.type = 3 -- tile change request p.netid = bot.netid p.int_data = 18 -- Fist p.int_x = 50; p.int_y = 24 bot:sendRaw(p) ``` ### sendRaw `bot:sendRaw(pkt) / bot:sendPacketRaw(pkt)` Send a GameUpdatePacket you built (both names are the same call). It is on you to make it well-formed. ```lua bot:sendRaw(p) ``` ### sendCall `bot:sendCall(name, ...)` Send a call-function packet (an OnXxx). Extra args type themselves (text, whole number, decimal), or wrap one with variant.new():set(...); you can also pass one variantlist you built. ```lua bot:sendCall("OnConsoleMessage", "hi") ``` ### variant `variant.new()` One typed value: :set(v), or :set(x, y) / :set(x, y, z) for a vector. Read it with :getString() / :getInt() / :getFloat() / :getVector2() / :getVector3(); :getType() returns a VariantType. ```lua local v = variant.new():set(5) print(v:getType() == VariantType.int32) ``` ### variantlist `variantlist.new()` A list of variants: vl:get(i) returns the variant at i (made on the spot, so you can set it), vl:size(), vl:print(). ```lua local vl = variantlist.new() vl:get(0):set("OnFoo"); vl:get(1):set(42) bot:sendCall(vl) ``` ## Script UI: questions and menus Turn a script into a tool people use without reading Lua. A form opens on the Puniko page when the script starts, questions pop up while it runs, and a menu can stay open to steer it. Only the person who runs it sees them. ### settings `settings{ title, text, field..., buttons, cancel, timeout, ask, remember }` Shows a form when the script starts and returns the values by field key, then the button pressed. It opens with the last answer on this PC (per bot) and goes on with those after timeout seconds (120 by default); ask = false never shows it, remember = false does not save. The button is nil when the form timed out, was closed or cancelled, and the script still goes on with the values: use if button ~= "Start" then return end when it must not start on its own. A Test run gets the first button. ```lua local s = settings{ title = "Auto farm", ui.world("farm", "Farm world", "MYFARM"), ui.item("seed", "Seed", "Dirt Seed"), ui.number("rounds", "Rounds", 10, 1, 100), } bot:goTo(s.farm) ``` ### fields `ui.text · ui.number · ui.toggle · ui.choice · ui.item · ui.world · ui.label · ui.spacer` ui.text(key, label, default, hint), ui.number(key, label, default, min, max, step), ui.toggle(key, label, default) (or ui.check / ui.checkbox), ui.choice(key, label, options, default), ui.item(key, label, default) (the value is the item id), ui.world(key, label, default), ui.label(text), ui.spacer(). Values come back as the right type. ```lua ui.choice("mode", "Mode", { "Fast", "Safe" }, "Safe") ``` ### ui.bots (new) `ui.bots(key, label[, default])` Your bots with tick boxes. The value is a list of bot ids; getBot(id) gives each bot. ```lua local s = settings{ ui.bots("crew", "Bots to send") } for _, id in ipairs(s.crew) do getBot(id):warp("MYFARM", 0) end ``` ### ui.list (new) `ui.list(key, label[, default, hint])` A box with one entry per line (worlds, items, names). The value is a list of strings, empty lines left out. ```lua local s = settings{ ui.list("worlds", "Worlds", { "FARM1", "FARM2" }, "one per line") } for _, w in ipairs(s.worlds) do bot:warp(w) end ``` ### ui.multi (new) `ui.multi(key, label, options[, default])` Pick several of the options. The value is a list of the picked ones. ```lua ui.multi("trash", "Trash these", { "Rock", "Dirt", "Lava" }, { "Rock" }) ``` ### ui.section (new) `ui.section(title[, open])` A foldable header; the fields after it sit inside it until the next section. open = false starts it folded. ```lua settings{ ui.section("Selling"), ui.toggle("autosell", "Sell on the way"), ui.section("Advanced", false), ui.number("delay", "Delay (ms)", 300), } ``` ### field:when (new) `field:when(key[, value])` Show a field only while the toggle key is on, or while the choice key is value. ```lua settings{ ui.toggle("autosell", "Auto sell"), ui.number("price", "Sell price", 20):when("autosell"), ui.choice("mode", "Mode", { "Fast", "Safe" }), ui.number("pause", "Pause (s)", 5):when("mode", "Safe"), } ``` ### ui.ask `ui.ask{ title, text, field..., buttons, cancel, timeout }` A question with any fields and buttons. Returns the button pressed and the values, or nil, values, why when nobody answered; no timeout waits for ever. ```lua local button, v = ui.ask{ title = "Found a cheap vend", text = "Buy 10 now?", ui.number("count", "How many", 10, 1, 200), buttons = { "Buy", "Skip" }, } if button == "Buy" then bot:buy(x, y, v.count) end ``` ### quick questions `ui.confirm(text[, title, timeout]) / ui.input(label[, default, title, timeout]) / ui.choose(text, options[, title, timeout])` confirm returns true or false, input the text typed, choose the option picked and its number; each is nil when nobody answered. In a Test run they answer with the first button, so confirm is true. ```lua if ui.confirm("Drop all World Locks here?") then bot:dropAll("World Lock") end local world = ui.input("Next world", "BUYWORLD") ``` ### ui.menu `ui.menu{ title, field..., buttons }` A panel that stays open while the script runs. Read it any time: m:get(key), m:getAll(), m:clicked(button) (true once per click), m:set(key, value), m:close(). ```lua local m = ui.menu{ title = "Farm", ui.toggle("on", "Running", true), buttons = { "Drop now" } } while true do if m:get("on") then bot:harvestAll() end if m:clicked("Drop now") then bot:dropAll("Dirt") end sleep(1000) end ``` ### DialogBuilder `DialogBuilder.new() / getDialog():setCustom(b) / getDialog():closeCustom()` The same menu built step by step: :setTitle, :addLabel, :addCheckbox, :addInput, :addNumber, :addChoice, :addItem, :addWorld, :addSpacer, :addButton, and :clear() to start over. setCustom shows or updates it, closeCustom takes it off the page. ```lua local b = DialogBuilder.new():setTitle("Vend bot") b:addCheckbox("buy", "Buy cheap items", true):addButton("stop", "Stop") getDialog():setCustom(b) ``` ### getCustom `getDialog():getCustom()` Reads that menu: r:get(name) (or :getString) as text, :getInt, :getNumber, :getBool, and :isClicked(button), true once per click. ```lua local r = getDialog():getCustom() if r:isClicked("stop") then return end if r:getBool("buy") then print("buying") end ``` ## Script UI: live view and alerts Show what the script is doing while it runs. It all appears next to the bot on the Puniko page and in the Scripts tab, and goes away when the script ends, except result tables, which stay until closed. ### progress / stat `ui.progress(label, done, total) / ui.stat(label, value) / ui.remove(label) / ui.clear()` A progress bar that reads "12 / 40", and lines with a value (numbers get thousands commas). Call again with the same label to update; the first progress bar also shows in the bot list. ```lua for i, w in ipairs(worlds) do ui.progress("Worlds", i, #worlds) ui.stat("Gems", bot.gems) bot:warp(w) end ``` ### ui.chart (new) `ui.chart(label, value[, keep])` Adds a point to a small line chart and shows the newest value. It keeps the last keep points (60 by default, 300 at most). ```lua every(60, function() ui.chart("Gems", bot.gems) end) ``` ### ui.mark (new) `ui.mark(x, y[, color, label]) / ui.unmark(x, y) / ui.clearMarks()` Highlight a tile on this bot's world map on growbgl.com: color "green" (default), "red", "yellow", "blue" or "purple", the label shows on hover. Up to 200 marks; marking a tile again changes it. ```lua for _, t in ipairs(bot:getReadyTrees()) do ui.mark(t.x, t.y, "green", "ready") end ui.unmark(10, 20) ui.clearMarks() ``` ### notify `notify(text[, level])` An alert, level "info", "good", "warn" or "bad": a toast while the Puniko page is open in front, else a push to the devices where you turned on Alerts (the bell in the Scripts tab). In Puniko Settings you pick what happens while the page is open: a notification, or a sound you choose. About 20 a minute per script; alerts use the same 2 devices as the Realtime Tracker. ```lua notify("Bought 10 Dirt for 2 WL", "good") ``` ### notify buttons (new) `notify(text, level, buttons) / a:wait([seconds]) / a:clicked() / a:close()` With up to 3 buttons it returns an alert: a:wait(seconds) gives the button pressed (nil when none in time; no seconds = 5 minutes, then the alert closes), a:clicked() checks without waiting, a:close() takes it away. Buttons show on the growbgl.com page, also when you open it later while the script still waits; a push shows just the text. An alert that could not be shown (too many in a minute, or a test run) comes back closed, so a:wait() gives nil at once. ```lua local a = notify("Mod in " .. bot.world, "warn", { "Leave", "Stay" }) if a and a:wait(30) == "Leave" then bot:leave() end ``` ### ui.table `ui.table{ title, columns, buttons, key }` A result table people can search, sort, copy or download as CSV; buttons go on every row. Up to 12 columns, 10 tables per script and 1000 rows each, and a new table with the same key (the title unless set) replaces the old one. ```lua local t = ui.table{ title = "Cheap vends", columns = { "Item:item", "Price:price", "World:world", "Reachable:yesno" }, buttons = { "Buy" }, } ``` ### column types `"Label:type" / { key, label, type, yes, no }` A plain "Label" is a text column. Types: text, number, item (id, name or { id, count }), price (World Locks, negative = that many per WL), world, yesno (true / false; yes and no set the words). ```lua columns = { "Item:item", { key = "ok", label = "Open", type = "yesno", yes = "Open", no = "Shut" } } ``` ### add rows `t:add(row) / t:addRows(list)` Add a row by position or by column key; add returns the row number (nil, why when full or closed), addRows adds many at once. ```lua t:add{ "Dirt", -5, "BUYDIRT", true } t:add{ Item = 242, Price = 1, World = "MYSHOP", Reachable = false } ``` ### row colours (new) `t:add(row, tone) / t:set(row, values, tone) / t:tone(row, tone)` Colour a row: tone is "good", "bad", "warn" or "info", and nil takes the colour off. set keeps the colour unless you give a tone. ```lua local r = t:add({ "Dirt", -5, "BUYDIRT", true }, "good") t:tone(r, "bad") t:tone(r, nil) ``` ### change rows `t:set(row, values) / t:get(row) / t:find(key, value) / t:remove(row) / t:clear() / t:count()` set changes only the cells you give, get returns a row's values by key, find returns the first row whose column holds that value. ```lua local r = t:find("World", "BUYDIRT") if r then t:set(r, { Price = -8 }) end ``` ### row buttons `t:clicked() / t:waitClick([seconds])` The next row button someone pressed: row, button, values (nil when none); waitClick waits for one. Buttons work while the script runs. ```lua while true do local row, button, v = t:waitClick() if button == "Buy" then bot:goTo(v.World) end end ``` ### title / close `t:setTitle(text) / t:close()` Rename the table, or take it off the page now. A table you do not close stays after the run for people to read and export. ```lua t:setTitle("Cheap vends (done)") ``` ## Fleet: bots and proxies Reach your other bots, start scripts on them, and add or remove bots and proxies. Additions are sealed on THIS PC and saved on growbgl.com, like the website buttons. Ids are record ids (the .id field), never a list position. ### getBots `getBots()` Every bot on this PC, as a list of bot objects. ```lua for _, b in ipairs(getBots()) do b:say("gm") end ``` ### getBot `getBot(name | id) / findBot(name | id)` One bot by GrowID or by id (bot.id, not a list position); no argument gives this run's bot. A number always gives a bot object, even for an id that is not on this PC, so check b.name. findBot is the same. ```lua local farmer = getBot("MyFarmBot") if farmer then farmer:warp("FARM") end ``` ### getOnlineBots `getOnlineBots()` Like getBots(), only the bots that are online now. ```lua print(#getOnlineBots(), "of", #getBots(), "online") ``` ### runScript `bot:runScript(name[, source]) / bot:stopScript()` Start one of your saved scripts by name on a bot, or pass Lua source as the second argument. stopScript stops whatever that bot runs. ```lua for _, b in ipairs(getBots()) do b:runScript("autofarm") end ``` ### isRunningScript `bot:isRunningScript()` true while a script runs on that bot. Handy for a manager script that restarts its workers. ```lua for _, b in ipairs(getBots()) do if not b:isRunningScript() then b:runScript("worker") end end ``` ### getProxies `getProxies()` The game proxy pool this PC uses: each .id, .host, .port, .address (host:port), .resting (resting after a failure) and .users (bots on it now). The login is never shown. ```lua for _, p in ipairs(getProxies()) do print(p.address, p.resting and "(resting)" or (p.users .. " bots")) end ``` ### getLoginProxies `getLoginProxies()` The account's login proxies pool (used only to log in), same shape as getProxies(). Empty when none are set. ```lua print(#getLoginProxies(), "login proxies") ``` ### addBot `addBot(growId, password[, mac, rid]) / addBot(table)` Add a GrowID bot, or pass { growId, password, mac, rid, platform, proxyId }. It waits until the bot is on this PC (up to about 20 s) and returns it, or nil when it did not show up; up to 200 bots. ```lua local b = addBot("MyAlt01", "hunter2") if b then b:connect() end ``` ### addTokenBot `addTokenBot(token[, proxyId])` Add a token bot from an ltoken or a bundle (token|mac|rid|wk|platform, @name|token|mac|rid|hash|platform|wk or email|token|mac|rid|wk|platform; the platform may be a name or a number), same as addBot{ token = ... }. It returns true once sent; the bot shows up in getBots() a moment later. ```lua addTokenBot(myToken, 5) ``` ### removeBot `removeBot(id | name | bot)` Remove a bot by id, GrowID or bot object. No argument removes this run's own bot. ```lua for _, b in ipairs(getBots()) do if not b.online then removeBot(b) end end ``` ### addProxy `addProxy(line[, kind]) / addProxy(table)` Add "host:port" or "host:port:user:pass", or { host, port, user, pass, kind }. kind is "game" (default) or "login"; it shows up in getProxies() a moment later, and a line you already have is skipped. ```lua addProxy("1.2.3.4:8080") addProxy("1.2.3.4:8080:user:pass", "login") ``` ### removeProxy `removeProxy(id | proxy)` Remove a game or login proxy by id or proxy object. Bots pinned to it fall back to the shared pool. ```lua for _, p in ipairs(getProxies()) do if p.resting then removeProxy(p) end end ``` ### addLoginProxy / removeLoginProxy `addLoginProxy(line) / removeLoginProxy(id)` Shortcuts for the login pool: addProxy(line, "login") and removeProxy(id). ```lua addLoginProxy("1.2.3.4:8080:user:pass") ``` ## Fleet teamwork Many bots, one plan. These are shared by every script on this PC, so bots can split work, count together and stay out of each other's way. Values are plain Lua data: numbers, text, true / false and tables of them. ### shared values `shared.key / getShared(key[, default]) / setShared(key, value) / addShared(key[, n])` A value every script can read and write. addShared adds in one safe step, even when many bots count at once, and returns the new number. ```lua addShared("harvested", 1) print("fleet total:", shared.harvested) ``` ### queue `queue(name)` A to-do list every bot can push to and take from; each entry goes to exactly one bot. q:push(v), :pushFront(v), :pushAll(list), :take(), :takeWait(seconds), :peek(), :size(), :isEmpty(), :clear(). ```lua local jobs = queue("worlds") jobs:pushAll({ "FARM1", "FARM2", "FARM3" }) local w = jobs:takeWait(10) if w then bot:goTo(w) end ``` ### lock `lock(name[, seconds]) / unlock(name) / withLock(name, fn[, seconds])` Only one script at a time: lock waits (30 s by default) and returns true once this script holds it. withLock runs fn while holding it, always lets go, and returns true plus what fn returned, or false, why when the lock was not free in time. An error inside fn is raised again after the lock is let go. ```lua withLock("bank", function() bot:goTo("MYBANK") bot:dropAll("World Lock") end) ``` ### world claims `claimWorld([world][, job]) / releaseWorld([world][, job]) / worldClaimer(world[, job])` One bot per world per job (the current world when none is given). claimWorld returns true, or false and the bot that has it. ```lua for _, w in ipairs(worlds) do if claimWorld(w, "farm") then bot:goTo(w); break end end ``` ### parallel `parallel(list, fn[, most])` Run fn(item, i) for every item at the same time (at most `most` at once) and wait for all of them. Returns the results and the errors, by index. ```lua parallel(getBots(), function(b) b:warp("MYFARM") end, 5) ``` ## HTTP, webhooks and files Call a web API, post to Discord, run a tiny web server on the PC, and read or write files. Web calls go out direct from the PC, not through the game or a proxy. ### HttpClient `HttpClient.new()` Set .url, .method (or :setMethod(Method.post)), .headers, .content and .timeout (seconds, 30 by default, 120 at most), then :request(). While it waits, the script's other threads keep running. ```lua local c = HttpClient.new() c.url = "https://api.example.com/x" local r = c:request() print(r.status, r.body) ``` ### the result `r.status / r.body / r:getError() / HttpResult.new()` request() returns the status code and the body; when the call failed, r:getError() says why. HttpResult.new() makes an empty result. ```lua local r = c:request() if r.status ~= 200 then print("failed:", r.status, r:getError()) end ``` ### setProxy `c:setProxy(...) / c:removeProxy()` Do nothing in Puniko: web calls always go out direct. They exist so scripts that call them do not crash. ```lua c:setProxy("1.2.3.4:8080") -- ignored ``` ### Webhook `Webhook.new(url)` Post to a Discord webhook: set .content, .username and .avatar_url, or fill embed1 / embed2 (set .use = true), then :send(). :edit(messageId) changes a message it sent before, and :makeContent() returns the JSON it would post. :send() returns the HTTP result (.status 204 means posted). ```lua local hook = Webhook.new(WEBHOOK_URL) hook.username = "Farm log" hook.embed1.use = true hook.embed1.title = "Bot online" hook.embed1.description = bot.name hook:send() ``` ### Embed `Embed.new() / hook.embed1` An embed: .title, .description, .color, .url, .thumbnail and .image (picture links), .footer = { text, icon_url }, .author = { name, url, icon_url }, and :addField(name, value, inline). ```lua local e = hook.embed1 e.use = true e.footer = { text = bot.name } e:addField("World", bot.world, true) ``` ### HttpServer `HttpServer.new([port])` A tiny web server (port 8080 by default), open on this PC at once. Add routes with :get, :post, :put, :delete or :patch(path, fn); :listen("0.0.0.0", port) opens it to other PCs (Windows Firewall may ask once). ```lua local s = HttpServer.new(8080) s:get("/status", function(req, res) res:setContent(bot.name .. " @ " .. bot.world) end) ``` ### requests `req:getParam(name) / req:getHeader(name) / req:getBody() / res:setContent(body[, type]) / res:setStatus(code)` A route gets fn(req, res): req.method, req.path, a query or form value, a header and the raw body; set the reply and its status (200 by default). Each request runs on its own, so a slow route does not hold up the others. res:setHeader is accepted but not sent. ```lua s:post("/say", function(req, res) local body = json.decode(req:getBody()) if not body then res:setStatus(400) return end bot:say(body.text) res:setContent(json.encode({ ok = true }), "application/json") end) ``` ### setLogger / stop `s:setLogger(fn) / s:stop()` setLogger calls fn(req, res) after every request; stop (or close) shuts the server down. ```lua s:setLogger(function(req, res) print(req.method, req.path, res.status) end) ``` ### read / write / append `read(path) / write(path, data) / append(path, data)` Read a whole file as text (nil when it is missing), replace it, or add to its end. Use it to keep state between runs or log to disk. ```lua append("farm.log", bot.name .. " ran\n") local saved = read("state.txt") ``` ### json `json.encode(v) / json.decode(text)` A Lua table to JSON text and back; decode returns nil, why on bad text. ```lua write("state.json", json.encode({ gems = bot.gems })) local state = json.decode(read("state.json") or "") ``` ## Utilities The small helpers every script leans on. ### sleep / wait `sleep(ms) / wait(ms)` Pause the script for ms milliseconds without freezing the bot or other scripts. Put one in every loop. ```lua sleep(1000) -- one second ``` ### runThread `runThread(fn)` Run fn in the background next to your script, so a long job does not block the rest. Threads and on() handlers share the script's variables and take turns: each runs while the others sleep or wait, so sleep in every loop. ```lua runThread(function() while true do bot:collect(6); sleep(500) end end) ``` ### now `now()` The engine's clock in milliseconds, for measuring time. ```lua local t0 = now() -- ... print("took", now() - t0, "ms") ``` ### print / log `print(...) / log(...)` Write a line to the Output console; log is the same. ```lua print("gems:", bot.gems) ``` ### clearConsole / removeColor `clearConsole() / removeColor(s)` Clear this bot's game console (what getConsole reads, not the Output), and strip Growtopia colour codes from a string. ```lua local clean = removeColor(text) ``` ### waitUntil / retry `waitUntil(fn[, seconds, step]) / retry(times, fn[, delay])` waitUntil calls fn until it returns something (that comes back) or the time is up (10 s by default, then false). retry calls fn(try) until its first value is truthy, delay seconds apart. ```lua waitUntil(function() return bot.online end, 30) local ok = retry(3, function() return bot:warp("BUYWORLD") end, 5) ``` ### every / after `every(seconds, fn) / after(seconds, fn)` every runs fn again and again in the background until h:stop(); after runs it once, later (h:cancel() skips it). ```lua local h = every(60, function() print("gems:", bot.gems) end) after(600, function() h:stop() end) ``` ### random & numbers `randomSleep(min, max) / chance(p) / pick(t) / shuffle(t) / clamp(v, lo, hi) / round(v[, decimals])` randomSleep (or randomDelay) waits a random time in ms, which looks less like a bot than a fixed delay. chance(0.25) is true about a quarter of the time. ```lua randomSleep(800, 1500) if chance(0.1) then bot:say(pick({ "hi", "hey" })) end ``` ### text & time `formatNumber(n) / formatTime(s) / split(s, sep) / trim(s) / stopwatch()` formatNumber(1250000) is "1,250,000" and formatTime(3725) is "1h 2m". stopwatch() gives t:elapsed() in seconds and t:reset(). ```lua local t = stopwatch() -- ... print("took", formatTime(t:elapsed())) ``` ## Enums Named constants so your checks read clearly, e.g. bot.status == BotStatus.online. ### BotStatus `BotStatus.online / offline / account_banned / account_suspended / ...` Every status a bot can report, as the exact string, so compare bot.status == BotStatus.x. A ban is account_banned (timed) or account_suspended (permanent); banwave_detected (a hold on the whole fleet) and location_banned (a login refusal) are not account bans. All values: offline, online, wrong_password, account_banned, account_suspended, location_banned, version_update, advanced_account_protection, mail_verification, invalid_email, server_overload, too_many_login, maintenance, server_busy, guest_limit, guest_disabled, account_restricted, network_restricted, http_block, bad_name_length, invalid_account, invalid_token, error_connecting, logon_fail, captcha_requested, mod_entered, player_entered, high_load, high_ping, changing_subserver, could_not_warp, stopped, getting_server_data, bypassing_server_data, banwave_detected, reconnecting, server_issue, login_blocked, retrieving_token, no_proxy. ```lua if bot.status == BotStatus.account_banned then print("banned:", bot.name) end ``` ### Event `Event.world_enter / inventory / ... / text / call / any` The event kinds for on(), waitFor() and addEvent(). See Events and waiting. ```lua on(Event.gems, function(old, new) print(new - old) end) ``` ### Action `Action.move / collect / hit / place / harvest / plant / warp / drop / trash` The action kinds for bot:getInterval and bot:setInterval. ```lua bot:setInterval(Action.place, 0.25) ``` ### Method `Method.get / post / put / patch / delete / head` HTTP methods for HttpClient:setMethod. ```lua c:setMethod(Method.post) ``` ### VariantType `VariantType.float / int32 / uint32 / string / vector2 / vector3 / ...` The type of a value in a call event or a variant. ```lua if ev:get(1):getType() == VariantType.string then print(ev:get(1):getString()) end ``` ### more `CaptchaStatus / GeigerArea / Role / Bubble / Platform / StorageType / Proxy` Captcha states, Geiger zones, bot roles, chat bubbles, login platforms, storage kinds and proxy types. ```lua bot:setPlatform(Platform.android) ```