plugins/issues.lua

1
-- Plugin for querying issue-tracker
2
--
3
-- Example config:
4
-- issues = {
5
--   ["project@conference.example.org"] = "http://example.org/issues/";
6
-- }
7
 
8
local url = require"socket.url";
9
local json = require"prosody.util.json";
10
local http = require"prosody.net.http";
11
 
12
function riddim.plugins.issues(bot)
13
	local conf = bot.config.issues;
14
 
15
	local ex = {
16
		headers = {
17
			Accept = "application/json";
18
		};
19
	};
20
 
21
	local function get_issue_url(base, id)
22
		local base_url = url.parse(base or "http://localhost:8006/");
23
		local base_path = url.parse_path(base_url.path);
24
		base_path[#base_path+1] = "issue";
25
		base_path[#base_path+1] = id;
26
		base_path.is_directory = nil;
27
		base_url.path = url.build_path(base_path);
28
		return url.build(base_url);
29
	end
30
 
31
	bot:hook("commands/issue", function (command)
32
		local issue_id = tonumber(command.param);
33
		if not issue_id then return; end
34
		local current_conf = conf[command.room and command.room.jid or "default"];
35
		if not current_conf then return end
36
		local issue_url = get_issue_url(current_conf, issue_id);
37
		http.request(issue_url, ex, function (data, code)
38
			if code > 400 then
39
				return command:reply("HTTP Error "..code.." :(");
40
			end
41
			data = data and json.decode(data);
42
			if not data then
43
				return command:reply("Got invalid JSON back :(");
44
			end
45
			local issue = data.issue;
46
			local tags = {};
47
			for tag in pairs(issue.tags) do
48
				table.insert(tags, tag);
49
			end
50
			command:reply(("Issue #%d %q {%s}\n%s"):format(issue.id, issue.title, table.concat(tags, ", "), issue_url));
51
		end);
52
		return true;
53
	end);
54
 
55
	local function check_for_issue_id(message)
56
		local issue_id = message.body and message.body:match"^#(%d+)" or message.body:match"%s#(%d+)";
57
		if issue_id then
58
			return bot:event("commands/issue", { param = issue_id, reply = message.reply, room = message.room });
59
		end
60
	end
61
 
62
	bot:hook("groupchat/joining", function (room)
63
		room:hook("message", check_for_issue_id);
64
	end);
65
end