In this blog, we will read messages from slack and will respond to them.
Let's first create a channel in which our bot will read the messages and then respond to them.
Create a channel:
Login to slack and in the channels, click on "Add Channels".
In this case, I am going to name the channel: slack_bot.
Now let's create an App that will read and respond to messages.
Go to Slack API.
Click on "Create New App" and then click on "From Scratch"
Give a name to the bot. I am giving a name as "Slack Bot" and select your workspace and click on "Create App".
Under "Add Features and functionalities" select Bots.
Click on "Review Scopes to Add"
Click on "Add New Redirect URL"
Give a URL link, your company URL and if you don't have then give any other URL like Google then click on "Add" and "Save URL"
Under Scopes -> Bot Token Scopes,
Add an OAuth Scopes, select three "channels:read", "channels:history", and "chat:write".
Scroll up and click on "Install to Workspace" and click on "Allow".
This will give you Bot user OAuth Token. Copy this token and will use this to connect from Python.
Now we need to add the bot to the channel.
Go to channel (#slack_bot), and in the message type below and hit enter:
invite /@Slack Bot
Now we are ready to interact with Slack from python.
import logging
import os
# Import WebClient from Python SDK
# (github.com/slackapi/python-slack-sdk)
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# Replace the token that you copied earlier.
token_oath = 'xoxb-2222222222222-4444444444444-BPvtQxxxxxxxxxxxxxxxxxxx'
# Best practice is to get the token from env variable like
# token_oath = os.environ.get("SLACK_BOT_TOKEN")
# WebClient instantiates a client that can call API methods
# When using Bolt, you can use either `app.client` or the `client` passed to listeners.
client = WebClient(token=token_oath)
logging.basicConfig(filename="mylog.log")
logger = logging.getLogger(__name__)
# Get the channel id for slack bot
# Let's get the channedID for the channel #slack_bot
channel_name = "slack_bot"
channel_id = None
try:
# Call the conversations.list method using the WebClient
for result in client.conversations_list():
if channel_id is not None:
break
for channel in result["channels"]:
if channel["name"] == channel_name:
channel_id = channel["id"]
#Print result
print(f"Found conversation ID: {channel_id}")
break
except SlackApiError as e:
print(f"Error: {e}")
# Read the conversation from channel slack bot
try:
# Call the conversations.history method using the WebClient
# conversations.history returns the first 100 messages by default
# These results are paginated,
# see: https://api.slack.com/methods/conversations.history$pagination
result = client.conversations_history(channel=channel_id)
conversation_history = result["messages"]
# Print results
logger.info("{} messages found in {}".format(len(conversation_history), id))
for message in conversation_history:
print(message['text'])
except SlackApiError as e:
logger.error("Error creating conversation: {}".format(e))
By this time, you can see all the messages.
Now let's try to post a message once we read a message like "Hi".
for message in conversation_history:
if message['text'] == 'Hi':
# POST a message
channel_id = conversation_id
try:
# Call the conversations.list method using the WebClient
result = client.chat_postMessage(
channel=channel_id,
text="Howdy!\nThis is a response from Bot."
# You could also use a blocks[] array to send richer content
)
# Print result, which includes information about the message (like TS)
print(result)
except SlackApiError as e:
print(f"Error: {e}")
By this stage you can see the message posted on your slack channel.





