blob: 1f20a88fca7d019ce74c2b5730ff28f1ba67ab01 [file] [log] [blame]
Philip Zeyliger9e3c8672025-05-27 17:09:14 +00001#!/usr/bin/env python3
2import json
3import os
4import subprocess
5import sys
6import urllib.request
7from datetime import datetime, timezone
8
9def validate_environment():
10 """Validate required environment variables."""
11 if os.environ.get('CI') != '1':
12 print("Error: CI environment variable must be set to '1'")
13 sys.exit(1)
14
15 if not os.environ.get('GITHUB_SHA'):
16 print("Error: GITHUB_SHA environment variable is required")
17 sys.exit(1)
18
19 if not os.environ.get('GITHUB_REPOSITORY'):
20 print("Error: GITHUB_REPOSITORY environment variable is required")
21 sys.exit(1)
22
23 if not os.environ.get('DISCORD_WEBHOOK_FOR_COMMITS'):
24 print("Error: DISCORD_WEBHOOK_FOR_COMMITS environment variable is required")
25 sys.exit(1)
26
27def get_commit_info():
28 """Extract commit information using git commands."""
29 try:
30 # Get commit message (subject line)
31 commit_message = subprocess.check_output(
32 ['git', 'log', '-1', '--pretty=format:%s'],
33 text=True, stderr=subprocess.DEVNULL
34 ).strip()
35
36 # Get commit author
37 commit_author = subprocess.check_output(
38 ['git', 'log', '-1', '--pretty=format:%an'],
39 text=True, stderr=subprocess.DEVNULL
40 ).strip()
41
42 return commit_message, commit_author
43 except subprocess.CalledProcessError as e:
44 print(f"Failed to get commit information: {e}")
45 sys.exit(1)
46
47def main():
48 # Validate we're running in the correct environment
49 validate_environment()
50
51 # Check for test mode
52 if os.environ.get('DISCORD_TEST_MODE') == '1':
53 print("Running in test mode - will not send actual webhook")
54
55 # Get commit information from git
56 commit_message, commit_author = get_commit_info()
57
58 # Get remaining info from environment
59 github_sha = os.environ.get('GITHUB_SHA')
60 commit_sha = github_sha[:8]
61 commit_url = f"https://github.com/{os.environ.get('GITHUB_REPOSITORY')}/commit/{github_sha}"
62
63 # Create timestamp
64 timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%S.%fZ')[:-3] + 'Z'
65
66 # Create Discord webhook payload
67 payload = {
68 "embeds": [
69 {
70 "title": "New commit to main",
71 "description": f"**{commit_message}**",
72 "color": 5814783,
73 "fields": [
74 {
75 "name": "Author",
76 "value": commit_author,
77 "inline": True
78 },
79 {
80 "name": "Commit",
81 "value": f"[{commit_sha}]({commit_url})",
82 "inline": True
83 },
84 {
85 "name": "Repository",
86 "value": os.environ.get('GITHUB_REPOSITORY'),
87 "inline": True
88 }
89 ],
90 "timestamp": timestamp
91 }
92 ]
93 }
94
95 # Convert to JSON
96 json_payload = json.dumps(payload)
97
98 # Test mode - just print the payload
99 if os.environ.get('DISCORD_TEST_MODE') == '1':
100 print("Generated Discord payload:")
101 print(json.dumps(payload, indent=2))
102 print("✓ Test mode: payload generated successfully")
103 return
104
105 # Send to Discord webhook
106 webhook_url = os.environ.get('DISCORD_WEBHOOK_FOR_COMMITS')
107
108 req = urllib.request.Request(
109 webhook_url,
110 data=json_payload.encode('utf-8'),
111 headers={'Content-Type': 'application/json'}
112 )
113
114 try:
115 with urllib.request.urlopen(req) as response:
116 if response.status == 204:
117 print("Discord notification sent successfully")
118 else:
119 print(f"Discord webhook returned status: {response.status}")
120 sys.exit(1)
121 except urllib.error.HTTPError as e:
122 print(f"Discord webhook HTTP error: {e.code} - {e.reason}")
123 try:
124 error_body = e.read().decode('utf-8')
125 print(f"Error details: {error_body}")
126 if e.code == 403 and 'error code: 1010' in error_body:
127 print("Error 1010: Webhook not found - the Discord webhook URL may be invalid or expired")
128 except:
129 pass
130 sys.exit(1)
131 except Exception as e:
132 print(f"Failed to send Discord notification: {e}")
133 sys.exit(1)
134
135if __name__ == "__main__":
136 main()