Slack

Slack

How to Build a Slack Bot With Napkin

For this example, we'll be making a Pokemon slack bot using the awesome PokeAPI. Our bot will be very simple: when a user enters the command "/pokebot" in Slack, the bot will show them a random Pokemon encounter.

image

Start by creating a new Napkin function called pokebot .

image

Next, we'll code our bot in the Napkin editor. You can paste the code below or feel free to change it how you like.

from napkin import response
import requests
import random

# src: https://bulbapedia.bulbagarden.net/wiki/Wild_Pok%C3%A9mon#Encounter_messages
phrases = [
    "The hooked {pokemon} attacked!",
    "The hooked {pokemon} attacked!",
    "{pokemon} fell out of the tree!",
    "Oh!, {pokemon} appeared!",
    "A wild {pokemon} and {pokemon} appeared!",
    "Whoa!, A wild {pokemon} came charging!",
    "A wild {pokemon} appeared from the tree you slathered with Honey!",
    "The Distortion World's {pokemon} appeared!",
    "Oh!, A wild {pokemon} and {pokemon} appeared!",
    "{pokemon} appeared!",
    "A wild {pokemon} appeared?!",
    "Whoa!, The {pokemon} you stepped on attacked!",
    "Whoa!, A wild {pokemon} swooped down from above!",
    "Whoa!, A wild {pokemon} dived out of the sky!",
    "Whoa!, A wild {pokemon} leaped out of the trash can!",
    "Whoa!, A wild {pokemon} leaped out of the tall grass!",
    "Oh!, A wild {pokemon} appeared!",
    "Oh!, A wild {pokemon} appeared!",
    "Whoa!, A horde of {pokemon} appeared!",
    "You are challenged by Totem {pokemon}!",
    "{pokemon} appeared!",
    "You encountered a very strong-looking {pokemon}!"
]

URL = "https://pokeapi.co/api/v2/pokemon/{}"

pokelimit = 100

random_idx = random.randrange(pokelimit) + 1

res = requests.get(URL.format(random_idx))
data = res.json()

pokemon_name = data['species']['name'].capitalize()

random_phrase = random.choice(phrases)

response.body={
    "encounter": random_phrase.format(pokemon=pokemon_name)
}

When you're happy with your code, click "Deploy" to deploy it as a live API endpoint.

image

Our Slack bot server is all set. You can test out your endpoint by opening your napkin endpoint url in another browser window.

Now we just have to register it in the Slack console in order to start using it in Slack. To do this, head to https://api.slack.com/apps?new_app=1 and create a new Slack app.

image

On the next page, choose "Slash Commands", and then click "Create New Command".

Fill out the "Create New Command" form with your Napkin function's URL.

image

The last step is to add the Slack app to your Slack workspace. Navigate back to the main page for the Pokebot Slack app. Then click "Install to Workspace"

image

✅ Done!

Once that's done, head over to your Slack app, add the bot to a channel, and try it out!