Last active
May 5, 2021 15:49
-
-
Save imring/c35bdfce7b37c78652f63c04d0d5473e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local requests = require 'requests' | |
local url = 'https://api.telegram.org/bot%s/%s' | |
local mt = {} | |
-- http://lua-users.org/wiki/CopyTable | |
local function shallowcopy(orig) | |
local orig_type = type(orig) | |
local copy | |
if orig_type == 'table' then | |
copy = {} | |
for orig_key, orig_value in pairs(orig) do | |
copy[orig_key] = orig_value | |
end | |
else -- number, string, boolean, etc | |
copy = orig | |
end | |
return copy | |
end | |
function mt.__call(self, data) | |
assert(self.method, 'self.method == nil') | |
local res = requests.post{ url:format(self.token, self.method), params = data } | |
return res.json() | |
end | |
function mt.__index(self, index) | |
local v = rawget(self, index) | |
if v ~= nil then return v end | |
local t = shallowcopy(self) | |
t.method = index | |
local mtt = shallowcopy(getmetatable(self)) | |
mtt.__index = nil | |
return setmetatable(t, mtt) | |
end | |
local function new(token) | |
local bot = { token = token, method = nil } | |
return setmetatable(bot, mt) | |
end | |
local token = 'your token' | |
local bot = new(token) | |
local res, err = assert(bot.getMe()) | |
if not res.ok then | |
error(tostring(res.error_code) .. ': ' .. res.description) | |
end | |
for i, k in pairs(res.result) do | |
print(i, k) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment