UNPKG

2.6 kBJavaScriptView Raw
1import superscript from 'superscript';
2// slack-client provides auth and sugar around dealing with the RealTime API.
3import Slack from 'slack-client';
4
5// Auth Token - You can generate your token from
6// https://<slack_name>.slack.com/services/new/bot
7const token = '...';
8
9// How should we reply to the user?
10// direct - sents a DM
11// atReply - sents a channel message with @username
12// public sends a channel reply with no username
13const replyType = 'atReply';
14
15const atReplyRE = /<@(.*?)>/;
16
17const slack = new Slack(token, true, true);
18
19const receiveData = function receiveData(slack, bot, data) {
20 // Fetch the user who sent the message;
21 const user = data._client.users[data.user];
22 let channel;
23 const messageData = data.toJSON();
24 let message = '';
25
26 if (messageData && messageData.text) {
27 message = `${messageData.text.trim()}`;
28 }
29
30 const match = message.match(atReplyRE);
31
32 // Are they talking to us?
33 if (match && match[1] === slack.self.id) {
34 message = message.replace(atReplyRE, '').trim();
35 if (message[0] === ':') {
36 message = message.substring(1).trim();
37 }
38
39 bot.reply(user.name, message, (err, reply) => {
40 // We reply back direcly to the user
41 switch (replyType) {
42 case 'direct':
43 channel = slack.getChannelGroupOrDMByName(user.name);
44 break;
45 case 'atReply':
46 reply.string = `@${user.name} ${reply.string}`;
47 channel = slack.getChannelGroupOrDMByID(messageData.channel);
48 break;
49 case 'public':
50 channel = slack.getChannelGroupOrDMByID(messageData.channel);
51 break;
52 }
53
54 if (reply.string) {
55 channel.send(reply.string);
56 }
57 });
58 } else if (messageData.channel[0] === 'D') {
59 bot.reply(user.name, message, (err, reply) => {
60 channel = slack.getChannelGroupOrDMByName(user.name);
61 if (reply.string) {
62 channel.send(reply.string);
63 }
64 });
65 } else {
66 console.log('Ignoring...', messageData);
67 }
68};
69
70const botHandle = function botHandle(err, bot) {
71 slack.login();
72
73 slack.on('error', (error) => {
74 console.error(`Error: ${error}`);
75 });
76
77 slack.on('open', () => {
78 console.log('Welcome to Slack. You are %s of %s', slack.self.name, slack.team.name);
79 });
80
81 slack.on('close', () => {
82 console.warn('Disconnected');
83 });
84
85 slack.on('message', (data) => {
86 receiveData(slack, bot, data);
87 });
88};
89
90// Main entry point
91const options = {
92 factSystem: {
93 clean: true,
94 },
95 importFile: './data.json',
96};
97
98superscript.setup(options, (err, bot) => {
99 botHandle(null, bot);
100});