Automation

Creating a Slack Bot with Python and Events API

Learn how to create a Slack bot using Python and integrate with the Events API, enabling the bot to respond to Slack channel events efficiently.

4 min read

Creating a Slack Bot with Python and Events API
Learn how to build a Slack bot with Python and integrate it with the Events API to respond to channel events.

Prerequisites for Building a Slack Bot

Before starting, ensure you have the following in place:

prerequisites

  • A Slack workspace where you can install and test your bot.
  • Python (version 3.8 or higher) installed on your system and a working knowledge of it.
  • Ngrok installed for exposing your local development server to the internet.
  • Basic understanding of Slack permissions, OAuth scopes, and webhooks.

Steps to Create a Slack Bot with Python

Follow these steps to create your Slack bot and integrate it with the Events API:

steps

  1. Create a Slack App

    • Visit the Slack API portal and create a new app.
    • Provide a unique app name and select your Slack workspace.
  2. Enable Event Subscriptions

    • Go to the "Event Subscriptions" tab in your app settings.
    • Enable events and specify a Request URL. This URL will handle POST requests sent by the Events API.
  3. Expose a Local Flask Server with Ngrok

    • Run Ngrok on the same port as the Flask app (e.g., 5000):
    bash
    ngrok http 5000
    • Use the forwarded Ngrok URL as the Request URL in the Slack app settings.
  4. Install Required Python Packages
    Install necessary dependencies:

bash
   pip install flask slackeventsapi
  1. Set Up Environment Variables
    Create a .env file in your project directory to securely store your credentials:

    bash
    SLACK_SIGNING_SECRET=<your-signing-secret>
    SLACK_BOT_TOKEN=<your-bot-token>
  2. Write the Flask Server Code
    Develop a simple Flask app to receive and handle Slack events:

    python
    from flask import Flask, request, jsonify
    from slackeventsapi import SlackEventAdapter
    import os
    from slack_sdk import WebClient
    
    # Load secrets
    slack_signing_secret = os.getenv("SLACK_SIGNING_SECRET")
    slack_bot_token = os.getenv("SLACK_BOT_TOKEN")
    
    app = Flask(__name__)
    slack_event_adapter = SlackEventAdapter(slack_signing_secret, "/slack/events", app)
    client = WebClient(token=slack_bot_token)
    
    @slack_event_adapter.on("message")
    def handle_message(payload):
        event = payload.get("event", {})
        user = event.get("user")
        text = event.get("text")
        channel = event.get("channel")
        
        # Avoid bot responding to its own messages
        if user != None:
            client.chat_postMessage(channel=channel, text=f"You said: {text}")
    
    if __name__ == "__main__":
        app.run(port=5000)
  3. Verify and Test

    • Restart your Flask server and Ngrok.
    • Subscribe to the message.channels event in your Slack app settings.
    • Test the bot by sending messages in your Slack channel and observing its responses.

Common Issues and Warnings

Socket Mode: Developing without Public URL

For local testing without exposing a publicly accessible endpoint, you can use Socket Mode.

When to Use Socket Mode

Choose Socket Mode if you:

  • Don't want to depend on Ngrok or another service exposing your local server.
  • Prefer secured communication over websockets managed by Slack.

Steps for Socket Mode:

  1. Enable Socket Mode in the app settings.
  2. Use a library like slack_bolt to connect to Slack's events API via websockets.

Takeaway

Building a Slack bot using Python and the Events API is straightforward with proper setup. Leveraging tools like Flask and Ngrok allows quick development for event-based handling. Transition to secure Socket Mode for a scalable solution during production. Create robust bots by expanding event listeners and scopes as required.

FAQ

How do I handle 3-second timeout errors in Slack?

Ensure your endpoint responds within Slack’s deadline by sending a quick HTTP 200 status and processing any internal logic asynchronously.

How do I prevent my bot from responding to itself?

Compare the user in incoming events with your bot’s own ID. If they match, ignore the event to stop recursive responses.

Can I add multiple event listeners in my bot?

Yes, create separate handlers for each event using @slack_event_adapter.on("<event_name>"). Adjust your app's subscribed events and permissions accordingly.


Official reference: Slack API documentation.