DEV Community

John Ajera
John Ajera

Posted on

How to Send Notifications to Slack Using Python

📢 How to Send Notifications to Slack Using Python

🚀 Introduction

If you need to send automated notifications to Slack from different services, you can use Python and Slack Incoming Webhooks to achieve this. This guide provides a generic Python script that can be used for various use cases, such as:

  • ✅ Sending notifications from AWS Lambda.
  • ✅ Integrating with message queues like AWS SQS.
  • ✅ Triggering alerts from any Python application.

🔧 Step 1: Create a Slack Channel

1️⃣ Open Slack and navigate to your workspace.

2️⃣ Click on the “+” (Add a Channel) button in the sidebar.

3️⃣ Select “Create a New Channel” from the options.

4️⃣ Enter a name for your channel (e.g., #aws-notifications).

5️⃣ Choose whether the channel should be public (accessible by all workspace members) or private (invite-only).

6️⃣ Click Create to finalize the channel setup and invite relevant team members if needed.


🔧 Step 2: Create and Configure a Slack App

1️⃣ Go to Slack API Console

2️⃣ Click "Create an App"

  • Choose "From scratch".
  • Name it (e.g., aws-notifications).
  • Choose a Slack workspace.

3️⃣ Enable Incoming Webhooks

  • Inside your app's settings, navigate to "Incoming Webhooks".
  • Toggle the switch to Activate Incoming Webhooks.
  • Click "Add New Webhook to Workspace".
  • Select the newly created Slack channel (e.g., #aws-notifications).
  • Click Create App.

4️⃣ Generate a Webhook URL

  • Click "Add New Webhook to Workspace".
  • Select the #aws-notifications channel.
  • Click "Allow" to grant the necessary permissions.
  • Copy the generated Webhook URL. Example:
 https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX 
Enter fullscreen mode Exit fullscreen mode

📌 You'll use this Webhook URL in your Python script to send messages to Slack.


🔧 Step 3: Write the Python Script

This Python script sends messages to Slack. It works in AWS Lambda, local applications, or any automation tool.

import json import urllib.request import os def send_slack_notification(message): slack_webhook_url = os.getenv("SLACK_WEBHOOK_URL") if not slack_webhook_url: raise ValueError("SLACK_WEBHOOK_URL environment variable is missing") data = json.dumps({"text": message}).encode("utf-8") req = urllib.request.Request(slack_webhook_url, data=data, headers={"Content-Type": "application/json"}) try: with urllib.request.urlopen(req) as response: print("✅ Slack notification sent successfully!") return response.status except Exception as e: print(f"Failed to send message to Slack: {e}") return None if __name__ == "__main__": message = "Hello from aws-notifications! 🚀" send_slack_notification(message) 
Enter fullscreen mode Exit fullscreen mode

🎯 Use Cases

✅ AWS Lambda Integration

Modify the script to accept event data in Lambda:

def lambda_handler(event, context): for record in event.get("Records", []): message_body = record.get("body", "No message body") send_slack_notification(f"AWS Lambda received: {message_body}") return {"status": "success"} 
Enter fullscreen mode Exit fullscreen mode

✅ Sending Slack Notifications from AWS SQS

AWS Lambda can trigger the script when an SQS message arrives.

✅ Sending Alerts from a Python Script

Use the script in any Python application to notify Slack:

send_slack_notification("AWS Lambda received: AWS Event Triggered") 
Enter fullscreen mode Exit fullscreen mode

🔧 Step 4: Sample Execution

✅ Running Locally

If running on your local machine, export your Slack webhook URL and execute the script:

export SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX python script.py 
Enter fullscreen mode Exit fullscreen mode

Expected Output:

✅ Slack notification sent successfully! 
Enter fullscreen mode Exit fullscreen mode

✅ Running in AWS Lambda

Deploy the function and invoke it via AWS CLI:

aws lambda invoke \ --function-name aws-notifications-lambda \ --payload '{"Records": [{"body": "AWS Event Triggered"}]}' \ response.json 
Enter fullscreen mode Exit fullscreen mode

Expected Slack Message:

AWS Lambda received: AWS Event Triggered 
Enter fullscreen mode Exit fullscreen mode

✅ Running via AWS SQS

Send a test message to SQS:

aws sqs send-message \ --queue-url https://sqs.YOUR-REGION.amazonaws.com/YOUR-ACCOUNT-ID/YOUR-QUEUE \ --message-body '{"event": "EC2 tag modified"}' 
Enter fullscreen mode Exit fullscreen mode

Slack will receive:

AWS Lambda received: EC2 tag modified 
Enter fullscreen mode Exit fullscreen mode

✅ Conclusion

Now, you have a generic Python script to send messages to Slack! 🎉 You’ve learned:

  • How to create a Slack channel.
  • How to configure Slack Webhooks.
  • How to send messages using Python.
  • How to integrate it into AWS Lambda, SQS, or any Python application.
  • How to execute and test the script locally and in AWS.

💬 What other Slack integrations do you want to see? Let me know in the comments! 🚀

Top comments (0)