From d40346b4810e20ad2af849dff938f9904822bdd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Mun=CC=83oz?= Date: Fri, 26 Dec 2014 12:13:27 +0100 Subject: [PATCH] lexical replacements --- bot/bot.lua | 32 +++++++++++++++++++++++++++++--- plugins/get.lua | 29 ++++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 4 deletions(-) diff --git a/bot/bot.lua b/bot/bot.lua index 70f5d8b..0e1e19d 100644 --- a/bot/bot.lua +++ b/bot/bot.lua @@ -42,6 +42,25 @@ function msg_valid(msg) end end +function do_lex(msg, text) + local mutated = true + while mutated do + mutated = false + for name, desc in pairs(plugins) do + if (desc.lex ~= nil) then + result = desc.lex(msg, text) + if (result ~= nil) then + -- print ("Mutating to " .. result) + text = result + mutated = true + end + end + end + end + -- print("Text mutated to " .. text) + return text +end + -- Where magic happens function do_action(msg) local receiver = get_receiver(msg) @@ -52,18 +71,25 @@ function do_action(msg) text = '['..msg.media.type..']' end -- print("Received msg", text) + + text = do_lex(msg, text) + for name, desc in pairs(plugins) do -- print("Trying module", name) for k, pattern in pairs(desc.patterns) do -- print("Trying", text, "against", pattern) matches = { string.match(text, pattern) } if matches[1] then - print(" matches",pattern) + -- print(" matches",pattern) if desc.run ~= nil then result = desc.run(msg, matches) - print(" sending", result) + -- print(" sending", result) if (result) then - _send_msg(receiver, result) + local result2 = do_lex(msg, result) + if (result2 == nil) then + result2 = result + end + _send_msg(receiver, result2) return end end diff --git a/plugins/get.lua b/plugins/get.lua index d9bad27..7f4631a 100644 --- a/plugins/get.lua +++ b/plugins/get.lua @@ -10,6 +10,17 @@ else _values = json:decode(c) end +function fetch_value(chat, value_name) + if (_values[chat] == nil) then + return nil + end + if (value_name == nil ) then + return nil + end + local value = _values[chat][value_name] + return value +end + function get_value(chat, value_name) -- If chat values is empty @@ -40,11 +51,27 @@ function run(msg, matches) return get_value(chat_id, matches[1]) end +function lex(msg, text) + local chat_id = tostring(msg.to.id) + local s, e = text:find("%$%a+") + if (s == nil) then + return nil + end + local var = text:sub(s + 1, e) + local value = fetch_value(chat_id, var) + if (value == nil) then + value = "(unknown value " .. var .. ")" + end + return text:sub(0, s - 1) .. value .. text:sub(e + 1) +end + return { description = "retrieves variables saved with !set", usage = "!get (value_name)", patterns = { "^!get (%a+)$", "^!get$"}, - run = run + run = run, + lex = lex } +