plugins/groupchat.lua

1
local st = require "prosody.util.stanza";
2
local jid = require "prosody.util.jid";
3
local xmlns_muc = "http://jabber.org/protocol/muc";
4
 
5
function riddim.plugins.groupchat(bot)
6
	bot.stream:add_plugin("groupchat")
7
	bot.rooms = bot.stream.rooms;
8
 
9
	bot:hook("started", function ()
10
		for k, v in pairs(bot.config.autojoin or {}) do
11
			if type(k) == "number" then
12
				bot:join_room(v);
13
			elseif type(k) == "string" then
14
				if type(v) == "string" then
15
					bot:join_room(k, v);
16
				end
17
			end
18
		end
19
	end);
20
	
21
	-- Re-broadcast groupchat event on the bot
22
	local reflect_events = { "groupchat/joining"; "groupchat/joined"; "groupchat/leaving"; "groupchat/left" };
23
	for i = 1,#reflect_events do
24
		bot.stream:hook(reflect_events[i], function(room, ...)
25
			room.bot = bot;
26
			bot:event(reflect_events[i], room, ...)
27
		end);
28
	end
29
 
30
	function bot:join_room(room_jid, nick, password)
31
		nick = nick or bot.config.nick or ("bot"..math.random(10000,99999));
32
		local room = bot.stream:join_room(room_jid, nick, password)
33
		room.bot = bot;
34
		room:hook("message", function(event)
35
			if event.nick == room.nick then
36
				return true;
37
			end
38
		end, 1000);
39
		room:hook("message", function(event)
40
			local stanza = event.stanza;
41
			local replied;
42
			local r = st.reply(stanza);
43
			if stanza.attr.type == "groupchat" then
44
				r.attr.type = stanza.attr.type;
45
				r.attr.to = jid.bare(stanza.attr.to);
46
			end
47
			function event:reply(reply)
48
				if not reply then reply = "Nothing to say to you"; end
49
				if replied then return false; end
50
				replied = true;
51
				if reply:sub(1,4) ~= "/me " and event.sender and r.attr.type == "groupchat" then
52
					reply = (event.reply_to or event.sender.nick)..": "..reply;
53
				end
54
				room:send(r:tag("body"):text(reply));
55
			end
56
		end, 500);
57
		return room;
58
	end
59
 
60
	bot.stream:hook("pre-groupchat/joining", function(presence)
61
		local muc_x = presence:get_child("x", xmlns_muc);
62
		if muc_x then
63
			muc_x:tag("history",{maxstanzas = "0"});
64
		end
65
	end);
66
end