Skip to content

chore: Update Slack announcement GH Action. #772

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions .github/scripts/announce_pr_on_slack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""
GitHub Actions script to send Slack notifications for new pull requests.
"""

import os
import sys
from typing import Tuple

import httpx


def send_slack_message(
slack_webhook_service_id: str, slack_token: str, slack_channel_id: str, message: str
) -> bool:
"""Send a message to Slack channel."""

url = f"https://hooks.slack.com/services/T{slack_channel_id}/B{slack_webhook_service_id}/{slack_token}"

headers = {
"Content-Type": "application/json",
}

data = {"text": message}

try:
with httpx.Client() as client:
response = client.post(url, headers=headers, json=data)
response.raise_for_status()

result = response.json()
if result.get("ok"):
print("✅ Slack message sent successfully")
return True
else:
print(f"❌ Slack API error: {result.get('error', 'Unknown error')}")
return False

except httpx.HTTPError as e:
print(f"❌ Request error: {e}")
return False


def ensure_environment_variables_are_present() -> (
Tuple[str, str, str, str, str, str, str, str]
):
"""
Ensures that all necessary environment variables are present for the application to run.

This function checks for the presence of required environment variables related to Slack bot token,
Pull Request (PR) details, and repository name. It also validates that the Slack channel is set.

Raises:
SystemExit: If any of the required environment variables are missing.

