-- VoteScript for Tibia OT: The Forgotten Server 1.4+ and OpenTibiaBR Canary. -- Put this file in data/scripts/ and run votescript-delivery.php (mode = game) next -- to the server (Lua here has no web requests; it talks to VoteScript). -- -- !vote claims by character name -- !vote CODE redeems a code from the vote page -- -- Rewards in VoteScript are an item id such as 2160, or a type such as -- vip/premium, storage/30001, teleport/temple. What each type does is below. -- The dashboard only sends names and numbers: anything not allowed here stays -- waiting in VoteScript, and nothing from there is ever run as code. local SECONDS_BETWEEN = 10 ------------------------------------------------------------ your settings -- Most that one claim can give, whatever the dashboard says. local MAX_DAYS, MAX_MINUTES, MAX_XP = 365, 720, 100000000 -- vip/NAME: names that add premium days. local VIP = { vip = true, premium = true } -- storage/ID, storage/ID/VALUE and until/ID: only storages in these ranges. local STORAGES = { { 30000, 39999 } } -- unlock/NAME: a storage that holds the time when access ends. -- local UNLOCK = { vote_dungeon = 30100 } local UNLOCK = {} -- teleport/NAME: your places. Add e.g. temple = { 1000, 1000, 7 } local PLACES = {} -- teleport/X,Y,Z: any place. Leave false unless you want that. local ANY_COORDINATES = false -- outfit/ID, mount/ID, badge/ID and title/ID/forever: allowed IDs. local OUTFITS, MOUNTS, BADGES, TITLES = { 128, 1999 }, { 1, 255 }, { 1, 255 }, { 1, 255 } -- spell/NAME: spells players may learn, with _ for spaces, e.g. light_healing = "Light Healing" local SPELLS = {} -- run/NAME: your own actions. The second value is the amount from the dashboard. -- daily_box = function(player, amount) player:addItem(2160, 5) return true end local RUN = {} -- custom/ANYTHING: { can = function(player, text, amount) end, give = function(player, text, amount) end } local CUSTOM = {} -- Your own words without a "/", such as "coins". Return true when handled. local function giveSpecial(player, key, amount) if key == "coins" and player.addTransferableCoins then player:addTransferableCoins(amount) return true end if key == "premium" and player.addPremiumDays then player:addPremiumDays(math.min(amount, MAX_DAYS)) return true end return false end ------------------------------------------------------------ what this server can do -- Canary calls it Result, TFS result. local R = Result or result local last, told, warned = {}, false, {} local function has(name) return type(Player) == "table" and Player[name] ~= nil end local function whole(text, from, to) local n = type(text) == "string" and text:match("^%-?%d+$") and tonumber(text) return n and n >= from and n <= to and n or nil end local function allowed(id) local n = whole(id, 1, 2147483647) for _, r in ipairs(STORAGES) do if n and n >= r[1] and n <= r[2] then return n end end end local function extend(player, storage, days) local now = os.time() local untilTime = math.max(now, player:getStorageValue(storage)) + math.min(days, MAX_DAYS) * 86400 player:setStorageValue(storage, math.min(untilTime, 2147483647)) return true end local function names(t, prefix) local out = {} for name in pairs(t) do if type(name) == "string" and name:match("^[%w][%w_-]*$") then out[#out + 1] = prefix .. name end end table.sort(out) return out end local function range(r, text) local n = whole(text, r[1], r[2]) return n end local SKILLS = {} for name, constant in pairs({ fist = "SKILL_FIST", club = "SKILL_CLUB", sword = "SKILL_SWORD", axe = "SKILL_AXE", distance = "SKILL_DISTANCE", shield = "SKILL_SHIELD", shielding = "SKILL_SHIELD", fishing = "SKILL_FISHING" }) do if _G[constant] then SKILLS[name] = _G[constant] end end local function place(a) local x, y, z = a[1]:match("^(%d+),(%d+),(%d+)$") local p = not x and PLACES[a[1]] or ANY_COORDINATES and x and { tonumber(x), tonumber(y), tonumber(z) } if p and p[1] <= 65535 and p[2] <= 65535 and p[3] <= 15 then return Position(p[1], p[2], p[3]) end end local function fighting(player) return player:isPzLocked() or CONDITION_INFIGHT and player:getCondition(CONDITION_INFIGHT, CONDITIONID_DEFAULT) and true or false end -- Per type: list = what to tell VoteScript, or nil when this server has no -- function for it. allow = is this value allowed. can = possible right now -- (false and a text when not). give = do it. local TYPES = { item = { list = function() return { "item" } end, give = function(player, a, n) if giveSpecial(player, a[1], n) then return true end local id = whole(a[1], 1, 4294967295) if not id then return false end -- Two arguments only: more would create single items instead of stacks. player:addItem(id, n) return true end, }, vip = { list = function() return (has("addPremiumDays") or has("setPremiumEndsAt")) and names(VIP, "vip/") or nil end, allow = function(a) return VIP[a[1]] and not a[2] end, give = function(player, a, n) local days = math.min(n, MAX_DAYS) if player.addPremiumDays then player:addPremiumDays(days) else player:setPremiumEndsAt(math.max(os.time(), player:getPremiumEndsAt()) + days * 86400) end return true end, }, storage = { list = function() local out = {} for _, r in ipairs(STORAGES) do out[#out + 1] = ("storage/%d-%d"):format(r[1], r[2]) end return has("setStorageValue") and out or nil end, allow = function(a) return allowed(a[1]) and (not a[2] or whole(a[2], -2147483647, 2147483647)) and not a[3] end, give = function(player, a, n) local id = allowed(a[1]) local value = a[2] and tonumber(a[2]) or math.max(0, player:getStorageValue(id)) + n player:setStorageValue(id, math.min(value, 2147483647)) return true end, }, ["until"] = { list = function() local out = {} for _, r in ipairs(STORAGES) do out[#out + 1] = ("until/%d-%d"):format(r[1], r[2]) end return has("setStorageValue") and out or nil end, allow = function(a) return allowed(a[1]) and not a[2] end, give = function(player, a, n) return extend(player, allowed(a[1]), n) end, }, unlock = { list = function() return has("setStorageValue") and names(UNLOCK, "unlock/") or nil end, allow = function(a) return UNLOCK[a[1]] and (not a[2] or a[2] == "forever") end, give = function(player, a, n) if a[2] then player:setStorageValue(UNLOCK[a[1]], 2147483647) return true end return extend(player, UNLOCK[a[1]], n) end, }, teleport = { list = function() return has("teleportTo") and (ANY_COORDINATES and { "teleport" } or names(PLACES, "teleport/")) or nil end, allow = function(a) return place(a) and not a[2] end, can = function(player, a) if fighting(player) then return false, "Your vote reward teleports you. It waits until you are out of the fight." end local tile = Tile(place(a)) return tile and tile:getGround() and true or false, "Your vote reward teleports you, but the place cannot be reached now." end, give = function(player, a) return player:teleportTo(place(a)) end, }, xp = { list = function() local out = has("addSkillTries") and names(SKILLS, "xp/") or {} if has("addExperience") then out[#out + 1] = "xp/experience" end if has("addManaSpent") then out[#out + 1] = "xp/magic" end return out end, allow = function(a) return (a[1] == "experience" or a[1] == "magic" or SKILLS[a[1]]) and not a[2] end, give = function(player, a, n) n = math.min(n, MAX_XP) if a[1] == "experience" then player:addExperience(n, true) elseif a[1] == "magic" then player:addManaSpent(n) else player:addSkillTries(SKILLS[a[1]], n) end return true end, }, boost = { -- Canary list = function() return has("setXpBoostTime") and has("setXpBoostPercent") and { "boost/experience" } or nil end, allow = function(a) return a[1] == "experience" and whole(a[2], 1, 1000) and not a[3] end, give = function(player, a, n) player:setXpBoostPercent(math.max(tonumber(a[2]), player:getXpBoostTime() > 0 and player:getXpBoostPercent() or 0)) player:setXpBoostTime(math.min(player:getXpBoostTime() + math.min(n, MAX_MINUTES) * 60, 65000)) return true end, }, outfit = { list = function() return has("addOutfitAddon") and { ("outfit/%d-%d"):format(OUTFITS[1], OUTFITS[2]) } or nil end, allow = function(a) local id, addon = a[1]:match("^(%d+),?([0-3]?)$") return id and range(OUTFITS, id) and not a[2] end, give = function(player, a) local id, addon = a[1]:match("^(%d+),?([0-3]?)$") if player.addOutfit then player:addOutfit(tonumber(id)) end if addon ~= "" and addon ~= "0" then player:addOutfitAddon(tonumber(id), tonumber(addon)) end return true end, }, mount = { list = function() return has("addMount") and { ("mount/%d-%d"):format(MOUNTS[1], MOUNTS[2]) } or nil end, allow = function(a) return range(MOUNTS, a[1]) and not a[2] end, give = function(player, a) player:addMount(tonumber(a[1])) -- false when they have it already return true end, }, spell = { list = function() return has("learnSpell") and names(SPELLS, "spell/") or nil end, allow = function(a) return SPELLS[a[1]] and not a[2] end, give = function(player, a) player:learnSpell(SPELLS[a[1]]) return true end, }, badge = { -- Canary list = function() return has("addBadge") and { ("badge/%d-%d"):format(BADGES[1], BADGES[2]) } or nil end, allow = function(a) return range(BADGES, a[1]) and not a[2] end, give = function(player, a) player:addBadge(tonumber(a[1])) return true end, }, title = { -- Canary; it has no titles for some days list = function() return has("addTitle") and { ("title/%d-%d/forever"):format(TITLES[1], TITLES[2]) } or nil end, allow = function(a) return range(TITLES, a[1]) and a[2] == "forever" and not a[3] end, give = function(player, a) player:addTitle(tonumber(a[1])) return true end, }, run = { list = function() return names(RUN, "run/") end, allow = function(a) return RUN[a[1]] and not a[2] end, give = function(player, a, n) return RUN[a[1]](player, n) ~= false end, }, custom = { list = function() return CUSTOM.give and { "custom" } or has("addBlessing") and { "custom/blessings" } or nil end, allow = function(a) return CUSTOM.give or a[1] == "blessings" end, can = function(player, a, n) if CUSTOM.can then return CUSTOM.can(player, a[1], n) end return true end, give = function(player, a, n) if a[1] == "blessings" and has("addBlessing") then for i = 1, Result and 8 or 5 do if not player:hasBlessing(i) then player:addBlessing(i, 1) end end return true end return CUSTOM.give(player, a[1], n) ~= false end, }, } -- "vip/gold" -> vip, { "gold" }; a key without a known type is an item. local function parse(key) local t, rest = key:match("^(%l+)/(.+)$") if not t or t == "item" or not TYPES[t] then return "item", { key } end if t == "custom" then return t, { rest } end local a = {} for part in rest:gmatch("[^/]+") do a[#a + 1] = part end return t, a end local function say(text) if not warned[text] then warned[text] = true print("[VoteScript] " .. text) end end local function tell(player, text) player:sendTextMessage(MESSAGE_EVENT_ADVANCE, text) end -- Tells the delivery program what this server can do. local function publish() local out = {} for _, t in pairs(TYPES) do for _, entry in ipairs(t.list() or {}) do out[#out + 1] = entry end end table.sort(out) local ok = db.query("CREATE TABLE IF NOT EXISTS `votescript_types` (`id` TINYINT NOT NULL PRIMARY KEY, `types` TEXT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4") return ok and db.query("REPLACE INTO `votescript_types` (`id`, `types`) VALUES (1, " .. db.escapeString(table.concat(out, ",")) .. ")") end ------------------------------------------------------------ command local talk = TalkAction("!vote") function talk.onSay(player, words, param, type) local now = os.time() local guid = player:getGuid() if last[guid] and now - last[guid] < SECONDS_BETWEEN then tell(player, "Please wait a moment before checking again.") return false end last[guid] = now local code = (param or ""):gsub("[^%w]", ""):sub(1, 20) db.asyncQuery("INSERT INTO `votescript_requests` (`player`, `code`) VALUES (" .. db.escapeString(player:getName()) .. ", " .. db.escapeString(code) .. ")") tell(player, "Checking your votes...") return false end talk:separator(" ") if talk.groupType then talk:groupType("normal") -- required by Canary, unknown to TFS end talk:register() ------------------------------------------------------------ delivery local function query(sql, columns) local id = db.storeQuery(sql) local rows = {} if id then repeat local row = {} for name, kind in pairs(columns) do row[name] = kind == "n" and R.getNumber(id, name) or R.getString(id, name) end rows[#rows + 1] = row until not R.next(id) R.free(id) end return rows end -- One claim: everything or nothing. Checks first, marks second, gives last, -- so nothing can be handed out twice. Teleports come after everything else. local function deliverClaim(player, name, request) local rows = query("SELECT `id`, `item_key`, `amount` FROM `votescript_items` WHERE `request_id` = " .. request .. " AND `player` = " .. name .. " AND `given` = 0 ORDER BY `id`", { id = "n", item_key = "s", amount = "n" }) for _, row in ipairs(rows) do row.type, row.args = parse(row.item_key) local t = TYPES[row.type] row.ok = row.amount > 0 and (not t.allow or t.allow(row.args)) and true or false if row.ok and t.can then local can, why = t.can(player, row.args, row.amount) if not can then return false, why or "Your vote reward waits. Try again later." end end end if #rows == 0 or not db.query("UPDATE `votescript_items` SET `given` = 1 WHERE `request_id` = " .. request .. " AND `player` = " .. name .. " AND `given` = 0") then return true end for _, teleports in ipairs({ false, true }) do for _, row in ipairs(rows) do if (row.type == "teleport") == teleports then local fine, done = false, "not allowed by the settings of this script" if row.ok then fine, done = pcall(TYPES[row.type].give, player, row.args, row.amount) end if not fine or not done then print("[VoteScript] " .. player:getName() .. " did not get " .. row.item_key .. " x" .. row.amount .. (fine and "" or ": " .. tostring(done))) end end end end return true end local function deliver(player) local name = db.escapeString(player:getName()) for _, r in ipairs(query("SELECT DISTINCT `request_id` FROM `votescript_items` WHERE `player` = " .. name .. " AND `given` = 0 ORDER BY `request_id` LIMIT 5", { request_id = "n" })) do local ok, why = deliverClaim(player, name, r.request_id) if not ok and (last[name .. why] or 0) < os.time() - 60 then last[name .. why] = os.time() tell(player, why) end end for _, row in ipairs(query("SELECT `id`, `message` FROM `votescript_requests` WHERE `player` = " .. name .. " AND `state` = 1 AND `told` = 0 LIMIT 5", { id = "n", message = "s" })) do db.query("UPDATE `votescript_requests` SET `told` = 1 WHERE `id` = " .. row.id) tell(player, row.message) end end local event = GlobalEvent("VoteScript") function event.onThink(interval) if not told then told = publish() and true if not told then say("cannot write the table votescript_types") end end -- Only players with something new, in one query. for _, row in ipairs(query("SELECT `player` FROM `votescript_items` WHERE `given` = 0 UNION SELECT `player` FROM `votescript_requests` WHERE `state` = 1 AND `told` = 0 LIMIT 200", { player = "s" })) do local player = Player(row.player) -- Player(name) may match the start of a name; the exact one must match. if player and player:getName():lower() == row.player:lower() then deliver(player) end end return true end event:interval(3000) event:register()