This repository has been archived by the owner on Feb 16, 2021. It is now read-only.
forked from FreeCodeCampOKC/twitch_slack_bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SlackBot.js
85 lines (69 loc) · 2.8 KB
/
SlackBot.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 Bot = require('slackbots');
class SlackBot {
constructor(settings, relay) {
this.slackBotSettings = {
token: settings.slackKey,
name: settings.slackName
};
this.channel = settings.slackChannel;
this.bot = new Bot(this.slackBotSettings);
this.relay = relay;
this.relay.createBot(this.bot, 'slack');
}
// Setup Slackbot actions
setup() {
let slackBot = this.bot;
let botIds = [];
let channelId;
slackBot.on('start', () => {
console.log('SlackBot started!');
// Get a list of all the bot ids in Slack.
// TODO: make this configurable?
botIds = slackBot.users
.filter(user => user.name === slackBot.name || user.name === 'slackbot')
.map(bot => bot.id);
console.log('bot ids:', botIds);
// Get the channel id for the channel we're watching on Slack.
channelId = slackBot.channels
.filter(channel => channel.name === this.channel)[0].id;
});
slackBot.on('message', (message) => {
// If the incoming message is from the channel we're watching, is of type "message",
// has text and doesn't belong to one of the bot users...
if (message.channel == channelId &&
message.type === 'message' &&
message.user &&
message.text && botIds.indexOf(message.user) === -1) {
function getUserNameByID(id)
{
return slackBot.users.filter(user => user.id === id)[0].name;
}
function replaceUserNames(messageText)
{
var tagsRegex = /<@\w{9}>/g;
var idRegex = /\w{9}/;
var tags = messageText.match(tagsRegex);
if(tags){
for (var i = 0; i < tags.length; i++)
{
var tag = tags[i];
var id = tag.match(idRegex)[0];
var username = getUserNameByID(id);
if (username)
{
messageText = messageText.replace(tag, '@' + username);
}
}
}
return messageText;
}
// Get the user name from the user id.
let user = getUserNameByID(message.user);
let messageText = replaceUserNames(message.text);
// Inform Relay of the message to send to Twitch.
this.relay.sendMessage(user, messageText, 'twitch');
}
});
}
}
module.exports = SlackBot;