Saturday, March 26, 2022

Read and Post messages in a Slack

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.


Saturday, March 19, 2022

Post a message in Slack

Using python, we can send automated messages to slack. In this post, we will use the webhook provided by slack to post messages in slack.

Let's follow the step-by-step process.

First, we will generate the webhook URL.

  1. Log in to your slack workspace. 
  2. Under apps, click on "Add Apps".
  3. In the search box, write "Incoming webhook" and search.
  4. Once you see "Incoming Webhook" under Available Apps, click on Add button.
  5. Click on the "Add to Slack"
  6. Select a channel or create a channel where the bot will post the messages.
  7. Now, click on the "Add Incoming Webhooks integration" button.
  8. The above step will give us a webhook URL. Copy this URL.

Now, it's time to use the webhook URL from python.

Go to your python editor and paste this code:

Make sure to update the url with the one you copied. Also, you can change the username that you will be displayed to show who has posted the message.


import json
import requests

url = 
'https://hooks.slack.com/services/Txxxxxxxxx/xxxxxxxxxxxxxxxxxxxxxxxxx'
headers = {'Content-Type' 'application/json' }
slack_data = {     
"username" "Demo bot" ,     
"icon_emoji" ":satellite:" ,     
"attachments" : [
 {            
"color" "#FF0000" ,             
"fields" :[
   {             
"title" "Test Message" ,
"value" "Hello, This is from Python" ,
"short" "false",
    }
 ]
  }
]
}

response = requests.post(url, data=json.dumps(slack_data), headers=headers)

print( 'Slack response' , response.status_code)


 

Once you run the code, you will see something like this on slack.