Code: Select all
#commit_notify.py
import requests
import send_email
# GitHub repository info
OWNER = ""
GITHUB_TOKEN = ""
GITHUB_API_URL = "https://api.github.com/repos/{owner}/{repo}/commits"
if not GITHUB_TOKEN:
raise ValueError("GITHUB_TOKEN is not set. Please set the environment variable.")
# Function to get the latest commit hash from GitHub
def get_latest_commit() -> str:
repo_data = []
headers = {"Authorization": f"token {GITHUB_TOKEN}"}
repos = {"", "", "", ""}
for repo in repos:
try:
url = GITHUB_API_URL.format(owner=OWNER, repo=repo)
response = requests.get(url,headers = headers)
print(response)
except requests.exceptions.RequestException as e:
print(f"Request failed for {repo}: {e}")
continue
if response.status_code == 200:
commits = response.json()
latest_commit_sha = commits[0]["sha"]
latest_commit_date = commits[0]["commit"]["author"]["date"]
latest_commit_id = commits[0]["author"]["id"]
repo_data.append({
"repo" : repo,
"sha" : latest_commit_sha,
"url" : url,
"date" : latest_commit_date,
"id" : latest_commit_id
})
continue
else:
print(f"Error fetching commits for {repo}: {response.status_code}")
print(f"Error details: {response.text}")
continue
if repo_data:
send_email.send_message(repo_data)
return repo_data
if __name__ == "__main__":
get_latest_commit()
Code: Select all
#send_email.py
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
DOMAIN = "" #Sender Domain
GITHUB_URL = "https://github.com/{owner}"
#SMTP Server Information
SMTP_SERVER = ""
SMTP_EMAIL = ""
SMTP_PASSWORD = ""
SMTP_PORT =
#Recipient Information
receiver_email = ""
#Sender Information
sender_email = f"notifications{DOMAIN}"
def send_message(latest_commit_data:dict) -> None:
resource_data_table = ""
for data in latest_commit_data:
resource_data_table += f"""
========================================================================
Secure Hash Algorithm (SHA):
{data["sha"][:7]}
Repository Name:
{data['repo']}
API URL:
{data['url']}
Commit Date:
{data['date']}
Author ID:
{data['id']}
"""
message_body = f"""
{resource_data_table}
"""
msg = MIMEMultipart()
msg['Subject'] = f"New Commit Notification"
msg['From'] = f"{sender_email"
msg['To'] = receiver_email
body = message_body
msg.attach(MIMEText(body, "html"))
try:
with smtplib.SMTP(SMTP_SERVER, SMTP_PORT) as server:
server.starttls()
server.login(SMTP_EMAIL, SMTP_PASSWORD)
server.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
print(f"Error sending email: {e}")