Skip to content

Instantly share code, notes, and snippets.

@jschairb
Created October 28, 2016 14:18
Show Gist options
  • Save jschairb/5bf1f346de6f8b9a91fe5920bc5f1592 to your computer and use it in GitHub Desktop.
Save jschairb/5bf1f346de6f8b9a91fe5920bc5f1592 to your computer and use it in GitHub Desktop.
'use strict'
// Slack's Realtime Messaging Client
const RtmClient = require('@slack/client').RtmClient;
const MemoryDataStore = require('@slack/client').MemoryDataStore;
// Slack's event name constants
const RTM_EVENTS = require('@slack/client').RTM_EVENTS;
const CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;
class Bot {
constructor(opts) {
let slackToken = opts.token;
let autoReconnect = opts.autoReconnect || true;
let autoMark = opts.autoMark || true;
// Construct the Slack client
this.slack = new RtmClient(slackToken, {
logLevel: 'error',
dataStore: new MemoryDataStore(),
autoReconnect: autoReconnect,
autoMark: autoMark
});
this.keywords = new Map();
this.slack.on(RTM_EVENTS.MESSAGE, (message) => {
// Only process text messages
if (!message.text) {
return;
}
let channel = this.slack.dataStore.getChannelGroupOrDMById(message.channel);
let user = this.slack.dataStore.getUserById(message.user);
// Test each keyword's regex and set callback for each match
for (let regex of this.keywords.keys()) {
if (regex.test(message.text)) {
let callback = this.keywords.get(regex);
callback(message, channel, user);
}
}
}
}
respondTo(keywords, callback, start) {
if (start) {
keywords = '^' + keywords;
}
let regex = new RegExp(keywords, 'i');
this.keywords.set(regex, callback);
}
send(message, channel, callback) {
this.slack.sendMessage(message, channel.id, () => {
if (callback) {
callback();
}
});
}
}
module.exports = Bot;
'use strict'
let Bot = require('./bot');
const Bot = new Bot({
token: process.env.SLACK_TOKEN,
autoReconnect: true,
autoMark: true
});
bot.respondTo('hello', (message, channel, user) => {
bot.send(`Kon\'nichiwa, ${user.name}!`, channel)
}, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment