Skip to content

Instantly share code, notes, and snippets.

@leseb
Created May 7, 2025 14:42
Show Gist options
  • Save leseb/e686d639333bb9775718dbc017116cb9 to your computer and use it in GitHub Desktop.
Save leseb/e686d639333bb9775718dbc017116cb9 to your computer and use it in GitHub Desktop.
weekly-report.py
import requests
from datetime import datetime, timedelta
import json
USERNAME = "YOUR_USERNAME_HERE" # or your GitHub username
TOKEN = "YOUR_TOKEN_HERE"
HEADERS = {
'Authorization': f'bearer {TOKEN}',
'Content-Type': 'application/json',
}
# Get the start of the current week (Monday) and end of the week (Friday)
today = datetime.utcnow()
start_of_week = today - timedelta(days=7) # Last 7 days
end_of_week = today # Today
# Format dates for GitHub API
start_date = start_of_week.strftime("%Y-%m-%d")
end_date = end_of_week.strftime("%Y-%m-%d")
def fetch_contributions():
query = """
query($username: String!, $from: DateTime!, $to: DateTime!) {
user(login: $username) {
contributionsCollection(from: $from, to: $to) {
totalCommitContributions
totalIssueContributions
totalPullRequestContributions
totalPullRequestReviewContributions
commitContributionsByRepository {
repository {
name
nameWithOwner
}
contributions(first: 100) {
totalCount
}
}
pullRequestContributionsByRepository {
repository {
name
}
contributions(first: 100) {
totalCount
nodes {
pullRequest {
title
url
state
}
}
}
}
issueContributionsByRepository {
repository {
name
}
contributions(first: 100) {
totalCount
nodes {
issue {
title
url
state
}
}
}
}
pullRequestReviewContributionsByRepository {
repository {
name
}
contributions(first: 100) {
totalCount
nodes {
pullRequestReview {
pullRequest {
title
url
}
state
}
}
}
}
}
}
}
"""
variables = {
"username": USERNAME,
"from": f"{start_date}T00:00:00Z",
"to": f"{end_date}T23:59:59Z"
}
try:
response = requests.post(
'https://api.github.com/graphql',
headers=HEADERS,
json={'query': query, 'variables': variables}
)
response.raise_for_status()
# Debug the response
data = response.json()
if 'errors' in data:
print("GraphQL Errors:")
for error in data['errors']:
print(f"- {error.get('message', 'Unknown error')}")
return None
if not data.get('data', {}).get('user'):
print(f"User '{USERNAME}' not found or no data available")
return None
return data['data']['user']['contributionsCollection']
except requests.exceptions.RequestException as e:
print(f"Network error: {e}")
return None
except json.JSONDecodeError as e:
print(f"Invalid JSON response: {e}")
print("Response content:", response.text)
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
# Fetch contributions data
contributions = fetch_contributions()
if not contributions:
print("Failed to fetch contributions data")
exit(1)
# Format report
print(f"# GitHub Weekly Report for {USERNAME}")
print(f"## Week of {start_date} to {end_date} (Mon-Fri)\n")
# PRs
print(f"## Pull Requests ({contributions['totalPullRequestContributions']})")
for repo in contributions['pullRequestContributionsByRepository']:
repo_name = repo['repository']['name']
for contribution in repo['contributions']['nodes']:
pr = contribution['pullRequest']
state = pr['state'].lower()
print(f"- [{pr['title']}]({pr['url']}) ({state})")
# Issues
print(f"\n## Issues ({contributions['totalIssueContributions']})")
for repo in contributions['issueContributionsByRepository']:
repo_name = repo['repository']['name']
for contribution in repo['contributions']['nodes']:
issue = contribution['issue']
state = issue['state'].lower()
print(f"- [{issue['title']}]({issue['url']}) ({state})")
# Reviews
print(f"\n## Code Reviews ({contributions['totalPullRequestReviewContributions']})")
for repo in contributions['pullRequestReviewContributionsByRepository']:
repo_name = repo['repository']['name']
for contribution in repo['contributions']['nodes']:
review = contribution['pullRequestReview']
pr = review['pullRequest']
state = review['state'].lower()
print(f"- [{state.title()} Review]({pr['url']}) - {pr['title']}")
# Commits
print(f"\n## Commits ({contributions['totalCommitContributions']})")
for repo in contributions['commitContributionsByRepository']:
repo_name = repo['repository']['name']
repo_full_name = repo['repository']['nameWithOwner']
count = repo['contributions']['totalCount']
commits_url = f"https://github.com/{repo_full_name}/commits?author={USERNAME}&since={start_date}T00:00:00Z&until={end_date}T23:59:59Z"
print(f"- {repo_name}: [{count} commits]({commits_url})")
@rhuss
Copy link

rhuss commented May 14, 2025

Thanks for sharing!

Little suggestion: To get only the activity in this week, this update should fix it:

from datetime import datetime, timedelta

today = datetime.utcnow()
start_of_week = today - timedelta(days=today.weekday())  # Monday
end_of_week = start_of_week + timedelta(days=4)          # Friday

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment