-
Notifications
You must be signed in to change notification settings - Fork 0
feat(webhooks): webhook notification module for score delivery #58
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| """Webhook notification module — send score results to external services. | ||
|
|
||
| Supports Slack (Block Kit) and Discord (embeds) with auto-detection from URL. | ||
| Optional HMAC-SHA256 signing for payload verification. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import hashlib | ||
| import hmac | ||
| import json | ||
| import urllib.request | ||
| import urllib.error | ||
| from dataclasses import asdict, dataclass, field | ||
| from datetime import datetime, timezone | ||
|
|
||
|
|
||
| @dataclass | ||
| class WebhookPayload: | ||
| """Score result payload for webhook delivery.""" | ||
|
|
||
| repo: str | ||
| score: float | ||
| grade: str | ||
| findings: int | ||
| loc: int | ||
| timestamp: str | ||
| dimensions: dict = field(default_factory=dict) | ||
| url: str = "" | ||
|
|
||
| def to_json(self) -> str: | ||
| """Serialize to JSON string.""" | ||
| return json.dumps(asdict(self), indent=2) | ||
|
|
||
| def to_dict(self) -> dict: | ||
| """Serialize to plain dict.""" | ||
| return asdict(self) | ||
|
|
||
|
|
||
| def _grade_emoji(grade: str) -> str: | ||
| """Map letter grade to emoji for chat formatting.""" | ||
| return { | ||
| "A+": "\u2b50", "A": "\u2705", "A-": "\u2705", | ||
| "B+": "\U0001f7e2", "B": "\U0001f7e2", "B-": "\U0001f7e1", | ||
| "C+": "\U0001f7e1", "C": "\U0001f7e0", "C-": "\U0001f7e0", | ||
| "D": "\U0001f534", "F": "\u274c", "N/A": "\u2753", | ||
| }.get(grade, "\u2753") | ||
|
|
||
|
|
||
| def _grade_color(grade: str) -> int: | ||
| """Map letter grade to Discord embed color (decimal).""" | ||
| if grade.startswith("A"): | ||
| return 0x2ECC71 # green | ||
| if grade.startswith("B"): | ||
| return 0x3498DB # blue | ||
| if grade.startswith("C"): | ||
| return 0xF39C12 # orange | ||
| return 0xE74C3C # red | ||
|
|
||
|
|
||
| def format_slack(payload: WebhookPayload) -> dict: | ||
| """Format payload as Slack Block Kit message.""" | ||
| emoji = _grade_emoji(payload.grade) | ||
| dims = payload.dimensions | ||
| dim_parts = [f"*{k.title()}*: {v}" for k, v in dims.items()] if dims else [] | ||
| dim_text = " | ".join(dim_parts) if dim_parts else "No dimension breakdown" | ||
|
|
||
| blocks = [ | ||
| { | ||
| "type": "header", | ||
| "text": { | ||
| "type": "plain_text", | ||
| "text": f"{emoji} Arbiter Score: {payload.repo}", | ||
| }, | ||
| }, | ||
| { | ||
| "type": "section", | ||
| "fields": [ | ||
| {"type": "mrkdwn", "text": f"*Score:* {payload.score:.1f}"}, | ||
| {"type": "mrkdwn", "text": f"*Grade:* {payload.grade}"}, | ||
| {"type": "mrkdwn", "text": f"*Findings:* {payload.findings:,}"}, | ||
| {"type": "mrkdwn", "text": f"*LOC:* {payload.loc:,}"}, | ||
| ], | ||
| }, | ||
| { | ||
| "type": "section", | ||
| "text": {"type": "mrkdwn", "text": dim_text}, | ||
| }, | ||
| { | ||
| "type": "context", | ||
| "elements": [ | ||
| {"type": "mrkdwn", "text": f"Scored at {payload.timestamp} by Arbiter"}, | ||
| ], | ||
| }, | ||
| ] | ||
|
|
||
| if payload.url: | ||
| blocks.insert( | ||
| -1, | ||
| { | ||
| "type": "section", | ||
| "text": {"type": "mrkdwn", "text": f"<{payload.url}|View Repository>"}, | ||
| }, | ||
| ) | ||
|
|
||
| return {"blocks": blocks} | ||
|
|
||
|
|
||
| def format_discord(payload: WebhookPayload) -> dict: | ||
| """Format payload as Discord embed.""" | ||
| emoji = _grade_emoji(payload.grade) | ||
| color = _grade_color(payload.grade) | ||
|
|
||
| fields = [ | ||
| {"name": "Score", "value": f"{payload.score:.1f}", "inline": True}, | ||
| {"name": "Grade", "value": f"{emoji} {payload.grade}", "inline": True}, | ||
| {"name": "Findings", "value": f"{payload.findings:,}", "inline": True}, | ||
| {"name": "LOC", "value": f"{payload.loc:,}", "inline": True}, | ||
| ] | ||
|
|
||
| for k, v in payload.dimensions.items(): | ||
| fields.append({"name": k.title(), "value": str(v), "inline": True}) | ||
|
|
||
| embed: dict = { | ||
| "title": f"Arbiter Score: {payload.repo}", | ||
| "color": color, | ||
| "fields": fields, | ||
| "footer": {"text": f"Scored at {payload.timestamp} by Arbiter"}, | ||
| } | ||
|
|
||
| if payload.url: | ||
| embed["url"] = payload.url | ||
|
|
||
| return {"embeds": [embed]} | ||
|
|
||
|
|
||
| def detect_format(url: str) -> str: | ||
| """Auto-detect webhook service from URL pattern. | ||
|
|
||
| Returns 'slack', 'discord', or 'generic'. | ||
| """ | ||
| if "hooks.slack.com" in url or "slack.com/api" in url: | ||
| return "slack" | ||
| if "discord.com/api/webhooks" in url or "discordapp.com/api/webhooks" in url: | ||
| return "discord" | ||
| return "generic" | ||
|
|
||
|
|
||
| def _sign_payload(body: bytes, secret: str) -> str: | ||
| """Compute HMAC-SHA256 signature for the payload body.""" | ||
| return hmac.new(secret.encode("utf-8"), body, hashlib.sha256).hexdigest() | ||
|
|
||
|
|
||
| def send_webhook(url: str, payload: WebhookPayload, secret: str = "") -> bool: | ||
| """Send score notification to a webhook URL. | ||
|
|
||
| Auto-detects Slack vs Discord from URL and formats accordingly. | ||
| Returns True on success, False on any failure. Never raises. | ||
| """ | ||
| try: | ||
| fmt = detect_format(url) | ||
| if fmt == "slack": | ||
| data = format_slack(payload) | ||
| elif fmt == "discord": | ||
| data = format_discord(payload) | ||
| else: | ||
| data = payload.to_dict() | ||
|
|
||
| body = json.dumps(data).encode("utf-8") | ||
|
|
||
| headers = {"Content-Type": "application/json"} | ||
| if secret: | ||
| headers["X-Arbiter-Signature"] = _sign_payload(body, secret) | ||
|
|
||
| req = urllib.request.Request(url, data=body, headers=headers, method="POST") | ||
| with urllib.request.urlopen(req, timeout=10) as resp: | ||
| return resp.status < 400 | ||
| except Exception: | ||
| return False |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
webhook-test --formatflag is documented as a forced format, but in non---dry-runmode the code always callssend_webhook(args.url, ...), which re-detects format from URL and ignores the user-provided override; this breaks testing for Slack/Discord payloads on custom domains (or tunneled endpoints) and can print a misleading success message with the requested format even when a different payload was sent.Useful? React with 👍 / 👎.