| 1 | function riddim.plugins.commands(bot) |
| 2 | local command_pattern = "^%"..bot.config.command_prefix.."([%a%-%_%d]+)(%s?)(.*)$"; |
| 3 | |
| 4 | local direct_address_pattern = false; |
| 5 | if bot.config.nick then |
| 6 | direct_address_pattern = "^"..bot.config.nick.."[,: ]+([%a%-%_%d]+)(%s?)(.*)"; |
| 7 | end |
| 8 | |
| 9 | local function process_command(event) |
| 10 | local body = event.body; |
| 11 | if not body then return; end |
| 12 | if event.delay then return; end -- Don't process old messages from groupchat |
| 13 | |
| 14 | local command, hasparam, param = body:match(command_pattern); |
| 15 | |
| 16 | if not command and direct_address_pattern then |
| 17 | command, hasparam, param = body:match(direct_address_pattern); |
| 18 | end |
| 19 | |
| 20 | if not command then |
| 21 | command, hasparam, param = body:match("%[([%a%-%_%d]+)(%s?)(.*)%]"); |
| 22 | if event.room then |
| 23 | local direct_to = body:match"^(.-)[,:]" |
| 24 | if event.room.occupants[direct_to] then |
| 25 | event.reply_to = direct_to |
| 26 | end |
| 27 | end |
| 28 | end |
| 29 | |
| 30 | if hasparam ~= " " then param = nil; end |
| 31 | |
| 32 | if command then |
| 33 | local command_event = { |
| 34 | command = command, |
| 35 | param = param, |
| 36 | sender = event.sender, |
| 37 | stanza = event.stanza, |
| 38 | reply = event.reply, |
| 39 | room = event.room, -- groupchat support |
| 40 | }; |
| 41 | local ret = bot:event("commands/"..command, command_event); |
| 42 | if ret == nil then |
| 43 | ret = bot:event("unhandled-command", command_event); |
| 44 | end |
| 45 | if type(ret) == "string" then |
| 46 | event:reply(ret); |
| 47 | end |
| 48 | return ret; |
| 49 | end |
| 50 | end |
| 51 | |
| 52 | -- Hook messages sent to bot, fire a command event on the bot |
| 53 | bot:hook("message", process_command); |
| 54 | |
| 55 | -- Support groupchat plugin: Hook messages from rooms that the bot joins |
| 56 | bot:hook("groupchat/joining", function (room) |
| 57 | room:hook("message", process_command); |
| 58 | end); |
| 59 | end |