[Python] Python making API data calls of previous GitHub commits - this is not supposed to...

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    Is there any particular reason as to why my code, which is deigned to retrieve the latest commits from my GitHub repository, keeps sending me not only an email of the latest commits, but also an email of the previous commits (the commit before the latest commit) as well.

    This is despite me telling it to only ping an email of the latest commits. I fail to see why this is so difficult for Python to work out and its making me infuriated.

    This runs through a for loop which contains a set() of remote GitHub repos and fetches the data through their respective API calls. It is then supposed to populate the repo_data list by .append(ing)()` each repo's data.

    It works perfectly, all returning 200 response codes & it prints the commit data for each repo (once & they're the latest commit SHA's as well), however, it's still also sending an email of the previous commit data. There is absolutely no reason for this this.

    This is my MRE:

    #commit_notify.py
    import requests
    import send_email

    # GitHub repository info
    OWNER = "<OWNER>"
    GITHUB_TOKEN = "<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 = {"<Remote Repo>", "<Remote Repo>", "<Remote Repo>", "<Remote Repo>"}

    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()


    Below is the send_email() module.

    #send_email.py
    import smtplib
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    DOMAIN = "<DOMAIN>" #Sender Domain
    GITHUB_URL = "https://github.com/{owner}"

    #SMTP Server Information
    SMTP_SERVER = "<SMTP_SERVER>"
    SMTP_EMAIL = "<SMTP_EMAIL>"
    SMTP_PASSWORD = "<SMTP_PASSWORD>"
    SMTP_PORT = <PORT>

    #Recipient Information
    receiver_email = "<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"""
    ========================================================================<br>
    <table border="0" cellpadding="5" cellspacing="0" style="border-collapse: collapse; text-align: left;">
    <tr>
    <th>Secure Hash Algorithm (SHA):</th>
    <td>{data["sha"][:7]}</td>
    </tr>
    <tr>
    <th>Repository Name:</th>
    <td>{data['repo']}</td>
    </tr>
    <tr>
    <th>API URL:</th>
    <td>{data['url']}</td>
    </tr>
    <tr>
    <th>Commit Date:</th>
    <td>{data['date']}</td>
    </tr>
    <tr>
    <th>Author ID:</th>
    <td>{data['id']}</td>
    </tr>
    </table>
    """

    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}")

    Continue reading...

Compartilhe esta Página