Created
February 1, 2024 07:48
-
-
Save FlakM/2781e4a4ff93fdecfc4048d7393afa68 to your computer and use it in GitHub Desktop.
Simple script for getting the hours for a month on-call from pager duty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Usage: pager_duty.py <MM.YYYY> <User Name> | |
# Example: ./pager_duty.py 12.2023 "Maciej Flak" | |
import http.client | |
import json | |
import sys | |
import os | |
from datetime import datetime, timedelta | |
def fetch_on_call_schedule(api_key, schedule_id, start_date, end_date): | |
conn = http.client.HTTPSConnection("api.pagerduty.com") | |
headers = { | |
'Authorization': f'Token token={api_key}', | |
'Content-Type': 'application/json' | |
} | |
url = f'/schedules/{schedule_id}?since={start_date}&until={end_date}' | |
conn.request("GET", url, headers=headers) | |
response = conn.getresponse() | |
data = response.read() | |
conn.close() | |
if response.status == 200: | |
return json.loads(data) | |
else: | |
print(f"Error fetching schedule: HTTP Status {response.status}") | |
return None | |
def format_datetime(dt_str): | |
dt = datetime.fromisoformat(dt_str) | |
return dt.strftime("%H:%M %d.%m") | |
def print_final_schedule_for_user(schedule_data, user_name): | |
total_hours = 0 | |
for entry in schedule_data.get('schedule', {}).get('final_schedule', {}).get('rendered_schedule_entries', []): | |
if entry['user']['summary'] == user_name: | |
start_dt = datetime.fromisoformat(entry['start']) | |
end_dt = datetime.fromisoformat(entry['end']) | |
duration_hours = (end_dt - start_dt).total_seconds() / 3600 | |
total_hours += duration_hours | |
start_formatted = format_datetime(entry['start']) | |
end_formatted = format_datetime(entry['end']) | |
print(f"{start_formatted} -> {end_formatted}, {duration_hours}") | |
print(f"Sum: {total_hours:.2f}") | |
def verify_environment_variables(): | |
api_key = os.environ.get('PAGER_API_KEY') | |
schedule_id = os.environ.get('PAGER_SCHEDULE_ID') | |
if not api_key: | |
sys.exit("Error: PAGER_API_KEY environment variable is not set.") | |
if not schedule_id: | |
sys.exit("Error: PAGER_SCHEDULE_ID environment variable is not set.") | |
return api_key, schedule_id | |
def verify_command_line_arguments(): | |
if len(sys.argv) < 3: | |
sys.exit("Usage: script.py <MM.YYYY> <User Name>") | |
date_input = sys.argv[1] | |
try: | |
month, year = map(int, date_input.split('.')) | |
datetime(year, month, 1) # to verify valid date | |
except ValueError: | |
sys.exit("Error: Date format should be MM.YYYY (e.g., 04.2024)") | |
name = sys.argv[2] | |
return month, year, name | |
# Check environment variables | |
api_key, schedule_id = verify_environment_variables() | |
# Check command line arguments | |
month, year, name = verify_command_line_arguments() | |
start_date = datetime(year, month, 1).isoformat() | |
end_date = (datetime(year, month + 1, 1) + timedelta(days=1)).isoformat() if month < 12 else (datetime(year + 1, 1, 2)).isoformat() | |
# Fetch schedule | |
schedule_data = fetch_on_call_schedule(api_key, schedule_id, start_date, end_date) | |
if schedule_data: | |
print_final_schedule_for_user(schedule_data, name) | |
else: | |
print("Failed to fetch schedule data.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment