A Slackbot is configured on the UI (there might be a way to do so programmatically, though not sure if there’s a need for it).
From there, one will obtain API keys for it (SLACK_API_TOKEN
).
There are three ways to set up a Slack bot in Python. Slack has three Python SDKs, each in increasing levels of declarativeness:
SlackClient
that provides more low-level control, and has access to some deprecated APIs/protocolsWebClient
is more high-levelBolt
, a framework built on top ofWebClient
that makes big use of dependency injection to simplify things
Code Snippets (WebClient
)
Listen for a Slack command
- Create a local webserver using something like Flask with a POST endpoint.
- Enable ngrok to expose the local webserver to the public
- Ensure that the
ngrok
instance is validated with a personal token - Spin up the server with
ngrok http <your-localhost-port-#>
- Ensure that the
- Run the local web application:
python app.py
Code Snippets (Bolt)
In the code above, we use socket_mode
. This allows the application to communicate with the Slack instance without going through the HTTP protocol. This is helpful for an internal application or for applications/instances that sit behind a firewall.
Note
I’m not quite sure if
socket_mode
will still be used in production or not.
Another thing worth noting is that there are a few kinds of tokens available when building a slack bot:
Token | Description |
---|---|
User token | |
Bot token | Used when creating the Bolt app or the WebClient . |
Application token | Used when creating the SocketModeHandler |
Permissionning
You need to enable some settings on the Slack application (api.slack.com) page otherwise events won’t be forwarded to your Bolt application.
- Go to “Event Subscription” on the left pane
- Enable “Enable Events”
- Scroll to “Subscribe to bot events”
- Add the required event listeners. The appropriate OAuth scopes will be granted.
- For example,
app_mention
if you need to listen for an app, ormessage.channel
to listen to messages in a channel
- For example,
How to change the Slack bot’s display name?
- On Slack, click on the info of a Slack application (like on the name from the group chat).
- Once a modal pops up, click on “Configuration”. This redirects you to the application’s Slack webpage on your browser
- On the Slack application’s webpage, scroll to the bottom and you can then edit the name