I should probably commit now. Less global magic!

This commit is contained in:
Brayden Banks 2016-04-08 14:12:02 -07:00
parent 550d0743b7
commit acb679f8fa
41 changed files with 1213 additions and 1241 deletions

View File

@ -53,13 +53,13 @@ Most plugins are intended for public use, but a few are for other purposes, like
A plugin can have five components, and two of them are required: A plugin can have five components, and two of them are required:
| Component | Description | Required? | | Component | Description | Required? |
|:----------|:---------------------------------------------|:----------| |:----------|:-----------------------------------------------------|:----------|
| action | Main function. Expects `msg` table as an argument. | Y | | action | Main function. Expects `msg` table as an argument. | Y |
| triggers | Table of triggers for the plugin. Uses Lua patterns. | Y | | triggers | Table of triggers for the plugin. Uses Lua patterns. | Y |
| cron | Optional function to be called every minute. | N | | cron | Optional function to be called every minute. | N |
| command | Basic command and syntax. Listed in the help text. | N | | command | Basic command and syntax. Listed in the help text. | N |
| doc | Usage for the plugin. Returned by "/help $command". | N | | doc | Usage for the plugin. Returned by "/help $command". | N |
The `on_msg_receive()` function adds a few variables to the `msg` table for your convenience. These are self-explanatory: `msg.from.id_str`, `msg.to.id_str`, `msg.chat.id_str`, `msg.text_lower`, `msg.from.name`. The `on_msg_receive()` function adds a few variables to the `msg` table for your convenience. These are self-explanatory: `msg.from.id_str`, `msg.to.id_str`, `msg.chat.id_str`, `msg.text_lower`, `msg.from.name`.

View File

@ -2,17 +2,13 @@
-- Bindings for the Telegram bot API. -- Bindings for the Telegram bot API.
-- https://core.telegram.org/bots/api -- https://core.telegram.org/bots/api
assert(HTTPS) local bindings = {}
assert(JSON)
assert(URL)
local BASE_URL = 'https://api.telegram.org/bot' .. config.bot_api_key local HTTPS = require('ssl.https')
local JSON = require('cjson')
local URL = require('socket.url')
if config.bot_api_key == '' then function bindings.sendRequest(url)
error('You did not set your bot token in config.lua!')
end
sendRequest = function(url)
local dat, res = HTTPS.request(url) local dat, res = HTTPS.request(url)
@ -30,28 +26,28 @@ sendRequest = function(url)
end end
getMe = function() function bindings:getMe()
local url = BASE_URL .. '/getMe' local url = self.BASE_URL .. '/getMe'
return sendRequest(url) return bindings.sendRequest(url)
end end
getUpdates = function(offset) function bindings:getUpdates(offset)
local url = BASE_URL .. '/getUpdates?timeout=20' local url = self.BASE_URL .. '/getUpdates?timeout=20'
if offset then if offset then
url = url .. '&offset=' .. offset url = url .. '&offset=' .. offset
end end
return sendRequest(url) return bindings.sendRequest(url)
end end
sendMessage = function(chat_id, text, disable_web_page_preview, reply_to_message_id, use_markdown, disable_notification) function bindings:sendMessage(chat_id, text, disable_web_page_preview, reply_to_message_id, use_markdown, disable_notification)
local url = BASE_URL .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. URL.escape(text) local url = self.BASE_URL .. '/sendMessage?chat_id=' .. chat_id .. '&text=' .. URL.escape(text)
if disable_web_page_preview == true then if disable_web_page_preview == true then
url = url .. '&disable_web_page_preview=true' url = url .. '&disable_web_page_preview=true'
@ -69,30 +65,30 @@ sendMessage = function(chat_id, text, disable_web_page_preview, reply_to_message
url = url .. '&disable_notification=true' url = url .. '&disable_notification=true'
end end
return sendRequest(url) return bindings.sendRequest(url)
end end
sendReply = function(msg, text) function bindings:sendReply(msg, text)
return sendMessage(msg.chat.id, text, true, msg.message_id) return bindings.sendMessage(self, msg.chat.id, text, true, msg.message_id)
end end
sendChatAction = function(chat_id, action) function bindings:sendChatAction(chat_id, action)
-- Support actions are typing, upload_photo, record_video, upload_video, record_audio, upload_audio, upload_document, find_location -- Support actions are typing, upload_photo, record_video, upload_video, record_audio, upload_audio, upload_document, find_location
local url = BASE_URL .. '/sendChatAction?chat_id=' .. chat_id .. '&action=' .. action local url = self.BASE_URL .. '/sendChatAction?chat_id=' .. chat_id .. '&action=' .. action
return sendRequest(url) return bindings.sendRequest(self, url)
end end
sendLocation = function(chat_id, latitude, longitude, reply_to_message_id, disable_notification) function bindings:sendLocation(chat_id, latitude, longitude, reply_to_message_id, disable_notification)
if latitude == 0 then latitude = 0.001 end if latitude == 0 then latitude = 0.001 end
if longitude == 0 then longitude = 0.001 end if longitude == 0 then longitude = 0.001 end
local url = BASE_URL .. '/sendLocation?chat_id=' .. chat_id .. '&latitude=' .. latitude .. '&longitude=' .. longitude local url = self.BASE_URL .. '/sendLocation?chat_id=' .. chat_id .. '&latitude=' .. latitude .. '&longitude=' .. longitude
if reply_to_message_id then if reply_to_message_id then
url = url .. '&reply_to_message_id=' .. reply_to_message_id url = url .. '&reply_to_message_id=' .. reply_to_message_id
@ -102,27 +98,27 @@ sendLocation = function(chat_id, latitude, longitude, reply_to_message_id, disab
url = url .. '&disable_notification=true' url = url .. '&disable_notification=true'
end end
return sendRequest(url) return bindings.sendRequest(self, url)
end end
forwardMessage = function(chat_id, from_chat_id, message_id, disable_notification) function bindings:forwardMessage(chat_id, from_chat_id, message_id, disable_notification)
local url = BASE_URL .. '/forwardMessage?chat_id=' .. chat_id .. '&from_chat_id=' .. from_chat_id .. '&message_id=' .. message_id local url = self.BASE_URL .. '/forwardMessage?chat_id=' .. chat_id .. '&from_chat_id=' .. from_chat_id .. '&message_id=' .. message_id
if disable_notification then if disable_notification then
url = url .. '&disable_notification=true' url = url .. '&disable_notification=true'
end end
return sendRequest(url) return bindings.sendRequest(self, url)
end end
-- TODO: More of this. -- TODO: More of this.
sendPhotoID = function(chat_id, file_id, caption, reply_to_message_id, disable_notification) function bindings:sendPhotoID(chat_id, file_id, caption, reply_to_message_id, disable_notification)
local url = BASE_URL .. '/sendPhoto?chat_id=' .. chat_id .. '&photo=' .. file_id local url = self.BASE_URL .. '/sendPhoto?chat_id=' .. chat_id .. '&photo=' .. file_id
if caption then if caption then
url = url .. '&caption=' .. URL.escape(caption) url = url .. '&caption=' .. URL.escape(caption)
@ -136,20 +132,20 @@ sendPhotoID = function(chat_id, file_id, caption, reply_to_message_id, disable_n
url = url .. '&disable_notification=true' url = url .. '&disable_notification=true'
end end
return sendRequest(url) return bindings.sendRequest(self, url)
end end
curlRequest = function(curl_command) function bindings.curlRequest(curl_command)
-- Use at your own risk. Will not check for success. -- Use at your own risk. Will not check for success.
io.popen(curl_command) io.popen(curl_command)
end end
sendPhoto = function(chat_id, photo, caption, reply_to_message_id, disable_notification) function bindings:sendPhoto(chat_id, photo, caption, reply_to_message_id, disable_notification)
local url = BASE_URL .. '/sendPhoto' local url = self.BASE_URL .. '/sendPhoto'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "photo=@' .. photo .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "photo=@' .. photo .. '"'
@ -165,13 +161,13 @@ sendPhoto = function(chat_id, photo, caption, reply_to_message_id, disable_notif
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
sendDocument = function(chat_id, document, reply_to_message_id, disable_notification) function bindings:sendDocument(chat_id, document, reply_to_message_id, disable_notification)
local url = BASE_URL .. '/sendDocument' local url = self.BASE_URL .. '/sendDocument'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "document=@' .. document .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "document=@' .. document .. '"'
@ -183,13 +179,13 @@ sendDocument = function(chat_id, document, reply_to_message_id, disable_notifica
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
sendSticker = function(chat_id, sticker, reply_to_message_id, disable_notification) function bindings:sendSticker(chat_id, sticker, reply_to_message_id, disable_notification)
local url = BASE_URL .. '/sendSticker' local url = self.BASE_URL .. '/sendSticker'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "sticker=@' .. sticker .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "sticker=@' .. sticker .. '"'
@ -201,13 +197,13 @@ sendSticker = function(chat_id, sticker, reply_to_message_id, disable_notificati
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
sendAudio = function(chat_id, audio, reply_to_message_id, duration, performer, title, disable_notification) function bindings:sendAudio(chat_id, audio, reply_to_message_id, duration, performer, title, disable_notification)
local url = BASE_URL .. '/sendAudio' local url = self.BASE_URL .. '/sendAudio'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "audio=@' .. audio .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "audio=@' .. audio .. '"'
@ -231,13 +227,13 @@ sendAudio = function(chat_id, audio, reply_to_message_id, duration, performer, t
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
sendVideo = function(chat_id, video, reply_to_message_id, duration, caption, disable_notification) function bindings:sendVideo(chat_id, video, reply_to_message_id, duration, caption, disable_notification)
local url = BASE_URL .. '/sendVideo' local url = self.BASE_URL .. '/sendVideo'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "video=@' .. video .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "video=@' .. video .. '"'
@ -257,13 +253,13 @@ sendVideo = function(chat_id, video, reply_to_message_id, duration, caption, dis
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
sendVoice = function(chat_id, voice, reply_to_message_id, duration, disable_notification) function bindings:sendVoice(chat_id, voice, reply_to_message_id, duration, disable_notification)
local url = BASE_URL .. '/sendVoice' local url = self.BASE_URL .. '/sendVoice'
local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "voice=@' .. voice .. '"' local curl_command = 'curl -s "' .. url .. '" -F "chat_id=' .. chat_id .. '" -F "voice=@' .. voice .. '"'
@ -279,6 +275,8 @@ sendVoice = function(chat_id, voice, reply_to_message_id, duration, disable_noti
curl_command = curl_command .. ' -F "disable_notification=true"' curl_command = curl_command .. ' -F "disable_notification=true"'
end end
return curlRequest(curl_command) return bindings.curlRequest(curl_command)
end end
return bindings

124
bot.lua
View File

@ -1,73 +1,77 @@
HTTP = require('socket.http') local bot = {}
HTTPS = require('ssl.https')
URL = require('socket.url')
JSON = require('cjson')
version = '3.5' local bindings = require('bindings') -- Load Telegram bindings.
local utilities = require('utilities') -- Load miscellaneous and cross-plugin functions.
bot_init = function() -- The function run when the bot is started or reloaded. bot.version = '3.5'
config = dofile('config.lua') -- Load configuration file. function bot:init() -- The function run when the bot is started or reloaded.
dofile('bindings.lua') -- Load Telegram bindings.
dofile('utilities.lua') -- Load miscellaneous and cross-plugin functions. self.config = require('config') -- Load configuration file.
self.BASE_URL = 'https://api.telegram.org/bot' .. self.config.bot_api_key
if self.config.bot_api_key == '' then
error('You did not set your bot token in config.lua!')
end
-- Fetch bot information. Try until it succeeds. -- Fetch bot information. Try until it succeeds.
repeat bot = getMe() until bot repeat self.info = bindings.getMe(self) until self.info
bot = bot.result self.info = self.info.result
-- Load the "database"! ;) -- Load the "database"! ;)
if not database then if not self.database then
database = load_data(bot.username..'.db') self.database = utilities.load_data(self.info.username..'.db')
end end
plugins = {} -- Load plugins. self.plugins = {} -- Load plugins.
for i,v in ipairs(config.plugins) do for _,v in ipairs(self.config.plugins) do
local p = dofile('plugins/'..v) local p = require('plugins/'..v)
table.insert(plugins, p) table.insert(self.plugins, p)
if p.init then p.init(self) end
end end
print('@' .. bot.username .. ', AKA ' .. bot.first_name ..' ('..bot.id..')') print('@' .. self.info.username .. ', AKA ' .. self.info.first_name ..' ('..self.info.id..')')
-- Generate a random seed and "pop" the first random number. :) -- Generate a random seed and "pop" the first random number. :)
math.randomseed(os.time()) math.randomseed(os.time())
math.random() math.random()
last_update = last_update or 0 -- Set loop variables: Update offset, self.last_update = self.last_update or 0 -- Set loop variables: Update offset,
last_cron = last_cron or os.date('%M') -- the time of the last cron job, self.last_cron = self.last_cron or os.date('%M') -- the time of the last cron job,
is_started = true -- and whether or not the bot should be running. self.is_started = true -- and whether or not the bot should be running.
database.users = database.users or {} -- Table to cache userdata. self.database.users = self.database.users or {} -- Table to cache userdata.
database.users[tostring(bot.id)] = bot self.database.users[tostring(self.info.id)] = self.info
-- Migration code. Remove in 3.6. -- Migration code. Remove in 3.6.
if database.lastfm then if self.database.lastfm then
for k,v in pairs(database.lastfm) do for k,v in pairs(self.database.lastfm) do
if not database.users[k] then database.users[k] = {} end if not self.database.users[k] then self.database.users[k] = {} end
database.users[k].lastfm = v self.database.users[k].lastfm = v
end end
end end
-- Migration code. Remove in 3.6. -- Migration code. Remove in 3.6.
if database.nicknames then if self.database.nicknames then
for k,v in pairs(database.nicknames) do for k,v in pairs(self.database.nicknames) do
if not database.users[k] then database.users[k] = {} end if not self.database.users[k] then self.database.users[k] = {} end
database.users[k].nickname = v self.database.users[k].nickname = v
end end
end end
end end
on_msg_receive = function(msg) -- The fn run whenever a message is received. function bot:on_msg_receive(msg) -- The fn run whenever a message is received.
-- Create a user entry if it does not exist. -- Create a user entry if it does not exist.
if not database.users[tostring(msg.from.id)] then if not self.database.users[tostring(msg.from.id)] then
database.users[tostring(msg.from.id)] = {} self.database.users[tostring(msg.from.id)] = {}
end end
-- Clear things that no longer exist. -- Clear things that no longer exist.
database.users[tostring(msg.from.id)].username = nil self.database.users[tostring(msg.from.id)].username = nil
database.users[tostring(msg.from.id)].last_name = nil self.database.users[tostring(msg.from.id)].last_name = nil
-- Wee. -- Wee.
for k,v in pairs(msg.from) do for k,v in pairs(msg.from) do
database.users[tostring(msg.from.id)][k] = v self.database.users[tostring(msg.from.id)][k] = v
end end
if msg.date < os.time() - 5 then return end -- Do not process old messages. if msg.date < os.time() - 5 then return end -- Do not process old messages.
@ -78,24 +82,24 @@ on_msg_receive = function(msg) -- The fn run whenever a message is received.
end -- If the replied-to message has a caption, make that its text. end -- If the replied-to message has a caption, make that its text.
if msg.text:match('^/start .+') then if msg.text:match('^/start .+') then
msg.text = '/' .. msg.text:input() msg.text = '/' .. utilities.input(msg.text)
end end
for i,v in ipairs(plugins) do for _,v in ipairs(self.plugins) do
for k,w in pairs(v.triggers) do for _,w in pairs(v.triggers) do
if string.match(msg.text:lower(), w) then if string.match(msg.text:lower(), w) then
-- a few shortcuts -- a few shortcuts
msg.chat.id_str = tostring(msg.chat.id) msg.chat.id_str = tostring(msg.chat.id)
msg.from.id_str = tostring(msg.from.id) msg.from.id_str = tostring(msg.from.id)
msg.text_lower = msg.text:lower() msg.text_lower = msg.text:lower()
msg.from.name = build_name(msg.from.first_name, msg.from.last_name) msg.from.name = utilities.build_name(msg.from.first_name, msg.from.last_name)
local success, result = pcall(function() local success, result = pcall(function()
return v.action(msg) return v.action(self, msg)
end) end)
if not success then if not success then
sendReply(msg, 'Sorry, an unexpected error occurred.') bindings.sendReply(self, msg, 'Sorry, an unexpected error occurred.')
handle_exception(result, msg.from.id .. ': ' .. msg.text) bindings.handle_exception(self, result, msg.from.id .. ': ' .. msg.text)
return return
end end
-- If the action returns a table, make that table msg. -- If the action returns a table, make that table msg.
@ -111,28 +115,30 @@ on_msg_receive = function(msg) -- The fn run whenever a message is received.
end end
bot_init() -- Actually start the script. Run the bot_init function. bot.init(bot) -- Actually start the script. Run the bot_init function.
while is_started do -- Start a loop while the bot should be running. while bot.is_started do -- Start a loop while the bot should be running.
local res = getUpdates(last_update+1) -- Get the latest updates! do
if res then local res = bindings.getUpdates(bot, bot.last_update+1) -- Get the latest updates!
for i,v in ipairs(res.result) do -- Go through every new message. if res then
last_update = v.update_id for _,v in ipairs(res.result) do -- Go through every new message.
on_msg_receive(v.message) bot.last_update = v.update_id
bot.on_msg_receive(bot, v.message)
end
else
print(bot.config.errors.connection)
end end
else
print(config.errors.connection)
end end
if last_cron ~= os.date('%M') then -- Run cron jobs every minute. if bot.last_cron ~= os.date('%M') then -- Run cron jobs every minute.
last_cron = os.date('%M') bot.last_cron = os.date('%M')
save_data(bot.username..'.db', database) -- Save the database. utilities.save_data(bot.info.username..'.db', bot.database) -- Save the database.
for i,v in ipairs(plugins) do for i,v in ipairs(bot.plugins) do
if v.cron then -- Call each plugin's cron function, if it has one. if v.cron then -- Call each plugin's cron function, if it has one.
local res, err = pcall(function() v.cron() end) local res, err = pcall(function() v.cron() end)
if not res then if not res then
handle_exception(err, 'CRON: ' .. i) utilities.handle_exception(bot, err, 'CRON: ' .. i)
end end
end end
end end
@ -141,5 +147,5 @@ while is_started do -- Start a loop while the bot should be running.
end end
-- Save the database before exiting. -- Save the database before exiting.
save_data(bot.username..'.db', database) utilities.save_data(bot.info.username..'.db', bot.database)
print('Halted.') print('Halted.')

View File

@ -1,26 +1,30 @@
local command = 'about' local about = {}
local doc = '`Returns information about the bot.`'
local triggers = { local bindings = require('bindings')
about.command = 'about'
about.doc = '`Returns information about the bot.`'
about.triggers = {
'' ''
} }
local action = function(msg) function about:action(msg)
-- Filthy hack, but here is where we'll stop forwarded messages from hitting -- Filthy hack, but here is where we'll stop forwarded messages from hitting
-- other plugins. -- other plugins.
if msg.forward_from then return end if msg.forward_from then return end
local message = config.about_text .. '\nBased on @otouto v'..version..' by topkecleon.' local message = self.config.about_text .. '\nBased on @otouto v'..self.version..' by topkecleon.'
if msg.new_chat_participant and msg.new_chat_participant.id == bot.id then if msg.new_chat_participant and msg.new_chat_participant.id == self.info.id then
sendMessage(msg.chat.id, message, true) bindings.sendMessage(self, msg.chat.id, message, true)
return return
elseif msg.text_lower:match('^/about[@'..bot.username..']*') then elseif msg.text_lower:match('^/about[@'..self.info.username..']*') then
sendMessage(msg.chat.id, message, true) bindings.sendMessage(self, msg.chat.id, message, true)
return return
elseif msg.text_lower:match('^/start') then elseif msg.text_lower:match('^/start') then
sendMessage(msg.chat.id, message, true) bindings.sendMessage(self, msg.chat.id, message, true)
return return
end end
@ -28,9 +32,4 @@ local action = function(msg)
end end
return { return about
action = action,
triggers = triggers,
doc = doc,
command = command
}

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,13 @@
local command = 'apod [date]' local apod = {}
local doc = [[```
local HTTPS = require('ssl.https')
local JSON = require('cjson')
local URL = require('socket.url')
local bindings = require('bindings')
local utilities = require('utilities')
apod.command = 'apod [date]'
apod.doc = [[```
/apod [query] /apod [query]
Returns the Astronomy Picture of the Day. Returns the Astronomy Picture of the Day.
If the query is a date, in the format YYYY-MM-DD, the APOD of that day is returned. If the query is a date, in the format YYYY-MM-DD, the APOD of that day is returned.
@ -10,31 +18,29 @@ Returns the explanation of the APOD.
Source: nasa.gov Source: nasa.gov
```]] ```]]
local triggers = { function apod:init()
'^/apod[@'..bot.username..']*', apod.triggers = utilities.triggers(self.info.username)
'^/apodhd[@'..bot.username..']*', :t('apod', true):t('apodhd', true):t('apodtext', true).table
'^/apodtext[@'..bot.username..']*' end
}
local action = function(msg) function apod:action(msg)
if not config.nasa_api_key then if not self.config.nasa_api_key then
config.nasa_api_key = 'DEMO_KEY' self.config.nasa_api_key = 'DEMO_KEY'
end end
local input = msg.text:input() local input = utilities.input(msg.text)
local caption = ''
local date = '*' local date = '*'
local disable_page_preview = false local disable_page_preview = false
local url = 'https://api.nasa.gov/planetary/apod?api_key=' .. config.nasa_api_key local url = 'https://api.nasa.gov/planetary/apod?api_key=' .. self.config.nasa_api_key
if input then if input then
if input:match('(%d+)%-(%d+)%-(%d+)$') then if input:match('(%d+)%-(%d+)%-(%d+)$') then
url = url .. '&date=' .. URL.escape(input) url = url .. '&date=' .. URL.escape(input)
date = date .. input date = date .. input
else else
sendMessage(msg.chat.id, doc, true, msg.message_id, true) bindings.sendMessage(self, msg.chat.id, apod.doc, true, msg.message_id, true)
return return
end end
else else
@ -45,14 +51,14 @@ local action = function(msg)
local jstr, res = HTTPS.request(url) local jstr, res = HTTPS.request(url)
if res ~= 200 then if res ~= 200 then
sendReply(msg, config.errors.connection) bindings.sendReply(self, msg, self.config.errors.connection)
return return
end end
local jdat = JSON.decode(jstr) local jdat = JSON.decode(jstr)
if jdat.error then if jdat.error then
sendReply(msg, config.errors.results) bindings.sendReply(msg, self.config.errors.results)
return return
end end
@ -62,7 +68,7 @@ local action = function(msg)
img_url = jdat.hdurl or jdat.url img_url = jdat.hdurl or jdat.url
end end
output = date .. '[' .. jdat.title .. '](' .. img_url .. ')' local output = date .. '[' .. jdat.title .. '](' .. img_url .. ')'
if string.match(msg.text, '^/apodtext*') then if string.match(msg.text, '^/apodtext*') then
output = output .. '\n' .. jdat.explanation output = output .. '\n' .. jdat.explanation
@ -73,13 +79,8 @@ local action = function(msg)
output = output .. '\nCopyright: ' .. jdat.copyright output = output .. '\nCopyright: ' .. jdat.copyright
end end
sendMessage(msg.chat.id, output, disable_page_preview, nil, true) bindings.sendMessage(self, msg.chat.id, output, disable_page_preview, nil, true)
end end
return { return apod
action = action,
triggers = triggers,
doc = doc,
command = command
}

View File

@ -1,13 +1,17 @@
local command = 'bandersnatch' local bandersnatch = {}
local doc = [[```
local bindings = require('bindings')
local utilities = require('utilities')
bandersnatch.command = 'bandersnatch'
bandersnatch.doc = [[```
Shun the frumious Bandersnatch. Shun the frumious Bandersnatch.
Alias: /bc Alias: /bc
```]] ```]]
local triggers = { function bandersnatch:init()
'^/bandersnatch[@'..bot.username..']*', bandersnatch.triggers = utilities.triggers(self.info.username):trigger('bandersnatch'):trigger('bc').table
'^/bc[@'..bot.username..']*' end
}
local fullnames = { "Wimbledon Tennismatch", "Rinkydink Curdlesnoot", "Butawhiteboy Cantbekhan", "Benadryl Claritin", "Bombadil Rivendell", "Wanda's Crotchfruit", "Biblical Concubine", "Syphilis Cankersore", "Buckminster Fullerene", "Bourgeoisie Capitalist" } local fullnames = { "Wimbledon Tennismatch", "Rinkydink Curdlesnoot", "Butawhiteboy Cantbekhan", "Benadryl Claritin", "Bombadil Rivendell", "Wanda's Crotchfruit", "Biblical Concubine", "Syphilis Cankersore", "Buckminster Fullerene", "Bourgeoisie Capitalist" }
@ -15,7 +19,7 @@ local firstnames = { "Bumblebee", "Bandersnatch", "Broccoli", "Rinkydink", "Bomb
local lastnames = { "Coddleswort", "Crumplesack", "Curdlesnoot", "Calldispatch", "Humperdinck", "Rivendell", "Cuttlefish", "Lingerie", "Vegemite", "Ampersand", "Cumberbund", "Candycrush", "Clombyclomp", "Cragglethatch", "Nottinghill", "Cabbagepatch", "Camouflage","Creamsicle", "Curdlemilk", "Upperclass", "Frumblesnatch", "Crumplehorn", "Talisman", "Candlestick", "Chesterfield", "Bumbersplat", "Scratchnsniff", "Snugglesnatch", "Charizard", "Carrotstick", "Cumbercooch", "Crackerjack", "Crucifix", "Cuckatoo", "Cockletit", "Collywog", "Capncrunch", "Covergirl", "Cumbersnatch", "Countryside","Coggleswort", "Splishnsplash", "Copperwire", "Animorph", "Curdledmilk", "Cheddarcheese", "Cottagecheese", "Crumplehorn", "Snickersbar", "Banglesnatch", "Stinkyrash", "Cameltoe", "Chickenbroth", "Concubine", "Candygram", "Moldyspore", "Chuckecheese", "Cankersore", "Crimpysnitch", "Wafflesmack", "Chowderpants", "Toodlesnoot", "Clavichord", "Cuckooclock", "Oxfordshire", "Cumbersome", "Chickenstrips", "Battleship", "Commonwealth", "Cunningsnatch", "Custardbath", "Kryptonite", "Curdlesnoot", "Cummerbund", "Coochyrash", "Crackerdong", "Crackerdong", "Curdledong", "Crackersprout", "Crumplebutt", "Colonist", "Coochierash", "Thundersnatch" } local lastnames = { "Coddleswort", "Crumplesack", "Curdlesnoot", "Calldispatch", "Humperdinck", "Rivendell", "Cuttlefish", "Lingerie", "Vegemite", "Ampersand", "Cumberbund", "Candycrush", "Clombyclomp", "Cragglethatch", "Nottinghill", "Cabbagepatch", "Camouflage","Creamsicle", "Curdlemilk", "Upperclass", "Frumblesnatch", "Crumplehorn", "Talisman", "Candlestick", "Chesterfield", "Bumbersplat", "Scratchnsniff", "Snugglesnatch", "Charizard", "Carrotstick", "Cumbercooch", "Crackerjack", "Crucifix", "Cuckatoo", "Cockletit", "Collywog", "Capncrunch", "Covergirl", "Cumbersnatch", "Countryside","Coggleswort", "Splishnsplash", "Copperwire", "Animorph", "Curdledmilk", "Cheddarcheese", "Cottagecheese", "Crumplehorn", "Snickersbar", "Banglesnatch", "Stinkyrash", "Cameltoe", "Chickenbroth", "Concubine", "Candygram", "Moldyspore", "Chuckecheese", "Cankersore", "Crimpysnitch", "Wafflesmack", "Chowderpants", "Toodlesnoot", "Clavichord", "Cuckooclock", "Oxfordshire", "Cumbersome", "Chickenstrips", "Battleship", "Commonwealth", "Cunningsnatch", "Custardbath", "Kryptonite", "Curdlesnoot", "Cummerbund", "Coochyrash", "Crackerdong", "Crackerdong", "Curdledong", "Crackersprout", "Crumplebutt", "Colonist", "Coochierash", "Thundersnatch" }
local action = function(msg) function bandersnatch:action(msg)
local message local message
@ -25,13 +29,8 @@ local action = function(msg)
message = firstnames[math.random(#firstnames)] .. ' ' .. lastnames[math.random(#lastnames)] message = firstnames[math.random(#firstnames)] .. ' ' .. lastnames[math.random(#lastnames)]
end end
sendReply(msg, message) bindings.sendReply(self, msg, message)
end end
return { return bandersnatch
action = action,
triggers = triggers,
command = command,
desc = desc
}

View File

@ -1,54 +1,54 @@
if not config.biblia_api_key then local bible = {}
print('Missing config value: biblia_api_key.')
print('bible.lua will not be enabled.') local HTTP = require('socket.http')
return local URL = require('socket.url')
local bindings = require('bindings')
local utilities = require('utilities')
function bible:init()
if not self.config.biblia_api_key then
print('Missing config value: biblia_api_key.')
print('bible.lua will not be enabled.')
return
end
bible.triggers = utilities.triggers(self.info.username):t('bible', true):t('b', true).table
end end
local command = 'bible <reference>' bible.command = 'bible <reference>'
local doc = [[``` bible.doc = [[```
/bible <reference> /bible <reference>
Returns a verse from the American Standard Version of the Bible, or an apocryphal verse from the King James Version. Results from biblia.com. Returns a verse from the American Standard Version of the Bible, or an apocryphal verse from the King James Version. Results from biblia.com.
Alias: /b Alias: /b
```]] ```]]
local triggers = { function bible:action(msg)
'^/bible*[@'..bot.username..']*',
'^/b[@'..bot.username..']* ',
'^/b[@'..bot.username..']*$'
}
local action = function(msg) local input = utilities.input(msg.text)
local input = msg.text:input()
if not input then if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) bindings.sendMessage(self, msg.chat.id, self.doc, true, msg.message_id, true)
return return
end end
local url = 'http://api.biblia.com/v1/bible/content/ASV.txt?key=' .. config.biblia_api_key .. '&passage=' .. URL.escape(input) local url = 'http://api.biblia.com/v1/bible/content/ASV.txt?key=' .. self.config.biblia_api_key .. '&passage=' .. URL.escape(input)
local message, res = HTTP.request(url) local message, res = HTTP.request(url)
if not message or res ~= 200 or message:len() == 0 then if not message or res ~= 200 or message:len() == 0 then
url = 'http://api.biblia.com/v1/bible/content/KJVAPOC.txt?key=' .. config.biblia_api_key .. '&passage=' .. URL.escape(input) url = 'http://api.biblia.com/v1/bible/content/KJVAPOC.txt?key=' .. self.config.biblia_api_key .. '&passage=' .. URL.escape(input)
message, res = HTTP.request(url) message, res = HTTP.request(url)
end end
if not message or res ~= 200 or message:len() == 0 then if not message or res ~= 200 or message:len() == 0 then
message = config.errors.results message = self.config.errors.results
end end
if message:len() > 4000 then if message:len() > 4000 then
message = 'The text is too long to post here. Try being more specific.' message = 'The text is too long to post here. Try being more specific.'
end end
sendReply(msg, message) bindings.sendReply(self, msg, message)
end end
return { return bible
action = action,
triggers = triggers,
command = command,
doc = doc
}

View File

@ -1,24 +1,31 @@
-- This plugin will allow the admin to blacklist users who will be unable to -- This plugin will allow the admin to blacklist users who will be unable to
-- use the bot. This plugin should be at the top of your plugin list in config. -- use the bot. This plugin should be at the top of your plugin list in config.
if not database.blacklist then local blacklist = {}
database.blacklist = {}
local bindings = require('bindings')
local utilities = require('utilities')
function blacklist:init()
if not self.database.blacklist then
self.database.blacklist = {}
end
end end
local triggers = { blacklist.triggers = {
'' ''
} }
local action = function(msg) function blacklist:action(msg)
if database.blacklist[msg.from.id_str] then return end if self.database.blacklist[msg.from.id_str] then return end
if database.blacklist[msg.chat.id_str] then return end if self.database.blacklist[msg.chat.id_str] then return end
if not msg.text:match('^/blacklist') then return true end if not msg.text:match('^/blacklist') then return true end
if msg.from.id ~= config.admin then return end if msg.from.id ~= self.config.admin then return end
local target = user_from_message(msg) local target = utilities.user_from_message(self, msg)
if target.err then if target.err then
sendReply(msg, target.err) bindings.sendReply(self, msg, target.err)
return return
end end
@ -26,17 +33,14 @@ local triggers = {
target.name = 'Group' target.name = 'Group'
end end
if database.blacklist[tostring(target.id)] then if self.database.blacklist[tostring(target.id)] then
database.blacklist[tostring(target.id)] = nil self.database.blacklist[tostring(target.id)] = nil
sendReply(msg, target.name .. ' has been removed from the blacklist.') bindings.sendReply(self, msg, target.name .. ' has been removed from the blacklist.')
else else
database.blacklist[tostring(target.id)] = true self.database.blacklist[tostring(target.id)] = true
sendReply(msg, target.name .. ' has been added to the blacklist.') bindings.sendReply(self, msg, target.name .. ' has been added to the blacklist.')
end end
end end
return { return blacklist
action = action,
triggers = triggers
}

View File

@ -1,21 +1,28 @@
local command = 'calc <expression>' local calc = {}
local doc = [[```
local URL = require('socket.url')
local HTTPS = require('ssl.https')
local bindings = require('bindings')
local utilities = require('utilities')
calc.command = 'calc <expression>'
calc.doc = [[```
/calc <expression> /calc <expression>
Returns solutions to mathematical expressions and conversions between common units. Results provided by mathjs.org. Returns solutions to mathematical expressions and conversions between common units. Results provided by mathjs.org.
```]] ```]]
local triggers = { function calc:init()
'^/calc[@'..bot.username..']*' calc.triggers = utilities.triggers(self.info.username):t('calc', true).table
} end
local action = function(msg) function calc:action(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text
else else
sendMessage(msg.chat.id, doc, true, msg.message_id, true) bindings.sendMessage(msg.chat.id, calc.doc, true, msg.message_id, true)
return return
end end
end end
@ -24,19 +31,14 @@ local action = function(msg)
local output = HTTPS.request(url) local output = HTTPS.request(url)
if not output then if not output then
sendReply(msg, config.errors.connection) bindings.sendReply(self, msg, self.config.errors.connection)
return return
end end
output = '`' .. output .. '`' output = '`' .. output .. '`'
sendMessage(msg.chat.id, output, true, msg.message_id, true) bindings.sendMessage(self, msg.chat.id, output, true, msg.message_id, true)
end end
return { return calc
action = action,
triggers = triggers,
command = command,
doc = doc
}

View File

@ -1,38 +1,39 @@
if not config.thecatapi_key then local cats = {}
print('Missing config value: thecatapi_key.')
print('cats.lua will be enabled, but there are more features with a key.') local HTTP = require('socket.http')
local bindings = require('bindings')
local utilities = require('utilities')
function bindings:init()
if not self.config.thecatapi_key then
print('Missing config value: thecatapi_key.')
print('cats.lua will be enabled, but there are more features with a key.')
end
end end
local command = 'cat' cats.command = 'cat'
local doc = '`Returns a cat!`' cats.doc = '`Returns a cat!`'
local triggers = { cats.triggers = utilities.triggers():t('cat')
'^/cat[@'..bot.username..']*$'
}
local action = function(msg) function cats:action(msg)
local url = 'http://thecatapi.com/api/images/get?format=html&type=jpg' local url = 'http://thecatapi.com/api/images/get?format=html&type=jpg'
if config.thecatapi_key then if self.config.thecatapi_key then
url = url .. '&api_key=' .. config.thecatapi_key url = url .. '&api_key=' .. self.config.thecatapi_key
end end
local str, res = HTTP.request(url) local str, res = HTTP.request(url)
if res ~= 200 then if res ~= 200 then
sendReply(msg, config.errors.connection) bindings.sendReply(msg, self.config.errors.connection)
return return
end end
str = str:match('<img src="(.-)">') str = str:match('<img src="(.-)">')
local output = '[Cat!]('..str..')' local output = '[Cat!]('..str..')'
sendMessage(msg.chat.id, output, false, nil, true) bindings.sendMessage(self, msg.chat.id, output, false, nil, true)
end end
return { return cats
action = action,
triggers = triggers,
doc = doc,
command = command
}

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
if not input then if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return return

View File

@ -16,7 +16,7 @@ local action = function(msg)
sendChatAction(msg.chat.id, 'upload_photo') sendChatAction(msg.chat.id, 'upload_photo')
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then input = os.date('%F') end if not input then input = os.date('%F') end
if not input:match('^%d%d%d%d%-%d%d%-%d%d$') then input = os.date('%F') end if not input:match('^%d%d%d%d%-%d%d%-%d%d$') then input = os.date('%F') end

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)

View File

@ -27,7 +27,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -13,7 +13,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -14,7 +14,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -96,7 +96,7 @@ end
local action = function(msg) local action = function(msg)
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
if not input then if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return return

View File

@ -22,7 +22,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
-- Attempts to send the help message via PM. -- Attempts to send the help message via PM.
-- If msg is from a group, it tells the group whether the PM was successful. -- If msg is from a group, it tells the group whether the PM was successful.

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -24,7 +24,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if string.match(msg.text, '^/lastfm') then if string.match(msg.text, '^/lastfm') then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)

View File

@ -19,7 +19,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if string.match(msg.text, '^/librefm') then if string.match(msg.text, '^/librefm') then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)

View File

@ -8,7 +8,7 @@ local action = function(msg)
return return
end end
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
sendReply(msg, 'Please enter a string to load.') sendReply(msg, 'Please enter a string to load.')
return return

View File

@ -7,7 +7,7 @@ local action = function(msg)
local target = database.users[msg.from.id_str] local target = database.users[msg.from.id_str]
if msg.from.id == config.admin and (msg.reply_to_message or msg.text:input()) then if msg.from.id == config.admin and (msg.reply_to_message or utilities.input(msg.text)) then
target = user_from_message(msg) target = user_from_message(msg)
if target.err then if target.err then
sendReply(msg, target.err) sendReply(msg, target.err)

View File

@ -59,7 +59,7 @@ local commands = {
['^/modcast[@'..bot.username..']*'] = function(msg) ['^/modcast[@'..bot.username..']*'] = function(msg)
local output = msg.text:input() local output = utilities.input(msg.text)
if not output then if not output then
return 'You must include a message.' return 'You must include a message.'
end end
@ -149,7 +149,7 @@ local commands = {
return config.moderation.errors.not_admin return config.moderation.errors.not_admin
end end
local modid = msg.text:input() local modid = utilities.input(msg.text)
if not modid then if not modid then
if msg.reply_to_message then if msg.reply_to_message then
@ -184,7 +184,7 @@ local commands = {
end end
end end
local userid = msg.text:input() local userid = utilities.input(msg.text)
local usernm = userid local usernm = userid
if msg.reply_to_message then if msg.reply_to_message then
@ -216,7 +216,7 @@ local commands = {
end end
end end
local userid = msg.text:input() local userid = utilities.input(msg.text)
local usernm = userid local usernm = userid
if msg.reply_to_message then if msg.reply_to_message then

View File

@ -22,7 +22,7 @@ local action = function(msg)
end end
local output local output
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if database.users[target.id_str].nickname then if database.users[target.id_str].nickname then
output = target.name .. '\'s nickname is "' .. database.users[target.id_str].nickname .. '".' output = target.name .. '\'s nickname is "' .. database.users[target.id_str].nickname .. '".'

View File

@ -12,7 +12,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
sendMessage(msg.chat.id, doc, true, nil, true) sendMessage(msg.chat.id, doc, true, nil, true)

View File

@ -15,12 +15,12 @@ local triggers = {
local action = function(msg) local action = function(msg)
msg.text_lower = msg.text_lower:gsub('/r/', '/r r/') msg.text_lower = msg.text_lower:gsub('/r/', '/r r/')
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
if msg.text_lower:match('^/r/') then if msg.text_lower:match('^/r/') then
msg.text_lower = msg.text_lower:gsub('/r/', '/r r/') msg.text_lower = msg.text_lower:gsub('/r/', '/r r/')
input = get_word(msg.text_lower, 1) input = get_word(msg.text_lower, 1)
else else
input = msg.text_lower:input() input = utilities.input(msg.text_lower)
end end
local url local url

View File

@ -15,7 +15,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
database.setandget[msg.chat.id_str] = database.setandget[msg.chat.id_str] or {} database.setandget[msg.chat.id_str] = database.setandget[msg.chat.id_str] or {}
if msg.text_lower:match('^/set') then if msg.text_lower:match('^/set') then
@ -26,7 +26,7 @@ local action = function(msg)
end end
local name = get_word(input:lower(), 1) local name = get_word(input:lower(), 1)
local value = input:input() local value = utilities.input(input)
if not name or not value then if not name or not value then
sendMessage(msg.chat.id, doc, true, nil, true) sendMessage(msg.chat.id, doc, true, nil, true)

View File

@ -8,7 +8,7 @@ local action = function(msg)
return return
end end
local input = msg.text:input() local input = utilities.input(msg.text)
input = input:gsub('', '--') input = input:gsub('', '--')
if not input then if not input then

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
sendMessage(msg.chat.id, doc, true, msg.message_id, true) sendMessage(msg.chat.id, doc, true, msg.message_id, true)

View File

@ -94,7 +94,7 @@ local slaps = {
local action = function(msg) local action = function(msg)
local victim = msg.text:input() local victim = utilities.input(msg.text)
if msg.reply_to_message then if msg.reply_to_message then
if database.users[tostring(msg.reply_to_message.from.id)].nickname then if database.users[tostring(msg.reply_to_message.from.id)].nickname then
victim = database.users[tostring(msg.reply_to_message.from.id)].nickname victim = database.users[tostring(msg.reply_to_message.from.id)].nickname

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -11,7 +11,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -14,7 +14,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -16,7 +16,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -14,7 +14,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -10,7 +10,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
local jstr, res = HTTP.request('http://xkcd.com/info.0.json') local jstr, res = HTTP.request('http://xkcd.com/info.0.json')
if res ~= 200 then if res ~= 200 then

View File

@ -21,7 +21,7 @@ local triggers = {
local action = function(msg) local action = function(msg)
local input = msg.text:input() local input = utilities.input(msg.text)
if not input then if not input then
if msg.reply_to_message and msg.reply_to_message.text then if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text input = msg.reply_to_message.text

View File

@ -1,13 +1,17 @@
-- utilities.lua -- utilities.lua
-- Functions shared among plugins. -- Functions shared among plugins.
-- you're welcome, brayden :^) local utilities = {}
HTTP = HTTP or require('socket.http')
HTTPS = HTTPS or require('ssl.https') local HTTP = require('socket.http')
JSON = JSON or require('cjson') local ltn12 = require('ltn12')
local HTTPS = require('ssl.https')
local URL = require('socket.url')
local JSON = require('cjson')
local bindings = require('bindings')
-- get the indexed word in a string -- get the indexed word in a string
get_word = function(s, i) function utilities.get_word(s, i)
s = s or '' s = s or ''
i = i or 1 i = i or 1
@ -23,7 +27,7 @@ end
-- Like get_word(), but better. -- Like get_word(), but better.
-- Returns the actual index. -- Returns the actual index.
function string:index() function utilities.index(s)
local t = {} local t = {}
for w in s:gmatch('%g+') do for w in s:gmatch('%g+') do
table.insert(t, w) table.insert(t, w)
@ -32,16 +36,16 @@ function string:index()
end end
-- Returns the string after the first space. -- Returns the string after the first space.
function string:input() function utilities.input(s)
if not self:find(' ') then if not s:find(' ') then
return false return false
end end
return self:sub(self:find(' ')+1) return s:sub(s:find(' ')+1)
end end
-- I swear, I copied this from PIL, not yago! :) -- I swear, I copied this from PIL, not yago! :)
function string:trim() -- Trims whitespace from a string. function utilities.trim(str) -- Trims whitespace from a string.
local s = self:gsub('^%s*(.-)%s*$', '%1') local s = str:gsub('^%s*(.-)%s*$', '%1')
return s return s
end end
@ -75,7 +79,7 @@ local lc_list = {
} }
-- Replaces letters with corresponding Cyrillic characters. -- Replaces letters with corresponding Cyrillic characters.
latcyr = function(str) function utilities.latcyr(str)
for k,v in pairs(lc_list) do for k,v in pairs(lc_list) do
str = str:gsub(k, v) str = str:gsub(k, v)
end end
@ -83,7 +87,7 @@ latcyr = function(str)
end end
-- Loads a JSON file as a table. -- Loads a JSON file as a table.
load_data = function(filename) function utilities.load_data(filename)
local f = io.open(filename) local f = io.open(filename)
if not f then if not f then
@ -98,7 +102,7 @@ load_data = function(filename)
end end
-- Saves a table to a JSON file. -- Saves a table to a JSON file.
save_data = function(filename, data) function utilities.save_data(filename, data)
local s = JSON.encode(data) local s = JSON.encode(data)
local f = io.open(filename, 'w') local f = io.open(filename, 'w')
@ -108,18 +112,18 @@ save_data = function(filename, data)
end end
-- Gets coordinates for a location. Used by gMaps.lua, time.lua, weather.lua. -- Gets coordinates for a location. Used by gMaps.lua, time.lua, weather.lua.
get_coords = function(input) function utilities:get_coords(input)
local url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .. URL.escape(input) local url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' .. URL.escape(input)
local jstr, res = HTTP.request(url) local jstr, res = HTTP.request(url)
if res ~= 200 then if res ~= 200 then
return config.errors.connection return self.config.errors.connection
end end
local jdat = JSON.decode(jstr) local jdat = JSON.decode(jstr)
if jdat.status == 'ZERO_RESULTS' then if jdat.status == 'ZERO_RESULTS' then
return config.errors.results return self.config.errors.results
end end
return { return {
@ -130,10 +134,10 @@ get_coords = function(input)
end end
-- Get the number of values in a key/value table. -- Get the number of values in a key/value table.
table_size = function(tab) function utilities.table_size(tab)
local i = 0 local i = 0
for k,v in pairs(tab) do for _,_ in pairs(tab) do
i = i + 1 i = i + 1
end end
return i return i
@ -141,7 +145,7 @@ table_size = function(tab)
end end
-- Just an easy way to get a user's full name. -- Just an easy way to get a user's full name.
build_name = function(first, last) function utilities.build_name(first, last)
if last then if last then
return first .. ' ' .. last return first .. ' ' .. last
else else
@ -149,10 +153,10 @@ build_name = function(first, last)
end end
end end
resolve_username = function(input) function utilities:resolve_username(input)
input = input:gsub('^@', '') input = input:gsub('^@', '')
for k,v in pairs(database.users) do for _,v in pairs(self.database.users) do
if v.username and v.username:lower() == input:lower() then if v.username and v.username:lower() == input:lower() then
return v return v
end end
@ -160,22 +164,22 @@ resolve_username = function(input)
end end
user_from_message = function(msg) function utilities:user_from_message(msg)
local input = msg.text_lower:input() local input = utilities.input(msg.text_lower)
local target = {} local target = {}
if msg.reply_to_message then if msg.reply_to_message then
target = msg.reply_to_message.from target = msg.reply_to_message.from
elseif input and tonumber(input) then elseif input and tonumber(input) then
target.id = input target.id = input
if database.users[input] then if self.database.users[input] then
for k,v in pairs(database.users[input]) do for k,v in pairs(self.database.users[input]) do
target[k] = v target[k] = v
end end
end end
elseif input and input:match('^@') then elseif input and input:match('^@') then
local uname = input:gsub('^@', '') local uname = input:gsub('^@', '')
for k,v in pairs(database.users) do for _,v in pairs(self.database.users) do
if v.username and uname == v.username:lower() then if v.username and uname == v.username:lower() then
for key, val in pairs(v) do for key, val in pairs(v) do
target[key] = val target[key] = val
@ -195,21 +199,21 @@ user_from_message = function(msg)
if not target.first_name then target.first_name = 'User' end if not target.first_name then target.first_name = 'User' end
target.name = build_name(target.first_name, target.last_name) target.name = utilities.build_name(target.first_name, target.last_name)
return target return target
end end
handle_exception = function(err, message) function utilities:handle_exception(err, message)
if not err then err = '' end if not err then err = '' end
local output = '\n[' .. os.date('%F %T', os.time()) .. ']\n' .. bot.username .. ': ' .. err .. '\n' .. message .. '\n' local output = '\n[' .. os.date('%F %T', os.time()) .. ']\n' .. self.info.username .. ': ' .. err .. '\n' .. message .. '\n'
if config.log_chat then if self.config.log_chat then
output = '```' .. output .. '```' output = '```' .. output .. '```'
sendMessage(config.log_chat, output, true, nil, true) bindings.sendMessage(self, self.config.log_chat, output, true, nil, true)
else else
print(output) print(output)
end end
@ -218,7 +222,7 @@ end
-- Okay, this one I actually did copy from yagop. -- Okay, this one I actually did copy from yagop.
-- https://github.com/yagop/telegram-bot/blob/master/bot/utils.lua -- https://github.com/yagop/telegram-bot/blob/master/bot/utils.lua
download_file = function(url, filename) function utilities.download_file(url, filename)
local respbody = {} local respbody = {}
local options = { local options = {
@ -227,7 +231,7 @@ download_file = function(url, filename)
redirect = true redirect = true
} }
local response = nil local response
if url:match('^https') then if url:match('^https') then
options.redirect = false options.redirect = false
@ -252,7 +256,7 @@ download_file = function(url, filename)
end end
markdown_escape = function(text) function utilities.markdown_escape(text)
text = text:gsub('_', '\\_') text = text:gsub('_', '\\_')
text = text:gsub('%[', '\\[') text = text:gsub('%[', '\\[')
@ -262,11 +266,30 @@ markdown_escape = function(text)
end end
function string:md_escape() function utilities.md_escape(s)
local text = self s = s:gsub('_', '\\_')
text = text:gsub('_', '\\_') s = s:gsub('%[', '\\[')
text = text:gsub('%[', '\\[') s = s:gsub('%*', '\\*')
text = text:gsub('%*', '\\*') s = s:gsub('`', '\\`')
text = text:gsub('`', '\\`') return s
return text end
utilities.INVOCATION_PATTERN = '/'
utilities.triggers_metatable = {}
function utilities.triggers_metatable:t(pattern, has_args)
self.table:insert('^'..utilities.INVOCATION_PATTERN..pattern..'$')
self.table:insert('^'..utilities.INVOCATION_PATTERN..pattern..'@'..self.username..'$')
if has_args then
self.table:insert('^'..utilities.INVOCATION_PATTERN..pattern..'%s+[^%s]*')
self.table:insert('^'..utilities.INVOCATION_PATTERN..pattern..'@'..self.username..'%s+[^%s]*')
end
return self
end
function utilities.triggers(username)
local self = setmetatable({}, utilities.triggers_metatable)
self.username = username
self.table = {}
return self
end end