slackbots

diary of a codelovingyogi
2 min readMay 6, 2020

slack has changed the way you create bots for posting or receiving messages in your channels.

to add a bot, you have to create an app.

login into your slack, go here to add an app: https://api.slack.com/apps

you will have to make selections in Add features and functionality before you can save the app and Install your app to your workspace

once you install the app to your workspace, you will get a Bot User OAuth Access Token . this is found in the Install App or OAuth & Permissions sections.

In OAuth & Permissions you also need to identify the scope before you can start using the Python client to post messages:

install the python client (requires python3)

pip install slackclient

as indicated in docs, here is quick start code to start posting messages to your slack channel:

from slack import WebClient
from slack.errors import SlackApiError
SLACK_BOT_TOKEN = <token as retrieved above>
SLACK_CHANNEL = <sign into slack web to easily retrieve>
client = WebClient(token=SLACK_BOT_TOKEN)try:
response = client.chat_postMessage(
channel=SLACK_CHANNEL,
text="Hello world!")
assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
# You will get a SlackApiError if "ok" is False
assert e.response["ok"] is False
assert e.response["error"] # str like 'invalid_auth', 'channel_not_found'
print(f"Got an error: {e.response['error']}")

when you install the app, slack will ask you to choose a channel for your bot to post to. your bot name is now the App display name, it is found in App Home :

to get your channel id, navigate to your slack workspace web version, and click on the channel. the url indicates your workspace id and the channel id.

i was not able to get slackclient working in juypter notebooks. running it will give an error:

RuntimeError: This event loop is already running

--

--