Returns:
A tuple containing the values of the following environment variables:
- SLACK_BOT_TOKEN: The token for the Slack bot.
- SLACK_CHANNEL: The Slack channel where notifications will be posted.
- SLACK_SERVICE_ID: The ID of the Slack service.
- PR_NUMBER: The number of the Pull Request.
- PR_TITLE: The title of the Pull Request.
- PR_URL: The URL of the Pull Request.
- PR_AUTHOR: The author of the Pull Request.
- REPO_NAME: The name of the repository.
"""
# Get environment variables
slack_token = os.getenv("SLACK_BOT_TOKEN")
slack_channel = os.getenv("SLACK_CHANNEL")
slack_service_id = os.getenv("SLACK_SERVICE_ID")
pr_number = os.getenv("PR_NUMBER")
pr_title = os.getenv("PR_TITLE")
pr_url = os.getenv("PR_URL")
pr_author = os.getenv("PR_AUTHOR")
repo_name = os.getenv("REPO_NAME")

# Validate required environment variables
if not slack_token:
print("❌ SLACK_BOT_TOKEN environment variable is required")
sys.exit(1)

if not slack_channel:
print("❌ SLACK_CHANNEL environment variable is required")
sys.exit(1)

if not slack_service_id:
print("❌ SLACK_SERVICE_ID environment variable is required")
sys.exit(1)

if not all([pr_number, pr_title, pr_url, pr_author, repo_name]):
print(
"❌ Missing required PR information (PR_NUMBER, PR_TITLE, PR_URL, PR_AUTHOR, REPO_NAME)"
)
sys.exit(1)

# Since we're validating these variables, we can assert they're not None
assert pr_number is not None
assert pr_title is not None
assert pr_url is not None
assert pr_author is not None
assert repo_name is not None

return (
slack_token,
slack_channel,
slack_service_id,
pr_number,
pr_title,
pr_url,
pr_author,
repo_name,
)


def main() -> None:
"""Main function to process PR and send Slack notification."""

(
slack_token,
slack_channel,
slack_service_id,
pr_number,
pr_title,
pr_url,
pr_author,
repo_name,
) = ensure_environment_variables_are_present()

print(f"Processing PR #{pr_number}")

# Create Slack message
message = (
f":mega: Oyez! Oyez! Oyez!\n"
f"Hello Team. Please, review this opened PR #{pr_number} in {repo_name}\n"
f"*{pr_title}* by @{pr_author}\n"
f"pull-request-opened: {pr_url}"
)

# Send to Slack
success = send_slack_message(slack_service_id, slack_token, slack_channel, message)

if not success:
sys.exit(1)

print("✅ Process completed successfully")


if __name__ == "__main__":
main()

# Made with Bob
90 changes: 90 additions & 0 deletions .github/scripts/announce_release_on_slack.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
#!/usr/bin/env python3

import json
import logging
import os
import sys

import requests
from github import Github


def ensure_environment_variables_are_present() -> None:
required_env_vars = (
"GITHUB_RELEASE_TAG",
"GITHUB_TOKEN",
"SLACK_BOT_SERVICE_ID",
"SLACK_BOT_TOKEN",
"SLACK_CHANNEL_ID_RELEASES",
)

for env_var in required_env_vars:
if env_var not in os.environ:
logging.fatal(f"A required environment variable is missing: {env_var}")
sys.exit(1)


def get_gh_release_info_text_with_token(release_tag: str, access_token: str) -> str:
gh = Github(access_token)
repo_name = "instana/python-sensor"
repo = gh.get_repo(repo_name)
release = repo.get_release(release_tag)

logging.info("GH Release fetched successfully %s", release)

msg = (
f":mega: Oyez! Oyez! Oyez!\n"
f":package: A new version of the Python Tracer has been released.\n"
f"Name: Instana Python Tracer {release.title}\n"
f"Tag: {release.tag_name}\n"
f"Created at: {release.created_at}\n"
f"Published at: {release.published_at}\n"
f"{release.body}\n"
)

logging.info(msg)
return msg


def post_on_slack_channel(
slack_webhook_service_id: str,
slack_token: str,
slack_channel_id: str,
message_text: str,
) -> None:
api_url = f"https://hooks.slack.com/services/T{slack_channel_id}/B{slack_webhook_service_id}/{slack_token}"

headers = {
"Content-Type": "application/json",
}
body = {"text": message_text}

response = requests.post(api_url, headers=headers, data=json.dumps(body))
response_data = json.loads(response.text)

if response_data["ok"]:
logging.info("Message sent successfully!")
else:
logging.fatal("Error sending message: %s", response_data["error"])


def main() -> None:
# Setting this globally to DEBUG will also debug PyGithub,
# which will produce even more log output
logging.basicConfig(level=logging.INFO)
ensure_environment_variables_are_present()

msg = get_gh_release_info_text_with_token(
os.environ["GITHUB_RELEASE_TAG"], os.environ["GITHUB_TOKEN"]
)

post_on_slack_channel(
os.environ["SLACK_BOT_SERVICE_ID"],
os.environ["SLACK_BOT_TOKEN"],
os.environ["SLACK_CHANNEL_ID_RELEASES"],
msg,
)


if __name__ == "__main__":
main()
41 changes: 41 additions & 0 deletions .github/workflows/opened-pr-notification-on-slack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: PR Slack Notification

permissions:
contents: read
pull-requests: read

on:
pull_request:
types: [opened, reopened, review_requested]

jobs:
notify-slack:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0 # Fetch all history to access commit messages

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.13'

- name: Install dependencies
run: |
pip install httpx

- name: Send Slack notification
env:
SLACK_BOT_TOKEN: ${{ secrets.RUPY_PR_ANNOUNCEMENT_TOKEN }}
SLACK_CHANNEL_ID_RELEASES: ${{ secrets.RUPY_PR_ANNOUNCEMENT_CHANNEL_ID }}
SLACK_BOT_SERVICE_ID: ${{ secrets.RUPY_TOWN_CRIER_SERVICE_ID }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
PR_NUMBER: ${{ github.event.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_URL: ${{ github.event.pull_request.html_url }}
PR_AUTHOR: ${{ github.event.pull_request.user.login }}
REPO_NAME: ${{ github.repository }}
run: python .github/scripts/slack_notify.py
7 changes: 4 additions & 3 deletions .github/workflows/release-notification-on-slack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ on:

# https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#release
release:
types: [published]
types: [published, released]
jobs:
build:
name: Slack Post
Expand All @@ -30,5 +30,6 @@ jobs:
./bin/announce_release_on_slack.py
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
SLACK_CHANNEL_ID_RELEASES: ${{ secrets.SLACK_CHANNEL_ID_RELEASES }}
SLACK_BOT_TOKEN: ${{ secrets.RUPY_TRACER_RELEASES_TOKEN }}
SLACK_CHANNEL_ID_RELEASES: ${{ secrets.RUPY_TRACER_RELEASES_CHANNEL_ID }}
SLACK_BOT_SERVICE_ID: ${{ secrets.RUPY_TOWN_CRIER_SERVICE_ID }}
73 changes: 0 additions & 73 deletions bin/announce_release_on_slack.py

This file was deleted.

Loading