Building a Slack bot in Node
I was looking into how to build a simple Slack bot. I ran across various bot kits and frameworks and whatnot, that seemed to really overcomplicate the issue. Went back to the Slack API and discovered that it's actually quite straightforward.
This particular code listens for messages in a private channel called 'dev'. Private channels are called 'Groups' in the Slack API.
The bot listens for messages, looks fo the text 'ping' and responds 'pong'. Â The rest is up to you!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { RTMClient, WebClient } = require('@slack/client'); | |
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS; | |
const token = 'xoxb-token-here'; | |
async function runBot() { | |
const rtm = new RTMClient(token); | |
const web = new WebClient(token); | |
const r = await rtm.start(); | |
console.log("Connected", r); | |
const lookupResponse = await web.users.lookupByEmail({email: 'steve@example.com'}); | |
const user = lookupResponse.user; | |
console.log("Got user", user); | |
const groups = await web.groups.list(); | |
console.log("Found Groups", groups); | |
const devGroup = groups.groups.find((g)=>(g.name === 'dev')); | |
async function handleMessage(message) { | |
console.log("on.message", message); | |
if (message.text === 'ping') { | |
rtm.sendMessage('pong', devGroup.id); | |
} | |
} | |
rtm.on('message', (message)=>{ | |
handleMessage(message); | |
}); | |
} |