How to build a SlackBot

Alex Stroulger
Sep 23, 2017 · 7 min read

Part 1: Project Setup

My first Slackbot accidentally posting in my team’s #general channel
mkdir jokes-bot
cd jokes-bot
git init

Part 2: Getting our bot to talk

const envKey = process.env.JOKES_BOT_TOKEN
var bot = new SlackBot({
token: envKey,
name: “Jokes Bot”
})

Part 3: Getting our bot to tell us jokes

Step 1: Talking to the bot directly

bot.on("message", msg => {
switch (msg.type) {
case "message":
if (msg.channel[0] === "D" && msg.bot_id === undefined) {
bot.postMessage(msg.user, "hi", { as_user: true })
}
break
}
})

Step 2: Connecting to the API

const getRandomJoke = (callback, user) => {
return request("https://icanhazdadjoke.com/slack", (error, response) => {
if (error) {
console.log("Error: ", error)
} else {
let jokeJSON = JSON.parse(response.body)
let joke = jokeJSON.attachments[0].text
return callback(joke, user)
}
})
}
{ attachments:
[ { fallback: 'Did you hear about the guy whose whole left side was cut off? He\'s all right now.',
footer: '<https://icanhazdadjoke.com/j/08EQZ8EQukb|permalink> - <https://icanhazdadjoke.com|icanhazdadjoke.com>',
text: 'Did you hear about the guy whose whole left side was cut off? He\'s all right now.' } ],
response_type: 'in_channel',
username: 'icanhazdadjoke'
}
const postMessage = (message, user) => {
bot.postMessage(user, message, { as_user: true })
}

Part 4: Deploying our bot with Heroku

Part 1: Creating a new app in Heroku

Step 2: Sharing config variables with Heroku

Step 3: Adding a Procfile

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade