Lua API Reference
Reference of the functions available inside your scripts (cavebot Action waypoints, persistents, console, hotkeys). These are the 177 functions the sandbox allows you to call — anything else is blocked.
1.1 Character Information (20)
id()
id()
[number]
name()
name()
[string]
hp()
hp()
[number]
maxhp()
maxhp()
[number]
hppc()
hppc()
[number]
mp()
mp()
[number]
maxmp()
maxmp()
[number]
mppc()
mppc()
[number]
level()
level()
[number]
exp()
exp()
[number]
party()
party()
[number]
0: No party.
1: Party leader inviting your character.
2: Invited member on party.
3: Party member.
4: Party leader.
cap()
cap()
[number]
dir()
dir()
[number] — 0 N, 1 E, 2 S, 3 W
iswalking()
iswalking()
[boolean]
outfit()
outfit()
[number]
posx()
posx()
[number]
posy()
posy()
[number]
posz()
posz()
[number]
skull()
skull()
[number]
0: No skull.
1: Yellow skull.
2: Green skull.
3: White skull.
4: Red skull.
stamina()
stamina()
[number]
1.2 Skill Information (14)
mlevel()
mlevel()
[number]
mlevelpc()
mlevelpc()
[number]
fist()
fist()
[number]
fistpc()
fistpc()
[number]
club()
club()
[number]
clubpc()
clubpc()
[number]
sword()
sword()
[number]
swordpc()
swordpc()
[number]
axe()
axe()
[number]
axepc()
axepc()
[number]
distance()
distance()
[number]
distancepc()
distancepc()
[number]
shielding()
shielding()
[number]
shieldingpc()
shieldingpc()
[number]
1.3 Conditions Information (12)
conditions()
conditions()
[number]
invisible()
invisible()
[boolean]
battlesigned()
battlesigned()
[boolean]
drunk()
drunk()
[boolean]
hasted()
hasted()
[boolean]
manashielded()
manashielded()
[boolean]
burning()
burning()
[boolean]
energized()
energized()
[boolean]
paralyzed()
paralyzed()
[boolean]
poisoned()
poisoned()
[boolean]
hungry()
hungry()
[boolean]
pzone()
pzone()
pzone = protection zone (PlayerStates.Pz; alias Pigeon no client).
NOTE: some custom servers do not send this bit in getStates() — in that case, `pzone()` will always return false and detection needs to be done by another means (e.g., tile flag, minimap color). We maintain the pattern of the remaining conditions; the user can involve their own check if needed.
1.3 System class (6)
botpaused()
botpaused()
[boolean]
looter()
looter()
[boolean]
cavebot()
cavebot()
[boolean]
islooting()
islooting()
[boolean]
targeting()
targeting()
[boolean]
standtime()
standtime()
[boolean]
1.3.2 Cavebot Waypoints (3)
getwaypoint(wptIndex)
getwaypoint(wptIndex)
getwaypoint(wptIndex) [table]
getwaypoints()
getwaypoints()
getwaypoints() [table]
wpt()
wpt()
wpt() [table]
1.4 Equipment Information (11)
getEquipment(equipName)
getEquipment(equipName)
[table]
armor()
armor()
No description.
back()
back()
No description.
belt()
belt()
No description.
feet()
feet()
No description.
finger()
finger()
No description.
head()
head()
No description.
legs()
legs()
No description.
lhand()
lhand()
No description.
neck()
neck()
No description.
rhand()
rhand()
No description.
2.7 Map Class — tiles / items / effects (14)
finditemonground(itemOrId)
finditemonground(itemOrId)
finditemonground(item|id) [table] — {count,posx,posy,posz} da primeira ocorrência
gettile(x, y, z)
gettile(x, y, z)
gettile(x, y, z) [table] — items (tabela), topitem, itemcount, posx/posy/posz
gettileeffects(x, y, z)
gettileeffects(x, y, z)
gettileeffects(x, y, z) [table] — lista de ids de effects vivos no tile.
gettiles()
gettiles()
gettiles() [table] — 15×11 em redor do player (raio 7 sqm), piso actual
gettileseffects()
gettileseffects()
gettileseffects() [table] — tiles na área visível (15×15 centrada no player)
com ≥ 1 effect “vivo”. A varredura é síncrona; chama uma vez por tick do
motor para captar runes / explosões logo quando acontecem.
iscreatureontile(x, y, z)
iscreatureontile(x, y, z)
iscreatureontile(x, y, z) [boolean]
isposonscreen(x, y, z, fromX, fromY, fromZ)
isposonscreen(x, y, z, fromX, fromY, fromZ)
isposonscreen(x, y, z, fromX?, fromY?, fromZ?) [boolean] — Chebyshev ≤ 7 e z igual.
Sem from = origem = player position.
tileiswalkable(x, y, z)
tileiswalkable(x, y, z)
tileiswalkable(x, y, z) [boolean] — idem iswalkable, mantido por contrato
tilereachable(x, y, z)
tilereachable(x, y, z)
tilereachable(x, y, z) [boolean] — reutiliza tryCreatureReachable
tileshootable(x, y, z)
tileshootable(x, y, z)
tileshootable(x, y, z) [boolean]
topitem(x, y, z, considerCreatures)
topitem(x, y, z, considerCreatures)
topitem(x, y, z, considerCreatures?) [table]
toplookitem(x, y, z, considerCreatures)
toplookitem(x, y, z, considerCreatures)
toplookitem(x, y, z, considerCreatures?) [table]
topmoveitem(x, y, z)
topmoveitem(x, y, z)
topmoveitem(x, y, z) [table]
topuseitem(x, y, z, considerCreatures)
topuseitem(x, y, z, considerCreatures)
topuseitem(x, y, z, considerCreatures?) [table]
Actions (reach, UI, fala, virar, abrir/usar itens — itens sempre por **ID**) (15)
closewindow(windowname)
closewindow(windowname)
closewindow(windowname) [void] — contentor cujo título / nome case
closewindows()
closewindows()
closewindows() [void] — fechar todos os contentores
openitem(item, location, newWindow, index)
openitem(item, location, newWindow, index)
openitem(itemid, location, newWindow, index) [void]
openitemslot(slotIndex, location, newWindow)
openitemslot(slotIndex, location, newWindow)
openitemslot(slotIndex, location, newWindow) [void] — slot 0-based no contentor; location = nome ou "container"
reachlocation(x, y, z, stepIn, mapClicks)
reachlocation(x, y, z, stepIn, mapClicks)
reachlocation(x,y,z, stepIn?, mapClicks?) [boolean] — inicia autoWalk; não garante chegada.
stepIn / mapClicks: reservado (sem API comum; ignorados).
resizebattle(size)
resizebattle(size)
resizebattle(size) [void]
resizewindow(itemOrWidget, linhas)
resizewindow(itemOrWidget, linhas)
No description.
resizewindows()
resizewindows()
resizewindows() [void] — 1 linha (59px: 25 + 1*34) em cada `container.window` aberto
rturn(times, backOriginal)
rturn(times, backOriginal)
rturn(times, backOriginal?) [void]
say(text, channel)
say(text, channel)
say(text, channel?) [void] — sem canal: talk local; com canal: tenta talkChannel (id)
turn(direction)
turn(direction)
turn(direction) [void] — só n/e/s/w
useitem(item, location)
useitem(item, location)
useitem(itemid, location) [void]
useitemon(item, x, y, z)
useitemon(item, x, y, z)
useitemon(itemid, x, y, z) [void] — item vindo de inventário / mochilas (mesma busca que eatfood)
useitemoncreature(item, creature)
useitemoncreature(item, creature)
useitemoncreature(item, creature) [void] — criatura por nome; item por id
useitemonitem(item, itemOn, itemOnLocation, itemLocation)
useitemonitem(item, itemOn, itemOnLocation, itemLocation)
useitemonitem(item, itemOn, itemOnLocation, itemLocation) [void] — todos ids
Activam/desactivam cada motor em runtime e sincronizam visualmente o (5)
setcavebot(b)
setcavebot(b)
No description.
sethealing(b)
sethealing(b)
No description.
sethotkeys(b)
sethotkeys(b)
Hotkeys: tem `enableAll` / `disableAll` em vez de `start`/`stop`. Faz
a tradução aqui para reusar `_ibSyncEnabledCheckbox` e o pattern uniform.
setlooting(b)
setlooting(b)
No description.
settargeting(b)
settargeting(b)
No description.
Bitmask de PlayerStates conforme `modules/gamelib/player.lua` em ambos (14)
bleeding()
bleeding()
No description.
cursed()
cursed()
No description.
dazzled()
dazzled()
No description.
drowning()
drowning()
No description.
feared()
feared()
No description.
freezing()
freezing()
No description.
hascondition(stateName)
hascondition(stateName)
Genérica: aceita o nome do estado (case-sensitive PascalCase, ex.: "Burn",
"Pz", "Hungry"). Útil quando se quer iterar sobre vários states em
código user/script sem multiplicar funções dedicadas.
hascondition('Burn') == burning()
hascondition('Pz') == pzone()
inprotectionzone()
inprotectionzone()
No description.
inpz()
inpz()
Aliases comuns (vBot-style).
partybuff()
partybuff()
No description.
protectionzone()
protectionzone()
No description.
pzblock()
pzblock()
pzblock = red swords / no-logout-no-pz (PvP after-hit timer).
rooted()
rooted()
Tibia 12+ (OTClient-main); OTCv8 não expõe estes mas se existirem
vão funcionar via `_G.PlayerStates`.
strengthened()
strengthened()
No description.
Combat — setattackmode / setpvpmode (OTCv8: setFightMode/setChaseMode/setPVPMode) (2)
setattackmode(mode)
setattackmode(mode)
No description.
setpvpmode(pvpMode)
setpvpmode(pvpMode)
No description.
Containers — minimize / restore / higher / stack / emptyslots (5)
emptyslots(windowName)
emptyslots(windowName)
emptyslots(windowName?) [number] — capacity − items.size. Sem nome = soma de todos.
higherwindows(windowName)
higherwindows(windowName)
higherwindows(containerName) [void] — sobe para o contentor pai via g_game.upContainer
minimizewindows(windowName)
minimizewindows(windowName)
minimizewindows("equip" | containerName) [void]
restorewindows(windowName)
restorewindows(windowName)
restorewindows("equip" | containerName) [void]
stackitems(location, onlyOnce, itemName)
stackitems(location, onlyOnce, itemName)
stackitems(location?, onlyOnce?, itemName?) — junta stacks parciais no mesmo contentor.
location: nome do contentor (ou "container" = primeiro aberto); nil = todos os abertos.
onlyOnce: se true, só faz um único merge e sai (útil em macros rápidos).
itemName/itemId: restringe a um id (nome só funciona se o contract resolver; aqui = id).
Creature extras — ignorecreature / getcreature / getcreatures (3)
getcreature(ref)
getcreature(ref)
getcreature(name|id) [table] — creatureToInfo resolvido por id (fast-path) ou nome (spectators).
getcreatures(filterStr)
getcreatures(filterStr)
getcreatures(filter) [table<creatureInfo>] — filtro livre:
'p' = player (isPlayer e não LocalPlayer)
'm' = monster (isMonster)
'f' = mesmo floor do player (z igual)
's' = mesmo floor + onscreen (Chebyshev ≤ 7)
Sem letras = todos (exclui LocalPlayer).
ignorecreature(creatureId, ignoreFlag)
ignorecreature(creatureId, ignoreFlag)
ignorecreature(id, ignore) [void] — true marca, false/nil remove.
Debug toggle: `_G.IB_CONNECTCHAR_DEBUG = true` activa logs detalhados. (1)
connectchar(account, password, characterName, callback)
connectchar(account, password, characterName, callback)
No description.
Food — `eatfood` / `foodItemIds` (1)
eatfood()
eatfood()
eatfood() [boolean] — usa o primeiro id disponível de `foodItemIds` (sem exigir fome).
Só `g_game.use(item)` — sem `useWith` / `useInventoryItem*`.
Devolve true se uma tentativa de uso correu (sem erro Lua); false se sem lista,
sem `g_game`/`lp`, sem item, ou tudo falhou.
Items — moveitems, ground, inventory, container (12)
attacked()
attacked()
attacked() [table] — criatura em ataque (quadrado vermelho); getAttacked() — mesmo contrato
container(containerName)
container(containerName)
No description.
following()
following()
following() [table] — follow (verde); getFollowing() — mesmo contrato
getAttacked()
getAttacked()
No description.
getFollowing()
getFollowing()
No description.
getSelf()
getSelf()
No description.
getTarget()
getTarget()
No description.
ground(x, y, z)
ground(x, y, z)
No description.
inventory(slot)
inventory(slot)
No description.
moveitems(itemId, toRef, fromRef, count)
moveitems(itemId, toRef, fromRef, count)
moveitems(int itemid, to, from, int count?) [void] — to = destino, from = origem
self()
self()
self() [table] — jogador local; getSelf() — mesmo contrato
target()
target()
target() [table] — alvo do motor de Targeting; getTarget() — mesmo contrato
Justificação: dependendo da versão do OTClient/protocolo, mensagens (9)
getlastmessage()
getlastmessage()
getlastmessage() [table]
getlastprivatemessage(visibleOnly)
getlastprivatemessage(visibleOnly)
getlastprivatemessage(visibleOnly?) [table]
getlastscreenmessage()
getlastscreenmessage()
getlastscreenmessage() [string] — debug helper. Devolve a última
mensagem capturada (ou via onTextMessage ou via hook directo nos
widgets de status — ver IB_HookStatusLabels) com prefixo de origem
e mode, para diagnosticar quando getstatusmessage devolve "":
ex: print(getlastscreenmessage())
-> "[label=bottomStatusLabel] Sorry, not possible."
-> "[mode=21] Sorry, not possible."
getmessages()
getmessages()
getmessages() [table]
getnewmessages()
getnewmessages()
getnewmessages() [table] — marca como lidas ao devolver.
getstatusmessage(visibleOnly)
getstatusmessage(visibleOnly)
getstatusmessage(visibleOnly?) [string] — última status message do
jogo (texto branco que aparece sob o mapa: "Sorry, not possible",
"You are exhausted", "You cannot use this object", "There is not
enough room", etc.). Filtra pelos modes de status/warning do
protocolo 8.6 (17 StatusDefault, 18 EventAdvance, 19, 20
StatusWarning, 21, 22 StatusSmall — este último é o típico "not
possible"). Devolve "" se nada na janela de visibilidade (5s).
Por defeito só devolve mensagens "ainda visíveis" no jogo (mesma
janela do screenmessage). Passa `false` para varrer o histórico
completo (últimas 32 screen messages).
itemcount(itemId, location)
itemcount(itemId, location)
itemcount(itemId, location?) [number] — soma a contagem visível de um item.
Sem `location`: soma todos os contentores abertos + slots de inventário
do player. Tiles do chão NÃO são incluídos por defeito (a UI só vê os
tiles à volta do player; "inventário visível" = bag + body slots).
Com `location`:
container('backpack') → só dentro desse contentor (case-insensitive).
container(...) → tabela do helper aceite.
inventory(slot) → só nesse slot do body (1..10). Útil para
confirmar se equipou determinado anel/runa.
ground() ou ground(x,y,z) → tile do player (sem args) ou tile dado.
"container" / "inventory" / "ground" (string) → equivalente.
"<nome do container>" → contentor por nome.
Stackables: usa `getCount()`. Items não-stackable contam como 1 cada.
itemcountmsg(itemName, message)
itemcountmsg(itemName, message)
itemcountmsg(item, message) [number] — extrai nº dentro da frase.
"Using one of 2 vials..." → 2; "Using the last vial..." → 1.
screenmessage(visibleOnly, typeStr)
screenmessage(visibleOnly, typeStr)
screenmessage(visibleOnly?, type?) [string] — última "green message" do écran.
type: 'any' / 'loot' / 'look' / 'exp' (filtro por palavras-chave no conteúdo).
Movement — `followcreature`, `move` (2)
followcreature(creatureName)
followcreature(creatureName)
followcreature(string) [void] — segue a primeira visível: por id (string numérica) ou por nome
move(direction)
move(direction)
move(string) [void] — "n", "s", "e", "w", "nw", "ne", "sw", "se" (ver `Directions` / fallback)
Reach — reachgrounditem (varre ecrã por tile com item), reachcreature (nome/id) (2)
reachcreature(creatureRef)
reachcreature(creatureRef)
reachcreature(name|id) [void]
reachgrounditem(itemOrId, stepIn)
reachgrounditem(itemOrId, stepIn)
reachgrounditem(item, stepIn?) [void] — stepIn=true: ficar **em cima**; false/nil: adjacente
Referências OTCv8: (2)
getviplist()
getviplist()
getviplist() [table] — array { { name, isonline }, ... } na ordem de
iteração do map interno de VIPs. `isonline` só é verdadeiro para
`VipState.Online`; Pending é tratado como offline (corresponde ao semáforo
"verde" visível da VIP List).
isviponline(vipName)
isviponline(vipName)
isviponline(vipName) [boolean] — true sse existe um VIP com esse nome e o
estado é Online. Pending (2) e Offline (0) → false. Case-insensitive, como
no `game_viplist.lua` do OTCv8.
Teste (1)
setfishing(modeArg, condMin, condMax, enabled)
setfishing(modeArg, condMin, condMax, enabled)
ligar/desligar o Auto Fishing programaticamente (Action de cavebot,
hotkey, persistent). Substitui o equivalente a abrir o painel Tools,
escolher modo, definir condMin/Max e marcar Enabled.
Args:
type : "Capacity" | "Count"
- Capacity: comeca a pescar quando cap() >= condmax,
para quando cap() <= condmin (encher mochila).
- Count : comeca quando #peixes <= condmin,
para quando #peixes >= condmax (sessoes).
nil/string invalida -> mantem o modo actual.
condmin : number, threshold inferior da histerese.
nil -> mantem actual.
condmax : number, threshold superior da histerese.
nil -> mantem actual.
bool : true / false, liga ou desliga o motor.
nil -> mantem actual.
Exemplos:
setfishing("Count", 0, 50, true) -- pescar 50 peixes e parar
setfishing("Capacity", 100, 200, true) -- encher bag com cap target
setfishing(nil, nil, nil, false) -- desligar (mantem config)
Sincroniza tambem os widgets do painel Tools se a janela ja' foi
criada nesta sessao -- o user ve a mudanca reflectida na UI sem
precisar de fechar e reabrir.
Tile helpers — isitemontile, iswalkable (iguais ao contract: ids sempre) (2)
isitemontile(itemOrId, posx, posy, posz)
isitemontile(itemOrId, posx, posy, posz)
isitemontile(itemid, x, y, z) [boolean]
iswalkable(posx, posy, posz)
iswalkable(posx, posy, posz)
iswalkable(x, y, z) [boolean]
Time / Experience (8)
date()
date()
No description.
expgained()
expgained()
No description.
exphour()
exphour()
No description.
formattedtime()
formattedtime()
No description.
runningtime()
runningtime()
No description.
startedtime()
startedtime()
No description.
timenow()
timenow()
No description.
timetosec(timeConvert)
timetosec(timeConvert)
timetosec("HH:MM" | "HH:MM:SS") → segundos desde 00:00.
Retorno por contrato = string (mantido) mas contém valor numérico.
Wrappers minimalistas sobre `g_game.forceLogout` / `g_game.safeLogout` (2)
forcelogout()
forcelogout()
— expoem-se como funcoes globais simples para uso em hotkeys, scripts
de Action no cavebot (`forcelogout()` / `safelogout()`) e persistents.
Diferenca:
`forcelogout()` — fecha a ligacao TCP independentemente de pzlocked /
in-fight / battle. O server marca o personagem como "logged out"
mesmo dentro de combate, *mas* o char permanece online no mundo
durante 60-90s a sofrer hits ate que o slot expira (regra de
servers OT classicos para evitar combat-log abuse). Util quando o
player vai morrer e ja' nao ha como salvar.
`safelogout()` — pede logout normal pelo protocolo (packet 0x14 em
OT). O server *recusa* o logout se ha pzblock ou estiveres em
in-fight com criaturas vivas. Em PZ ou fora de combate fecha
limpamente. Recomendado para hotkeys de "AFK exit" e end-of-hunt
scripts onde o char ja' voltou ao depot.
Defensivo: se `g_game` ou os metodos nao existem (forks antigos),
as funcoes sao no-op silencioso em vez de levantar erro.
safelogout()
safelogout()
No description.
moveitemspos / useitemonpos — pixel x/y do gameMapPanel (2)
moveitemspos(px, py, item, location, count)
moveitemspos(px, py, item, location, count)
(conversão via `modules.game_interface.gameMapPanel:getTile({x=px,y=py})`;
igual ao que o OTCv8 faz em `getTileUnderCursor`).
moveitemspos(px, py, itemid, location?, count?) [void]
useitemonpos(px, py, item, location)
useitemonpos(px, py, item, location)
useitemonpos(px, py, itemid, location?) [void]
reconnect(callback?) — reconecta com tier de fallbacks. Robust em (1)
reconnect(callback)
reconnect(callback)
forks que tem bugs no CharacterList module.
Tiers (cada um faz pcall + valida widgets/refs antes de tocar):
T1: g_game.loginWorld(...) DIRECTO — bypassa todo o UI / module
client_entergame. Usa world info cacheada do último connectchar.
Esta e a via mais fiavel: nao depende de charactersWindow estar
visivel, nao chama CharacterList.create (que tem upvalue bugs em
alguns forks). Requer: connectchar() previo nesta sessao.
T2: CharacterList.doLogin() com char focado — comportamento OTCv8
padrao. Funciona quando a charlist ja esta visivel e com char
focado (last-used-character). Nao precisa de creds em cache.
T3: connectchar(...) flow completo — re-digita credenciais + escolhe
char por nome. Usado quando nada mais funciona; precisa creds
em cache.
Cada tier valida pre-conditions; se falhar, tenta o seguinte. Erro
final agrega causas para debug.
shootarearune / shootexplosion — área (OTCv8-style) (2)
shootarearune(rune, minMonsters, ...)
shootarearune(rune, minMonsters, ...)
No description.
shootexplosion(minMonsters, ...)
shootexplosion(minMonsters, ...)
No description.