-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.js
More file actions
90 lines (72 loc) · 2.45 KB
/
bot.js
File metadata and controls
90 lines (72 loc) · 2.45 KB
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
86
87
88
89
"use strict";
const CLIENT = require('@slack/client'),
RtmClient = CLIENT.RtmClient,
MemoryDataStore = CLIENT.MemoryDataStore,
CLIENT_EVENTS = CLIENT.CLIENT_EVENTS,
RTM_EVENTS = CLIENT.RTM_EVENTS;
class Bot {
constructor(opts) {
this.slack = new RtmClient(opts.token, {
logLevel: 'error',
dataStore: new MemoryDataStore(),
autoReconnect: opts.autoReconnect || true,
autoMark: opts.autoMark || true
});
this.keywords = new Map();
this.slack.on(CLIENT_EVENTS.RTM.RTM_CONNECTION_OPENED, () => {
let dataStore = this.slack.dataStore,
user = dataStore.getUserById(this.slack.activeUserId),
team = dataStore.getTeamById(this.slack.activeTeamId);
this.name = user.name;
console.log(`Connected to ${team.name} as ${user.name}`);
});
this.slack.on(RTM_EVENTS.MESSAGE, (message) => {
if (!message.text) {
return;
}
let dataStore = this.slack.dataStore,
channel = dataStore.getChannelGroupOrDMById(message.channel),
user = dataStore.getUserById(message.user);
for (let regex of this.keywords.keys()) {
let match = message.text.match(regex);
if (match) {
let callback = this.keywords.get(regex);
match.shift();
callback(message, channel, user, ...match);
}
}
});
this.slack.start();
}
respondTo(keyword_regex, callback) {
this.keywords.set(keyword_regex, callback);
}
send(message, channel, cb) {
this.slack.sendMessage(message, channel.id, () => cb && cb());
}
sendDirect(message, user, cb) {
if (user && user.is_bot) {
return;
}
let dm = this.slack.dataStore.getDMByName(user.name);
this.slack.sendMessage(message, dm.id, () => cb && cb());
}
getChannel(name) {
return this.slack.dataStore.getChannelByName(name);
}
getUser(userInfo) {
let ds = this.slack.dataStore;
return ds.getUserByName(userInfo) || ds.getUserByEmail(userInfo);
}
getUserById(user) {
return this.slack.dataStore.getUserBuId(user);
}
debug(propPath, channel) {
this.send("Debugging...", channel);
let val = propPath ? propPath.split(".").reduce((obj, prop) => (obj || {})[prop], this.slack)
: this.slack;
this.send("Keys: " + Object.keys(val || {}), channel);
this.send("Value: " + val, channel);
}
}
module.exports = Bot;