-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (72 loc) · 1.88 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const url = require('url');
const querystring = require('querystring');
const { log, logLevel } = require("./logger");
const { WebClient, RTMClient } = require('@slack/client');
const HttpsProxyAgent = require('https-proxy-agent');
const _ = require('lodash');
const { getYouTrackIssue, linkRE } = require('./youtrack');
const formatMessage = require('./formatMessage');
const { proxyUrl, SLACK_BOT_TOKEN } = require("./config.js");
const logger = log.getLogger("bot");
logger.setLevel(logLevel);
// Web API connector
const slackWeb = new WebClient(SLACK_BOT_TOKEN);
// RTM API connector
const rtmOptions = {
logLevel
};
if (proxyUrl) {
rtmOptions.agent = new HttpsProxyAgent(proxyUrl);
}
const rtm = new RTMClient(SLACK_BOT_TOKEN, rtmOptions);
rtm.start();
rtm.on('message', (event) => {
if (event.subtype) {
return;
}
let links = parseLinks(event.text);
if (links.length) {
Promise.all(links.map(getMessageForLink))
.then(messages => {
messages
.filter(message => !!message)
.forEach(message => sendMessage(message, event));
})
.catch(logger.error);
}
});
function parseLinks(text) {
let links = text.match(linkRE);
return _(links)
.map(link => link.substr(1, link.length - 2))
.uniq()
.valueOf();
}
function getMessageForLink(linkUrl) {
const {id, commentId} = parseLinkIds(linkUrl);
return getYouTrackIssue(id)
.then(data => {
if (data) {
return formatMessage(id, commentId, data);
}
});
}
function parseLinkIds(linkUrl) {
const parsed = url.parse(linkUrl);
const id = _.last(parsed.pathname.split('/'));
const commentId = parsed.hash
? querystring.parse(parsed.hash)['#comment']
: null;
return {id, commentId};
}
function sendMessage({url, text}, event) {
const body = {
text,
channel: event.channel
};
if (event.thread_ts) {
body.thread_ts = event.thread_ts;
}
logger.info('send info for', url);
slackWeb.chat.postMessage(body);
}