This is a basic example of how to build a slack bot using the events API.
- Reply to the message 'BOT TEST' when it is posted to a slack channel with the bots handle mentioned.
- slackbot_events_api_example.py: Source code for the slack bot.
- configs.json: Configuration file.
In order for this slack bot to work it will need a few keys to authenticate to slack, the contents of the config file as well as what they are can be found below.
{
"slack_bot_token":"",
"slack_signing_secret":""
}
- slack_bot_token: This is the token of the bot user configured in slack
- slack_signing_secret: This is the signing secret that the bot will use to authenticate to the channel sent by the events subscription.
In order to run this bot locally you are first going to need a tunneling software set up and configured. When you post a message in slack, the slack event handler will send a message to your server. As you will be running this locally you will need a way to forward that request to your local host. For this example I have used ngrok.
At a high level, the steps you will need to take to get this set up are listed below. If you want a more comprehensive walk through, please check out the youtube link below.
- Create an application in slack
- Add a bot user to the slack application
- Enable OAuth for the bot user
- Grant the bot user chat:write:bot scope
- Enable event subscriptions
- Grant the subscribe to bot events the message.channels scope
- Copy the slack bot token and the slack signing secret to the configs.json file
- In terminal session a, launch ngrok
./ngrok http 3000
- In terminal session b, launch the slack bot
pip3 install -r requirements.txt python3 slackbot_events_api_example.py
- Now you should be able to go to the slack app, invite the bot and then send a message
/invite @slackbot_events_api_example @slackbot_events_api_example BOT TEST
- If everything went to play the bot should respond with the following
Responding to `BOT TEST` message sent by user @yourUserName