- Code-Optimierung

- Tabellen als Rückgabewerte von Plugins werden nicht mehr unterstützt
This commit is contained in:
Andreas Bielawski 2016-08-07 20:45:51 +02:00
parent 3740ccc497
commit 8c97cf4637
9 changed files with 37 additions and 63 deletions

View File

@ -92,14 +92,12 @@ Ein Plugin kann zehn Komponenten haben, aber nur zwei werden benötigt:
| `plugin.command` | Einfaches Kommando mit Syntax. Wird bei `/hilfe` gelistet | N | | `plugin.command` | Einfaches Kommando mit Syntax. Wird bei `/hilfe` gelistet | N |
| `plugin.doc` | Plugin-Hilfe. Wird mit `/help $kommando` gelistet | N | | `plugin.doc` | Plugin-Hilfe. Wird mit `/help $kommando` gelistet | N |
| `plugin.error` | Plugin-spezifische Fehlermeldung | N | | `plugin.error` | Plugin-spezifische Fehlermeldung | N |
| `plugin:callback` | Aktion, die ausgeführt wird, nachdem auf einen Callback-Button gedrückt wird. Siehe `gImages.lua` für ein Beispiel. Argumente: `callback` (enthält Callback-Daten), `msg`, `self`, `config`, `input` (enthält Parameter ohne `callback` | N | | `plugin:callback` | Aktion, die ausgeführt wird, nachdem auf einen Callback-Button gedrückt wird. Siehe `gImages.lua` für ein Beispiel. Argumente: `callback` (enthält Callback-Daten), `msg`, `self`, `config`, `input` (enthält Parameter ohne `callback`) | N |
| `plugin:inline_callback` | Aktion, die ausgeführt wird, wenn der Bot per Inline-Query ausgelöst wird. Argumente sind `inline_query` für die Daten, `config` und `matches` | N | | `plugin:inline_callback` | Aktion, die ausgeführt wird, wenn der Bot per Inline-Query ausgelöst wird. Argumente sind `inline_query` für die Daten, `config` und `matches` | N |
Die`bot:on_msg_receive` Funktion fügt einige nützte Variablen zur ` msg` Tabelle hinzu. Diese sind:`msg.from.id_str`, `msg.to.id_str`, `msg.chat.id_str`, `msg.text_lower`, `msg.from.name`. Die`bot:on_msg_receive` Funktion fügt einige nützte Variablen zur ` msg` Tabelle hinzu. Diese sind:`msg.from.id_str`, `msg.to.id_str`, `msg.chat.id_str`, `msg.text_lower`, `msg.from.name`.
Rückgabewerte für `plugin:action` sind optional, aber wenn eine Tabelle zurückgegeben wird, wird diese die neue `msg`,-Tabelle und `on_msg_receive` wird damit fortfahren.
Interaktionen mit der Bot-API sind sehr einfach. Siehe [Bindings](#bindings) für Details. Interaktionen mit der Bot-API sind sehr einfach. Siehe [Bindings](#bindings) für Details.
Einige Funktionen, die oft benötigt werden, sind in `utilites.lua` verfügbar. Einige Funktionen, die oft benötigt werden, sind in `utilites.lua` verfügbar.

View File

@ -26,22 +26,12 @@ function bot:init(config) -- The function run when the bot is started or reloade
self.database = utilities.load_data(self.info.username..'.db') self.database = utilities.load_data(self.info.username..'.db')
end end
-- Table to cache user info (usernames, IDs, etc).
self.database.users = self.database.users or {}
-- Table to store userdata (nicknames, lastfm usernames, etc).
self.database.userdata = self.database.userdata or {}
-- Save the bot's version in the database to make migration simpler.
self.database.version = bot.version
-- Add updated bot info to the user info cache.
self.database.users = self.database.users or {} -- Table to cache userdata.
self.database.users[tostring(self.info.id)] = self.info
self.plugins = {} -- Load plugins. self.plugins = {} -- Load plugins.
enabled_plugins = load_plugins() enabled_plugins = load_plugins()
for k,v in pairs(enabled_plugins) do for k,v in pairs(enabled_plugins) do
local p = require('otouto.plugins.'..v) local p = require('otouto.plugins.'..v)
-- print('loading plugin',v) -- print('loading plugin',v)
table.insert(self.plugins, p) self.plugins[k] = p
self.plugins[k].name = v self.plugins[k].name = v
if p.init then p.init(self, config) end if p.init then p.init(self, config) end
end end
@ -62,18 +52,6 @@ function bot:on_msg_receive(msg, config) -- The fn run whenever a message is rec
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.
-- Cache user info for those involved.
self.database.users[tostring(msg.from.id)] = msg.from
if msg.reply_to_message then
self.database.users[tostring(msg.reply_to_message.from.id)] = msg.reply_to_message.from
elseif msg.forward_from then
self.database.users[tostring(msg.forward_from.id)] = msg.forward_from
elseif msg.new_chat_member then
self.database.users[tostring(msg.new_chat_member.id)] = msg.new_chat_member
elseif msg.left_chat_member then
self.database.users[tostring(msg.left_chat_member.id)] = msg.left_chat_member
end
msg = utilities.enrich_message(msg) msg = utilities.enrich_message(msg)
if msg.reply_to_message then if msg.reply_to_message then
@ -97,7 +75,8 @@ function bot:on_msg_receive(msg, config) -- The fn run whenever a message is rec
msg = service_modify_msg(msg) msg = service_modify_msg(msg)
end end
for _, plugin in ipairs(self.plugins) do for n=1, #self.plugins do
local plugin = self.plugins[n]
match_plugins(self, msg, config, plugin) match_plugins(self, msg, config, plugin)
end end
end end
@ -123,7 +102,8 @@ function bot:on_callback_receive(callback, msg, config) -- whenever a new callba
msg = utilities.enrich_message(msg) msg = utilities.enrich_message(msg)
for _, plugin in ipairs(self.plugins) do for n=1, #self.plugins do
local plugin = self.plugins[n]
if plugin.name == called_plugin then if plugin.name == called_plugin then
if is_plugin_disabled_on_chat(plugin.name, msg) then return end if is_plugin_disabled_on_chat(plugin.name, msg) then return end
plugin:callback(callback, msg, self, config, param) plugin:callback(callback, msg, self, config, param)
@ -144,7 +124,9 @@ function bot:process_inline_query(inline_query, config) -- When an inline query
if inline_query.query:match('"') then if inline_query.query:match('"') then
inline_query.query = inline_query.query:gsub('"', '\\"') inline_query.query = inline_query.query:gsub('"', '\\"')
end end
for _, plugin in ipairs(self.plugins) do
for n=1, #self.plugins do
local plugin = self.plugins[n]
match_inline_plugins(self, inline_query, config, plugin) match_inline_plugins(self, inline_query, config, plugin)
end end
end end
@ -155,7 +137,8 @@ function bot:run(config)
while self.is_started do -- Start a loop while the bot should be running. while self.is_started do -- Start a loop while the bot should be running.
local res = bindings.getUpdates(self, { timeout=20, offset = self.last_update+1 } ) local res = bindings.getUpdates(self, { timeout=20, offset = self.last_update+1 } )
if res then if res then
for _,v in ipairs(res.result) do -- Go through every new message. for n=1, #res.result do -- Go through every new message.
local v = res.result[n]
self.last_update = v.update_id self.last_update = v.update_id
if v.inline_query then if v.inline_query then
bot.process_inline_query(self, v.inline_query, config) bot.process_inline_query(self, v.inline_query, config)
@ -172,7 +155,8 @@ function bot:run(config)
if self.last_cron ~= os.date('%M') then -- Run cron jobs every minute. if self.last_cron ~= os.date('%M') then -- Run cron jobs every minute.
self.last_cron = os.date('%M') self.last_cron = os.date('%M')
utilities.save_data(self.info.username..'.db', self.database) -- Save the database. utilities.save_data(self.info.username..'.db', self.database) -- Save the database.
for i,v in ipairs(self.plugins) do for n=1, #self.plugins do
local v = self.plugins[n]
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 result, err = pcall(function() v.cron(self, config) end) local result, err = pcall(function() v.cron(self, config) end)
if not result then if not result then
@ -194,7 +178,8 @@ end
-- Apply plugin.pre_process function -- Apply plugin.pre_process function
function pre_process_msg(self, msg, config) function pre_process_msg(self, msg, config)
for _,plugin in ipairs(self.plugins) do for n=1, #self.plugins do
local plugin = self.plugins[n]
if plugin.pre_process and msg then if plugin.pre_process and msg then
-- print('Preprocess '..plugin.name) -- remove comment to restore old behaviour -- print('Preprocess '..plugin.name) -- remove comment to restore old behaviour
new_msg = plugin:pre_process(msg, self, config) new_msg = plugin:pre_process(msg, self, config)
@ -204,7 +189,9 @@ function pre_process_msg(self, msg, config)
end end
function match_inline_plugins(self, inline_query, config, plugin) function match_inline_plugins(self, inline_query, config, plugin)
for _, trigger in ipairs(plugin.inline_triggers or {}) do local match_table = plugin.inline_triggers or {}
for n=1, #match_table do
local trigger = plugin.inline_triggers[n]
if string.match(string.lower(inline_query.query), trigger) then if string.match(string.lower(inline_query.query), trigger) then
local success, result = pcall(function() local success, result = pcall(function()
for k, pattern in pairs(plugin.inline_triggers) do for k, pattern in pairs(plugin.inline_triggers) do
@ -224,18 +211,16 @@ function match_inline_plugins(self, inline_query, config, plugin)
end end
function match_plugins(self, msg, config, plugin) function match_plugins(self, msg, config, plugin)
for _, trigger in ipairs(plugin.triggers or {}) do local match_table = plugin.triggers or {}
for n=1, #match_table do
local trigger = plugin.triggers[n]
if string.match(msg.text_lower, trigger) then if string.match(msg.text_lower, trigger) then
-- Check if Plugin is disabled -- Check if Plugin is disabled
if is_plugin_disabled_on_chat(plugin.name, msg) then return end if is_plugin_disabled_on_chat(plugin.name, msg) then return end
local success, result = pcall(function() local success, result = pcall(function()
-- trying to port matches to otouto -- trying to port matches to otouto
for k, pattern in pairs(plugin.triggers) do local pattern = plugin.triggers[n]
matches = match_pattern(pattern, msg.text) local matches = match_pattern(pattern, msg.text)
if matches then
break;
end
end
print(plugin.name..' triggered') print(plugin.name..' triggered')
return plugin.action(self, msg, config, matches) return plugin.action(self, msg, config, matches)
end) end)
@ -251,14 +236,6 @@ function match_plugins(self, msg, config, plugin)
utilities.handle_exception(self, result, msg.from.id .. ': ' .. msg.text, config) utilities.handle_exception(self, result, msg.from.id .. ': ' .. msg.text, config)
return return
end end
-- If the action returns a table, make that table the new msg.
if type(result) == 'table' then
msg = result
-- If the action returns true, continue.
elseif result ~= true then
return
end
end end
end end
end end

View File

@ -128,7 +128,7 @@ end
function gImages:cache_result(results, text) function gImages:cache_result(results, text)
local cache = {} local cache = {}
for v in pairs(results) do for v in pairs(results) do
table.insert(cache, results[v].link) cache[v] = results[v].link
end end
for n, link in pairs(cache) do for n, link in pairs(cache) do
redis:hset('telegram:cache:gImages:'..link, 'mime', results[n].mime) redis:hset('telegram:cache:gImages:'..link, 'mime', results[n].mime)

View File

@ -51,11 +51,11 @@ function help:action(msg, config, matches)
local help_text = '*Verfügbare Befehle:*\n'..config.cmd_pat local help_text = '*Verfügbare Befehle:*\n'..config.cmd_pat
for _,plugin in ipairs(self.plugins) do for _,plugin in ipairs(self.plugins) do
if plugin.command then if plugin.command then
table.insert(commandlist, plugin.command) commandlist[#commandlist+1] = plugin.command
end end
end end
table.insert(commandlist, 'hilfe [Befehl]') commandlist[#commandlist+1] = 'hilfe [Befehl]'
table.sort(commandlist) table.sort(commandlist)
local help_text = help_text .. table.concat(commandlist, '\n'..config.cmd_pat) .. '\nParameter: <benötigt> [optional]' local help_text = help_text .. table.concat(commandlist, '\n'..config.cmd_pat) .. '\nParameter: <benötigt> [optional]'
local help_text = help_text:gsub('%[', '\\[') local help_text = help_text:gsub('%[', '\\[')

View File

@ -89,7 +89,7 @@ function id:action(msg)
for i = 1, #users do for i = 1, #users do
local user_id = users[i] local user_id = users[i]
local user_info = id:get_user(user_id, chat_id) local user_info = id:get_user(user_id, chat_id)
table.insert(users_info, user_info) users_info[#users_info+1] = user_info
end end
-- get all administrators and the creator -- get all administrators and the creator
@ -97,7 +97,7 @@ function id:action(msg)
local admins = {} local admins = {}
for num in pairs(administrators.result) do for num in pairs(administrators.result) do
if administrators.result[num].status ~= 'creator' then if administrators.result[num].status ~= 'creator' then
table.insert(admins, tostring(administrators.result[num].user.id)) admins[#admins+1] = tostring(administrators.result[num].user.id)
else else
creator_id = administrators.result[num].user.id creator_id = administrators.result[num].user.id
end end

View File

@ -10,7 +10,8 @@ post_photo.triggers = {
function post_photo:pre_process(msg, self, config) function post_photo:pre_process(msg, self, config)
if not msg.document then return msg end -- Ignore if not msg.document then return msg end -- Ignore
local mime_type = msg.document.mime_type local mime_type = msg.document.mime_type
if mime_type ~= 'image/jpeg' and mime_type ~= 'image/png' and mime_type ~= 'image/bmp' then return msg end local valid_mimetypes = {['image/jpeg'] = true, ['image/png'] = true, ['image/bmp'] = true}
if not valid_mimetypes[mime_type] then return msg end
local file_id = msg.document.file_id local file_id = msg.document.file_id
local file_size = msg.document.file_size local file_size = msg.document.file_size

View File

@ -104,14 +104,14 @@ function twitter:action(msg, config, matches)
if v.video_info then if v.video_info then
if not v.video_info.variants[3] then if not v.video_info.variants[3] then
local vid = v.video_info.variants[1].url local vid = v.video_info.variants[1].url
table.insert(videos, vid) videos[#videos+1] = vid
else else
local vid = v.video_info.variants[3].url local vid = v.video_info.variants[3].url
table.insert(videos, vid) videos[#videos+1] = vid
end end
end end
text = text:gsub(url, "") text = text:gsub(url, "")
table.insert(images, pic) images[#images+1] = pic
end end
end end

View File

@ -197,8 +197,7 @@ function wikipedia:inline_callback(inline_query, config, matches)
end end
end end
local results = results..']' local results = results..']'
local res, err = utilities.answer_inline_query(self, inline_query, results, 10) utilities.answer_inline_query(self, inline_query, results, 10)
print(results)
end end
function wikipedia:action(msg, config, matches) function wikipedia:action(msg, config, matches)

View File

@ -11,7 +11,6 @@ URL = require('socket.url')
json = require("dkjson") json = require("dkjson")
pcall(json.use_lpeg) pcall(json.use_lpeg)
serpent = require("serpent") serpent = require("serpent")
bindings = require('otouto.bindings')
redis = (loadfile "./otouto/redis.lua")() redis = (loadfile "./otouto/redis.lua")()
mimetype = (loadfile "./otouto/mimetype.lua")() mimetype = (loadfile "./otouto/mimetype.lua")()
OAuth = require "OAuth" OAuth = require "OAuth"
@ -608,7 +607,7 @@ function plugins_names()
for k, v in pairs(scandir("otouto/plugins")) do for k, v in pairs(scandir("otouto/plugins")) do
-- Ends with .lua -- Ends with .lua
if (v:match(".lua$")) then if (v:match(".lua$")) then
table.insert(files, v) files[#files+1] = v
end end
end end
return files return files