Adam Oudad

Adam Oudad

(Machine) Learning log.

2 minutes read

In this article we'll see how to code your simple bot for Slack, and schedule it to run regularily. As some testing might be necessary, I recommend to create a dummy Slack workspace for this tutorial.

Add a webhook for your Slack workspace

We first need to configure a web hook to communicate to our Slack workspace. Go to this url, choose your channel and click on add a webhook. In this tutorial, I choose to post to the #random channel. The rest of the configuration can be left as is, so you can save it.

Copy your web hook url which should have the form https://hooks.slack.com/services/SOME_GIBBERISH_CODE.

Run the bot locally

Let's test locally the connection to the webhook we just created. We'll use python library slackweb. The code is straightforward. We'll put this in slackbot.py.

#!/bin/python3
#-*- encoding: utf-8 -*-
import slackweb
HOOK_URL='https://hooks.slack.com/services/SOME_GIBBERISH_CODE.'
slack = slackweb.Slack(url=HOOK_URL)
slack.notify(text="Hello world!")

Replace the content of HOOK_URL by your hook url copied from the previous step. Then run the code and check if it works; you should see in #random a message from your program. The first line of the above code specifies the location of the python interpreter to run, and the second line should be used if the file contains unicode characters, such as japanese kanji or french é, à, etc.

Schedule the program

You could decide to schedule the program to run on your own computer, but if you want it to run even when your computer is shut down, we need a web server. PythonAnywhere offers free server space and python environment for development purpose. So let's create an account and head to our PythonAnywhere dashboard.

Go to the Files tab and upload your file slackbot.py to your directory /home/your_username/.
Then, let's install the dependancy. Open a bash terminal and run pip3 install --user slackweb.
Inside the same terminal, we can check that everything works. Run python3 slackbot.py, and see if the message appears again in #random channel.

Scheduling is done in the Task tab. Create your task by specifying a frequency and the command to run: /home/adamoudad/slackbot.py. You can see the expiry date of your task when you created it, which is probably roughly one month. For the free plan, PythonAnywhere requests you to log at least once a month for your scheduled tasks to remain valid.

Conclusion

That's it! you have your Slack bot up and running on the web. And it will haunt your Slack workspace until the end of times… cordially.

comments powered by Disqus

Recent posts

See more

Categories

About

This website is a weblog were I write about computer science, machine learning, language learning.