Slacking with Python

You may read the title and think to yourself does Mike mean how to be lazy with Python?

No, I literally mean Slack, as in the messaging app.

You may find yourself constantly sending out the same Slack message, for example, an update, a poll, or a link to some live event. This is, by definition, a manual effort. Luckily, it no longer has to be a manual effort!

In this blog post, you’ll learn how to write Python code to send a message in Slack.


To follow along with this blog post, you’ll need:

Writing and Running the Code (Post to Slack with Python)

In a short 26 lines of code, you can have any message, in any Slack channel, sent automatically. Let’s dive into how to do that.

  • For the imports, you’ll use the standard sys library and the slack_sdk library, along with the errors import to call upon non-generic errors.
  • For the message() function, you’ll pass in three arguments – token (the API), channel (what channel you want to post to), and mess (the message)
  • The auth variable calls upon the WebClient class, which ingests the value of the token argument
  • Within the try block, you’ll be using the str function to message in your message. Then, using the auth variable, you’ll use the chat_postMessage() function to pass in the channel and message arguments.
  • In the except block, you’ll use custom error handling to retrieve a response from the Slack API. Although it sounds odd, ok means an error occurred (I know, it sounds like it should be backward and ok should mean all is well)
  • Using the sys library, you’ll pass in the three arguments – token, channel, and mess.
  • Finally, call the function.

You can see the code below.

import os
import sys

from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

def message(token, channel, mess):
    auth = WebClient(token=token)

        message = str(mess)
        auth.chat_postMessage(channel=channel, text=message)
    except SlackApiError as e:
        assert e.response["ok"] is False
        print(f"Received Error: {e.response['error']}")

token = sys.argv[1]
channel = sys.argv[2]
mess = sys.argv[3]

if __name__ == '__main__':
    message(token, channel, mess)

Now that the code is written, you can use the terminal to post to Slack with Python and pass in the arguments. For example, the line below writes testing 123 in the general channel.

python .\\ your_token general 'test 123'

And just like that, an automated Slack message has been sent to the general channel.

Leave a Reply

Your email address will not be published. Required fields are marked *