This commit is contained in:
Slipstream 2025-05-13 07:39:54 -06:00
parent d94cea9c0c
commit f341ea0aa7
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -293,11 +293,11 @@ def format_github_issues_embed(payload: Dict[str, Any], repo_url: str) -> discor
color=color
)
embed.set_author(name=user_login, url=user_url, icon_url=user_avatar)
if issue_data.get('body') and action == "opened":
body = issue_data['body']
embed.add_field(name="Description", value=body[:1020] + "..." if len(body) > 1024 else body, inline=False)
if issue_data.get('labels'):
labels = ", ".join([f"`{label['name']}`" for label in issue_data['labels']])
embed.add_field(name="Labels", value=labels if labels else "None", inline=True)
@ -339,7 +339,7 @@ def format_github_pull_request_embed(payload: Dict[str, Any], repo_url: str) ->
description = f"Pull Request #{pr_number} in `{repo_name}` was {action}."
if action == "closed" and pr_data.get('merged'):
description = f"Pull Request #{pr_number} in `{repo_name}` was merged."
embed = discord.Embed(
title=f"PR {action.capitalize()}: #{pr_number} {title}",
url=pr_url,
@ -351,7 +351,7 @@ def format_github_pull_request_embed(payload: Dict[str, Any], repo_url: str) ->
if pr_data.get('body') and action == "opened":
body = pr_data['body']
embed.add_field(name="Description", value=body[:1020] + "..." if len(body) > 1024 else body, inline=False)
embed.add_field(name="Base Branch", value=f"`{pr_data.get('base', {}).get('ref', 'N/A')}`", inline=True)
embed.add_field(name="Head Branch", value=f"`{pr_data.get('head', {}).get('ref', 'N/A')}`", inline=True)
@ -396,7 +396,7 @@ def format_github_release_embed(payload: Dict[str, Any], repo_url: str) -> disco
if release_data.get('body'):
body = release_data['body']
embed.add_field(name="Release Notes", value=body[:1020] + "..." if len(body) > 1024 else body, inline=False)
return embed
except Exception as e:
log.error(f"Error formatting GitHub release embed: {e}\nPayload: {payload}")
@ -415,7 +415,7 @@ def format_github_issue_comment_embed(payload: Dict[str, Any], repo_url: str) ->
user_login = sender.get('login', 'Unknown User')
user_url = sender.get('html_url', '#')
user_avatar = sender.get('avatar_url')
issue_title = issue_data.get('title', 'Untitled Issue')
issue_number = issue_data.get('number')
@ -431,7 +431,7 @@ def format_github_issue_comment_embed(payload: Dict[str, Any], repo_url: str) ->
if comment_data.get('body'):
body = comment_data['body']
embed.description = body[:2040] + "..." if len(body) > 2048 else body
return embed
except Exception as e:
log.error(f"Error formatting GitHub issue_comment embed: {e}\nPayload: {payload}")
@ -458,7 +458,7 @@ def format_gitlab_issue_embed(payload: Dict[str, Any], repo_url: str) -> discord
discord.Color.red() if action == "close" else \
discord.Color.gold() if action == "reopen" else \
discord.Color.light_grey()
embed = discord.Embed(
title=f"Issue {action.capitalize()}: #{issue_iid} {title}",
url=issue_url,
@ -474,7 +474,7 @@ def format_gitlab_issue_embed(payload: Dict[str, Any], repo_url: str) -> discord
if attributes.get('labels'):
labels = ", ".join([f"`{label['title']}`" for label in attributes['labels']])
embed.add_field(name="Labels", value=labels if labels else "None", inline=True)
assignees_data = payload.get('assignees', [])
if assignees_data:
assignees = ", ".join([f"{a['name']}" for a in assignees_data])
@ -525,7 +525,7 @@ def format_gitlab_merge_request_embed(payload: Dict[str, Any], repo_url: str) ->
embed.add_field(name="Source Branch", value=f"`{attributes.get('source_branch', 'N/A')}`", inline=True)
embed.add_field(name="Target Branch", value=f"`{attributes.get('target_branch', 'N/A')}`", inline=True)
if action == "merge" and attributes.get('merge_commit_sha'):
embed.add_field(name="Merge Commit", value=f"`{attributes['merge_commit_sha'][:8]}`", inline=True)
@ -560,7 +560,7 @@ def format_gitlab_release_embed(payload: Dict[str, Any], repo_url: str) -> disco
if payload.get('description'):
desc = payload['description']
embed.add_field(name="Release Notes", value=desc[:1020] + "..." if len(desc) > 1024 else desc, inline=False)
return embed
except Exception as e:
log.error(f"Error formatting GitLab release embed: {e}\nPayload: {payload}")
@ -597,7 +597,7 @@ def format_gitlab_note_embed(payload: Dict[str, Any], repo_url: str) -> discord.
snippet_data = payload.get('snippet', {})
title_prefix = f"Comment on Snippet #{snippet_data.get('id', 'N/A')}"
target_info = snippet_data.get('title', '')
embed = discord.Embed(
title=f"{title_prefix}: {target_info}".strip(),
url=note_url,
@ -608,7 +608,7 @@ def format_gitlab_note_embed(payload: Dict[str, Any], repo_url: str) -> discord.
if attributes.get('note'):
note_body = attributes['note']
embed.description = note_body[:2040] + "..." if len(note_body) > 2048 else note_body
embed.set_footer(text=f"Comment in {repo_name}")
return embed
except Exception as e:
@ -694,7 +694,7 @@ async def webhook_github(
notification_channel_id = repo_config['notification_channel_id']
# Convert embed to dict for sending via API
message_content = {"embeds": [discord_embed.to_dict()]}
send_payload_dict = {"embeds": [discord_embed.to_dict()]}
# Use the send_discord_message_via_api from api_server.py
# This requires DISCORD_BOT_TOKEN to be set in the environment for api_server
@ -703,42 +703,10 @@ async def webhook_github(
# Still return 200 to GitHub to acknowledge receipt, but log error.
return {"status": "error", "message": "Notification sending failed (bot token not configured)."}
send_result = await send_discord_message_via_api(
channel_id=notification_channel_id,
content=json.dumps(message_content) # send_discord_message_via_api expects a string for 'content'
# but it should handle dicts with 'embeds' if modified or we send raw.
# For now, let's assume it needs a simple string or we adapt it.
# The current send_discord_message_via_api sends 'content' as a top-level string.
# We need to send an embed.
)
# The send_discord_message_via_api needs to be adapted to send embeds.
# For now, let's construct the data for the POST request directly as it would expect.
# Corrected way to send embed using the existing send_discord_message_via_api structure
# The function expects a simple string content. We need to modify it or use aiohttp directly here.
# Let's assume we'll modify send_discord_message_via_api later or use a more direct aiohttp call.
# For now, this will likely fail to send an embed correctly with the current send_discord_message_via_api.
# This is a placeholder for correct embed sending.
# To send an embed, the JSON body to Discord API should be like:
# { "embeds": [ { ... embed object ... } ] }
# The current `send_discord_message_via_api` sends `{"content": "message"}`.
# This part needs careful implementation.
# For now, let's log what would be sent.
log.info(f"Prepared to send GitHub notification to channel {notification_channel_id} for repo {repo_db_id}.")
# Actual sending logic will be refined.
# Placeholder for actual sending:
# For a quick test, we can try to send a simple text message.
# simple_text = f"New push to {repo_config['repository_url']}. Commits: {len(payload.get('commits', []))}"
# send_result = await send_discord_message_via_api(notification_channel_id, simple_text)
# If send_discord_message_via_api is adapted to handle embeds in its 'content' (e.g. by checking if it's a dict with 'embeds' key)
# then the following would be more appropriate:
# This requires send_discord_message_via_api to be flexible.
send_payload_dict = {"embeds": [discord_embed.to_dict()]}
log.info(f"Sending GitHub notification to channel {notification_channel_id} for repo {repo_db_id}.")
# Send the embed using the send_discord_message_via_api function
# The function can handle dict content with embeds
send_result = await send_discord_message_via_api(
channel_id=notification_channel_id,
content=send_payload_dict # Pass the dict directly
@ -794,13 +762,13 @@ async def webhook_gitlab(
# The payload's object_kind is often more specific: 'push', 'tag_push', 'issue', 'merge_request'.
# We should aim to match against object_kind primarily.
# Let's simplify: if 'push' is in allowed_events, we'll accept 'push' and 'tag_push' object_kinds.
effective_event_type = event_type
if event_type == "tag_push" and "push" in allowed_events and "tag_push" not in allowed_events:
# If only "push" is allowed, but we receive "tag_push", treat it as a push for now.
# This logic might need refinement based on how granular the user wants control.
pass # It will be caught by the 'push' check if 'push' is allowed.
is_event_allowed = False
if event_type in allowed_events:
is_event_allowed = True
@ -848,13 +816,19 @@ async def webhook_gitlab(
notification_channel_id = repo_config['notification_channel_id']
# Similar to GitHub, sending embed needs careful handling with send_discord_message_via_api
# Use the send_discord_message_via_api from api_server.py
# This requires DISCORD_BOT_TOKEN to be set in the environment for api_server
if not api_settings.DISCORD_BOT_TOKEN:
log.error("DISCORD_BOT_TOKEN not configured in API settings. Cannot send webhook notification.")
return {"status": "error", "message": "Notification sending failed (bot token not configured)."}
# Convert embed to dict for sending via API
send_payload_dict = {"embeds": [discord_embed.to_dict()]}
log.info(f"Sending GitLab notification to channel {notification_channel_id} for repo {repo_db_id}.")
# Send the embed using the send_discord_message_via_api function
# The function can handle dict content with embeds
send_result = await send_discord_message_via_api(
channel_id=notification_channel_id,
content=send_payload_dict # Pass the dict directly