Get Slack Alerts for New GitHub Issues Instantly!
Автор: CodeVisium
Загружено: 2025-05-30
Просмотров: 307
Welcome to CodeVisium’s Lightning-Fast Automations! In this tutorial, we’ll set up a Python script that checks a GitHub repository for new issues and sends alerts to Slack. No API experience needed.
1. Setup Environment
Virtual Environment: Isolates dependencies.
python3 -m venv venv
Activate:
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # Windows
Install Dependencies:
pip install requests python-dotenv schedule
requests: For HTTP API calls.
python-dotenv: Loads sensitive variables (tokens, URLs) from a .env file.
schedule: Runs functions on a timer inside Python.
2. GitHub Personal Access Token
Why? Unauthenticated calls to GitHub’s API are rate-limited. A token raises your limit and can access private repos.
Create Token:
Log in to GitHub.
Go to Settings → Developer settings → Personal access tokens → Generate new token.
Name it (e.g., “Slack Notifier”) and grant repo or public_repo scope.
Click Generate token and copy the value.
Store in .env:
GITHUB_TOKEN=ghp_yourGeneratedTokenHere
Never share or commit this file.
3. Slack Incoming Webhook
What? A Webhook URL lets you post messages into a Slack channel.
Setup:
In Slack, click Apps → Search Incoming Webhooks → Add to Slack.
Pick a channel (e.g., #alerts) and click Allow.
Copy the Webhook URL (looks like https://hooks.slack.com/services/...).
Store in .env:
SLACK_WEBHOOK_URL=https://hooks.slack.com/services/XXXX...
4. Writing the Script (github_to_slack.py)
Load Variables
import os
from dotenv import load_dotenv
load_dotenv()
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN")
SLACK_WEBHOOK_URL = os.getenv("SLACK_WEBHOOK_URL")
Define Repo & Tracking File
OWNER = "your-username-or-org"
REPO = "your-repo-name"
LAST_ISSUE_FILE = "last_issue_id.txt"
Helper Functions
Read last seen issue ID or return None
def get_last_seen_issue_id():
if os.path.exists(LAST_ISSUE_FILE):
with open(LAST_ISSUE_FILE) as f:
return f.read().strip()
return None
Save new issue ID
def save_last_seen_issue_id(issue_id):
with open(LAST_ISSUE_FILE, "w") as f:
f.write(str(issue_id))
Fetch Latest Issue from GitHub
import requests
def fetch_latest_issue():
url = f"https://api.github.com/repos/{OWNER}/{REPO}/issues?state=open&sort=created&direction=desc&per_page=1"
headers = {"Authorization": f"token {GITHUB_TOKEN}"}
response = requests.get(url, headers=headers)
if response.status_code == 200:
issues = response.json()
return issues[0] if issues else None
else:
print("GitHub API error:", response.status_code, response.text)
return None
Send Slack Notification
import json, requests
def send_slack_notification(issue):
title = issue.get("title")
url = issue.get("html_url")
body = issue.get("body") or "No description."
payload = {
"text": f":warning: New GitHub Issue!*\n*Title: {title}\n*URL:* {url}\n*Description:* {body[:200]}..."
}
headers = {"Content-Type": "application/json"}
res = requests.post(SLACK_WEBHOOK_URL, headers=headers, data=json.dumps(payload))
if res.status_code != 200:
print("Slack error:", res.status_code, res.text)
Main Job Function
def job():
last_id = get_last_seen_issue_id()
latest = fetch_latest_issue()
if latest:
latest_id = str(latest.get("id"))
if last_id != latest_id:
send_slack_notification(latest)
save_last_seen_issue_id(latest_id)
5. Scheduling the Script
In-Python (cross-platform)
import schedule, time
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(30)
This runs job() every 5 minutes.
Cron (Linux/macOS)
*/5 * * * * /usr/bin/python3 /path/to/github_to_slack.py
Edit with crontab -e. Ensures the script executes every 5 minutes.
6. Test & Deploy
Local Test
Activate virtual environment.
Verify .env values.
Run the script:
python github_to_slack.py
Creates last_issue_id.txt.
Sends a Slack alert if a new issue exists.
Keep Running
Use screen, tmux, or a process manager (e.g., systemd) to keep the Python script active.
Or rely on Cron for periodic execution.
Troubleshooting
GitHub 401: Check token validity and scope.
Slack invalid_payload: Verify Webhook URL and JSON payload.
Ensure .env variable names (GITHUB_TOKEN, SLACK_WEBHOOK_URL) match exactly.
By following these steps, every new GitHub issue will trigger an instant Slack notification—helping your team respond faster. Use this pattern to automate CI/CD alerts, error notifications, deployment updates, or any other workflow. Stay tuned for more Lightning-Fast Automations on CodeVisium!
#Automation #Python #GitHub #Slack #Webhooks #CodeVisium #DevOps #Notifications

Доступные форматы для скачивания:
Скачать видео mp4
-
Информация по загрузке: