pythonchatslack

How to send message to a Slack channel in Python


I need to send out message to a Slack channel with Python.

My Google search (here) and search from Stack Overflow (here) results in little help. What is the right way to get it working?

The closest guide I found is from Slack official guide here but it's not clear how to do the authentication with SLACK_BOT_TOKEN to call client.chat_postMessage()

from slack_sdk import WebClient
client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))

result = client.chat_postMessage(
    channel=channel_id,
    text="Hello world!"
)

Solution

  • In brief

    p.s.

    How to get

    After days seeking Slack documentation for it, here is related guide; please search the page to get to this section OAuth Tokens for Your Workspace - this is a pain. I have no idea why there is no SLACK_BOT_TOKEN mentioned in this guide.

    enter image description here


    Full details:

    One thing you'll need before starting is a Slack app. If you don't have one yet, here's a very quick guide to help you create one.

    Requesting the necessary permissions chat:write. This one grants permission for your app to send messages as itself (apps can send messages as users or bot users)

    Requesting these permissions is easy: