lua_xmpp_sed_bot/main.lua
2024-06-24 17:00:30 -05:00

80 lines
3 KiB
Lua
Executable file

-- Get the verse lib
verse = require("verse")
-- Get pcre2 lib
re = require("rex_pcre2")
-- Setup logging and config
require("utils")
local log = setup_log(string.format("%s_main", config.name))
log("info", "Log initialized")
-- Get the client lib
local client_lib = verse.init("client")
-- Make the client
local client = client_lib.new()
-- Load client plugins
client:add_plugin("groupchat")
client:add_plugin("version")
-- Client hooks
client:hook("disconnected", function()
log("error", "XMPP connetion lost. Quitting...")
os.exit(1)
end)
client:hook("authentication-failure", function()
log("error", "Failed to authenticate with XMPP Server. Quitting...")
os.exit(1)
end)
client:hook("authentication-success", function()
log("info", "XMPP authentication sucessful!")
end)
client:hook("ready", function()
log("info", "Client ready")
-- Main code goes here
for _, room in pairs(config.rooms_to_join) do
local room, err = client:join_room(room.jid, config.name, {}, config.password)
if room then
-- Run on message events
room:hook("message", function(event)
if event.stanza.attr.type == "groupchat"
and not string.find(event.stanza.attr.from, "/" .. config.name)
and not event.stanza:get_child("delay", "urn:xmpp:delay") then
local body = event.stanza:get_child_text("body")
if body then
-- Try to get pairs of sed patterns and quotes
for text, pattern, replacement, flags in re.gmatch(body, sed_expresion_regex, "gx") do
-- Remove block quote markets
text = re.gsub(text, "^>", "", nil, "m")
-- Get compilation flags
local compilation_flags = string.gsub(flags, "[^imsxU]", "")
-- u flag?
local n = nil
if not string.find(flags, "g") then
n = 1
end
-- Run the expression and send result
local result, new_text = pcall(re.gsub, text, pattern, replacement, n, compilation_flags)
if result then
if new_text then
send_sed_output(room, new_text, event)
end
else
send_sed_output(room, string.format("PCRE2 Error: %s", new_text), event)
end
end
end
end
end)
log("info", "Joined room \"%s\"", room.jid)
else
log("error", "Error joining room \"%s\": %s", room.jid, err)
end
end
end)
log("info", "Connecting to server...")
client:connect_client(config.jid, config.password)
verse.loop()
log("info", "Verse loop exited. Quitting...")