To generate a Slack API token, you'll need to run do the following:
- Create a new Slack App
- Add permissions
- Copy the token URL
Create a new Slack App
To start, you'll need to create a Slack App. Follow the link, and click Create New App. The process is fairly self-explanatory.
In the menu on the left, find OAuth and Permissions. Click it, and scroll down to the Scopes section. Click Add an OAuth Scope.
Search for the chat:write scope, and add it. At this point, you'll need to re-install the app in your workspace for the permissions to take effect.
Copy the token URL
On the same page you'll find your access token under the label Bot User OAuth Access Token. Copy this token, and save it for later.
In the Slack application, choose a channel that you want the bot to interact with. Click the Conversation Settings icon (the cog), and then click Add an app.
Search for your app name, then click Add.
At this point, we have everything we need to send a message. Below is a simple example to get you started:
import slack client = slack.WebClient(token='xxxyourtokenxxx') client.chat_postMessage(channel='general', text='This is only a test.')
You've heard it elsewhere, and I'm going to say it here as well. You shouldn't store the slack token in your codebase. So even if you hardcode the token at first, don't commit.
An acceptable solution is to set the token as an environment variable on your server or container. So in your Dockerfile or startup script, you could set the environment variable:
Then in Python:
import os slack_token = os.environ.get('SLACK_TOKEN')
An even better option is to use a secrets manager. We use Kubernetes to manage our application, so we utilize Kubernetes Secrets. If you go this route, you'll have to use whatever solution fits your use case. I don't have many recommendations besides Vault.