Last modified: Feb 01, 2026 By Alexander Williams

Python Slack API Guide for Beginners

Slack is a powerful platform for team communication. You can automate it with Python. This guide shows you how.

We will cover the basics of the Slack API. You will learn to send messages and build simple bots. This is a great way to start with API integration.

If you are new to APIs, our Python API Tutorial for Beginners is a helpful starting point.

What is the Slack API?

The Slack API lets your code talk to Slack. You can read messages, send alerts, and manage channels. It turns Slack into a programmable tool.

You interact with it over HTTP. Your Python code sends requests to Slack's servers. Slack sends back data like messages or user info.

This is similar to how you would pull data from other services, as explained in our Python API Data Pulling Guide.

Getting Started: Prerequisites

You need a few things before you start. First, make sure Python is installed. You also need a Slack workspace where you have permission to create apps.

Most importantly, you need a Slack API token. This token is like a key. It tells Slack that your application is allowed to perform actions.

1. Create a Slack App

Go to the Slack API website. Click "Create New App". Choose "From scratch".

Give your app a name and select your development workspace. Click "Create App". You will be taken to your app's settings page.

2. Get Your Bot Token

In the left sidebar, click "OAuth & Permissions". Scroll to "Scopes".

Under "Bot Token Scopes", add the permissions you need. For sending messages, add chat:write.

Scroll back to the top of the page. Click "Install to Workspace". Follow the prompts. After installation, you will see a "Bot User OAuth Token".

Copy this token. It starts with xoxb-. Keep it secret. Never share it or commit it to public code.

3. Install the Python Library

The easiest way to use the Slack API in Python is with the official slack_sdk library. Install it using pip.


pip install slack_sdk
    

Sending Your First Message

Let's write a simple script. It will post a message to a Slack channel. Replace the placeholder token and channel ID with your own.


# Import the WebClient from the SDK
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

# Your bot's OAuth token (starts with xoxb-)
SLACK_TOKEN = "xoxb-your-token-here"
# The ID of the channel you want to post to
CHANNEL_ID = "C1234567890"

# Initialize a Web API client
client = WebClient(token=SLACK_TOKEN)

try:
    # Call the chat.postMessage method
    response = client.chat_postMessage(
        channel=CHANNEL_ID,
        text="Hello from Python! :python:"
    )
    print("Message sent successfully!")
except SlackApiError as e:
    # You will get a SlackApiError if something goes wrong
    print(f"Error sending message: {e.response['error']}")
    

In this code, we create a WebClient object with our token. We then use the chat_postMessage method to send a message.

The channel parameter can be a channel ID or a channel name. The text parameter contains your message.

Handling errors with SlackApiError is crucial for robust applications, much like handling API call errors in general, covered in our Python API Calls Guide for Beginners.

Reading Messages from a Channel

You can also fetch message history. This is useful for building bots that react to user input. Use the conversations_history method.


from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

SLACK_TOKEN = "xoxb-your-token-here"
CHANNEL_ID = "C1234567890"

client = WebClient(token=SLACK_TOKEN)

try:
    # Fetch the conversation history
    result = client.conversations_history(channel=CHANNEL_ID, limit=5)
    
    # Print the messages
    for message in result["messages"]:
        print(f"User: {message.get('user')}")
        print(f"Text: {message.get('text')}")
        print("-" * 20)
        
except SlackApiError as e:
    print(f"Error fetching history: {e.response['error']}")
    

User: UABCD1234
Text: Has anyone seen the latest report?
--------------------
User: UEFGH5678
Text: I just posted it in #reports.
--------------------
    

The conversations_history method returns a list of messages. The limit parameter controls how many messages to get.

Each message is a dictionary. You can access the sender's user ID with message['user'] and the text with message['text'].

Building a Simple Slack Bot

A bot can listen for events and respond. This requires using the Socket Mode for real-time events. First, enable it in your app settings.

Go to your app's "Socket Mode" page and enable it. You will need to generate an "App-Level Token" with the connections:write scope.

Here is a basic bot that responds when mentioned.


from slack_sdk import WebClient
from slack_sdk.socket_mode import SocketModeClient
from slack_sdk.socket_mode.response import SocketModeResponse
from slack_sdk.socket_mode.request import SocketModeRequest

SLACK_APP_TOKEN = "xapp-your-app-level-token"  # Starts with xapp-
SLACK_BOT_TOKEN = "xoxb-your-bot-token"

# Initialize clients
web_client = WebClient(token=SLACK_BOT_TOKEN)
socket_client = SocketModeClient(app_token=SLACK_APP_TOKEN, web_client=web_client)

def process_event(client: SocketModeClient, req: SocketModeRequest):
    # This function handles incoming events
    if req.type == "events_api":
        # Acknowledge the event receipt
        response = SocketModeResponse(envelope_id=req.envelope_id)
        client.send_socket_mode_response(response)
        
        event_data = req.payload["event"]
        
        # Check if it's a message and the bot is mentioned
        if event_data.get("type") == "message" and "subtype" not in event_data:
            channel = event_data["channel"]
            text = event_data.get("text", "")
            
            if "hello bot" in text.lower():
                # Respond to the message
                web_client.chat_postMessage(
                    channel=channel,
                    text=f"Hello there, <@{event_data['user']}>! How can I help?"
                )

# Connect the event listener
socket_client.socket_mode_request_listeners.append(process_event)

# Start the connection
socket_client.connect()
print("Bot is running... Press Ctrl+C to stop.")

# Keep the main thread alive
import time