-
Notifications
You must be signed in to change notification settings - Fork 3
Slack Bot Setup
Author: Felix Nützel
Author: Erben Emanuel
Date: 19.05.2023
At the Slack Api Website Click on 'Create New App' and select 'From scratch'. There you enter the Name of the App. In our case: 'QA Chat'. Then you need to select the workspace where the Slack Bot should be deployed to.
After this, the Slack Bot is created and needs to be configured. For that go to the settings page of your created app. In our case, this is QAChat Settings. Here we can find the App Credentials and already some Tokens and Secrets one would need, to use a WebSocket to communicate with the Slack Bot. There we can also change the Display Information, which get shown as a description of the Slack Bot, when a user wants to add the app to his Slack. On this page, we also need to create an App-Level Token with the scope: 'connections:write'. After entering a name and saving it, you get displayed a token, that you also need for communication with the bot. You can also review this token when clicking on the name of the created token.
Now one can add features and functionality. Therefore click on the designated button at the top of the page.
Here we then have to first make settings to the 'Event Subscription' page. There enable Events by clicking on the switch to the show 'on' Then we need to specify the events, the bot will subscribe to. Here add the three events you can see in the following image:
Now click on 'Save Changes'.
On this page, you can also enter a Request URL, where the bot has its endpoint to call your program. But we will use Socket Mode. With this. we won't need to specify it and the program will establish the connection to the app. For this click on 'Socket Mode' in the Left Side Menu.
.
On the page switch the toggle for enabling Socket Mode. This is all you need to do for an Event Subscription.
Next to the submenu 'Bots'. There are two main things we will edit here, the first is under the App's Presence header we will enable 'Always Show My Bot as Online'. This is mainly a cosmetic thing but nice for the user. The second thing is under the 'Show Tabs' header Check the box 'Allow users to send Slash commands and messages from the messages tab'.
The last tab we will check is 'Permissions' which will lead us to 'OAuth & Permissions'. Under the header Scopes add the following scopes:
This list can be reduced or extended by whatever your bot needs.
When you are finished with all of the above, you can now Install the app to the Workspace. With this, the bot gets available to everyone in your Workspace and you will create the last token, that you need to communicate from the Python script. This process can/must be repeated when you change the settings of your bot or when you need to regenerate the token ;-).
When you have done this, head to your Slack Workspace and click on 'Apps hinzufügen'/'Add app':
There either search or select the created app from the list. After this, your bot should appear in the left list under Apps and you should now be able to send messages to the bot.
For the slackbot to work to work you need the webclient, the sockethandler and the bolt application. They are imported as follows:
from slack_sdk import WebClient
from slack_bolt.adapter.socket_mode import SocketModeHandler
from slack_bolt import App
They need to be initialized with their respective tokens:
self.app = App(token=SLACK_TOKEN)
self.client = client or WebClient(token=SLACK_TOKEN)
self.handler = SocketModeHandler(self.app, SLACK_APP_TOKEN)
The SLACK_TOKEN can be found in the Settings > Install App tab and is called "Bot User OAuth Token". Meanwhile, the SLACK_APP_TOKEN can be found in the Settings > Basic Information tab after scrolling a bit down. In our case, it is called "qa-token".
Events such as actions commands or messages are handled by our initialized handler object / our Bolt app. For example, if we want to add a listener for specific message, we can use the provided message function:
self.handler.app.message(re.compile('.*'))(self.process_question)
Here message is passed a regex to accept any string, and returns an object that consumes the function it should invoke when it reads the specified string. In our case, process_question will be called anytime a message is posted.
Functions that we pass to our application can accept special parameters such as the say function which can be used by our bot to post messages or the body parameter which is a dict containing relevant information on the topic. Here is an example where we retrieve the user_id of the message poster and answer with the content of the message:
def process_question(self, body, say):
text = body['event']['text']
user_id = body['event']['user']
say(text)
For a full list of events the slack bot can handle please refer to its documentation.
If you want to read the messages of channels, where the bot is part of, you first need to know the channel id to request the messages of a channel. Therfore one need to:
def fetch_conversations(self):
try:
# Call the conversations.list method using the WebClient
result = self.client.conversations_list()
#the list of conversations one can get from result["channels"]
except SlackApiError as e:
print("Error fetching conversations: {}".format(e))
Now one can get the messages from the channel with a call of:
self.client.conversations_history(channel=channel_id, oldest=oldest)
The channel attribute being the channel_id and oldest a timestamp to which the messages will be read back.
Attention!: The bot can only read messages, where he is part of, therefore filtering the conversation-list by checking for the attribute conversation["is_member"].