Skip to content

Instantly share code, notes, and snippets.

@imring
Last active September 12, 2019 16:33
Show Gist options
  • Save imring/8704d6b6c5d3721e12e5107a4b2ca5c8 to your computer and use it in GitHub Desktop.
Save imring/8704d6b6c5d3721e12e5107a4b2ca5c8 to your computer and use it in GitHub Desktop.
local function script_path() -- https://stackoverflow.com/a/39637679
local str = debug.getinfo(2, 'S').source:sub(2)
return str:match('(.*/)')
end
local function char_to_hex(str)
return string.format("%%%02X", string.byte(str))
end
local function url_encode(str)
local str = string.gsub(str, "\\", "\\")
local str = string.gsub(str, "([^%w])", char_to_hex)
return str
end
local function http_build_query(query)
local buff=""
for k, v in pairs(query) do
buff = buff.. string.format("%s=%s&", k, url_encode(v))
end
local buff = string.reverse(string.gsub(string.reverse(buff), "&", "", 1))
return buff
end
package.path = script_path() .. '?.lua;' .. package.path
local requests = require 'requests' -- https://luarocks.org/modules/jakeg/lua-requests
local json = require 'json' -- https://github.com/rxi/json.lua
local token = require 'token' -- ./token.lua
local function get_post_json()
ngx.req.read_body()
local args_str = ngx.var.request_body
local ok, res = pcall(json.decode, args_str)
if ok then return res end
end
local function send_text(id, text)
local args = http_build_query{ chat_id = id, text = text }
local response = requests.request('POST', 'https://api.telegram.org/bot' .. token .. '/sendMessage?' .. args)
end
local _POST = get_post_json()
if _POST and _POST.update_id then -- tg
local msg = _POST.message.text
if msg == 'ping' then
send_text(_POST.message.chat.id, 'pong')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment