Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

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

Get Slack Alerts for New GitHub Issues Instantly!

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

array(10) { [0]=> object(stdClass)#4753 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "V-FasHSM5oE" ["related_video_title"]=> string(155) "Браузер внутри терминала? Челлендж: Живём в Linux через командную строку! Круто или нет?" ["posted_time"]=> string(19) "3 дня назад" ["channelName"]=> string(9) "CyberYozh" } [1]=> object(stdClass)#4726 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "p0Ri2tNb-6I" ["related_video_title"]=> string(186) "Человечество навсегда ЗАПЕРТО в Солнечной системе? Астрофизик Борис Штерн раскрыл неприятную правду" ["posted_time"]=> string(21) "1 день назад" ["channelName"]=> string(23) "Глеб Соломин" } [2]=> object(stdClass)#4751 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "pxyRbnMikTA" ["related_video_title"]=> string(128) "Петр Толстой ВЫ ЧЁ, ОХАМЕЛИ? Наглый УЛЬТИМАТУМ Баку после рейда на ОПГ!" ["posted_time"]=> string(24) "11 часов назад" ["channelName"]=> string(61) "Последние новости дня на этот час" } [3]=> object(stdClass)#4758 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "LQl460dFw74" ["related_video_title"]=> string(86) "Угроза окружения в «треугольнике смерти»" ["posted_time"]=> string(24) "14 часов назад" ["channelName"]=> string(18) "The Breakfast Show" } [4]=> object(stdClass)#4737 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "OUe8mQM1H0E" ["related_video_title"]=> string(61) "РЕВОЛЮЦИЯ, которую мы НЕ ЗАМЕТИЛИ" ["posted_time"]=> string(21) "5 дней назад" ["channelName"]=> string(20) "Раз два три" } [5]=> object(stdClass)#4755 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "kHQy0IcqDTg" ["related_video_title"]=> string(100) "Алексей Семихатов - Мы не знаем, что такое пространство" ["posted_time"]=> string(21) "7 дней назад" ["channelName"]=> string(29) "Айрат Хайруллин" } [6]=> object(stdClass)#4750 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "nrEdavr-d6c" ["related_video_title"]=> string(117) "Путин на скамье подсудимых / Соловьёв захватывает страны Балтии" ["posted_time"]=> string(23) "7 часов назад" ["channelName"]=> string(12) "NEXTA Moment" } [7]=> object(stdClass)#4760 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "cfpLcZqYSZ0" ["related_video_title"]=> string(90) "Делаем  Mac удобнее! Мой ТОП-24 фишек и программ!" ["posted_time"]=> string(25) "2 недели назад" ["channelName"]=> string(14) "Maxim Gustarev" } [8]=> object(stdClass)#4736 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "4JOgKuhGkSY" ["related_video_title"]=> string(98) "КТО ЖИВЁТ ПОД ДНОМ ОКЕАНА? Семихатов, Сурдин, Осадчиев" ["posted_time"]=> string(22) "11 дней назад" ["channelName"]=> string(27) "Вселенная Плюс" } [9]=> object(stdClass)#4754 (5) { ["video_id"]=> int(9999999) ["related_video_id"]=> string(11) "3uPlWhnkR60" ["related_video_title"]=> string(183) "РФ Применила Гром-Э1⚡Зирка Пала🔥 Первые Саперы Прибыли В Курскую Область🪖🚧 Военные Сводки 28.06.2025" ["posted_time"]=> string(23) "5 часов назад" ["channelName"]=> string(27) "Военные Сводки" } }
Браузер внутри терминала? Челлендж: Живём в Linux через командную строку! Круто или нет?

Браузер внутри терминала? Челлендж: Живём в Linux через командную строку! Круто или нет?

Человечество навсегда ЗАПЕРТО в Солнечной системе? Астрофизик Борис Штерн раскрыл неприятную правду

Человечество навсегда ЗАПЕРТО в Солнечной системе? Астрофизик Борис Штерн раскрыл неприятную правду

Петр Толстой ВЫ ЧЁ, ОХАМЕЛИ? Наглый УЛЬТИМАТУМ Баку после рейда на ОПГ!

Петр Толстой ВЫ ЧЁ, ОХАМЕЛИ? Наглый УЛЬТИМАТУМ Баку после рейда на ОПГ!

Угроза окружения в «треугольнике смерти»

Угроза окружения в «треугольнике смерти»

РЕВОЛЮЦИЯ, которую мы НЕ ЗАМЕТИЛИ

РЕВОЛЮЦИЯ, которую мы НЕ ЗАМЕТИЛИ

Алексей Семихатов - Мы не знаем, что такое пространство

Алексей Семихатов - Мы не знаем, что такое пространство

Путин на скамье подсудимых / Соловьёв захватывает страны Балтии

Путин на скамье подсудимых / Соловьёв захватывает страны Балтии

Делаем  Mac удобнее! Мой ТОП-24 фишек и программ!

Делаем  Mac удобнее! Мой ТОП-24 фишек и программ!

КТО ЖИВЁТ ПОД ДНОМ ОКЕАНА? Семихатов, Сурдин, Осадчиев

КТО ЖИВЁТ ПОД ДНОМ ОКЕАНА? Семихатов, Сурдин, Осадчиев

РФ Применила Гром-Э1⚡Зирка Пала🔥 Первые Саперы Прибыли В Курскую Область🪖🚧 Военные Сводки 28.06.2025

РФ Применила Гром-Э1⚡Зирка Пала🔥 Первые Саперы Прибыли В Курскую Область🪖🚧 Военные Сводки 28.06.2025

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]