diff --git a/discord_webhook.py b/discord_webhook.py new file mode 100644 index 0000000..52753b2 --- /dev/null +++ b/discord_webhook.py @@ -0,0 +1,69 @@ +from discord import Webhook, Embed, Colour +import aiohttp +import os +import logging +import re +from datetime import datetime + +async def send_message(**kwargs): + instance_data = { + "start_timestamp": None, + "end_timestamp": None, + "instance_id": None, + "world_name": None, + "member_count": None, + "thumbnail_url": None + } + for key, value in kwargs.items(): + if key in instance_data: + instance_data[key] = value + + + if instance_data["instance_id"] is not None: + # convert full group instance ID to regular digits + match = re.match(r'^\d+(?=~)', instance_data["instance_id"]) + + if match: + instance_id = match.group(0) + else: + raise ValueError("Invalid instance_id format") + else: + raise ValueError("instance_id is required") + + # validate timestamps are datetime and make them strings + if isinstance(instance_data["start_timestamp"], datetime) and isinstance(instance_data["end_timestamp"], datetime): + start_timestamp = instance_data["start_timestamp"].strftime("%Y-%m-%d %H:%M:%S UTC") + end_timestamp = instance_data["end_timestamp"].strftime("%Y-%m-%d %H:%M:%S UTC") + else: + raise ValueError("Timestamps are not in a datetime format") + + # other vars are strings and don't need validation + world_name = instance_data["world_name"] + member_count = instance_data["member_count"] + thumbnail_url = instance_data["thumbnail_url"] + + + embed = Embed( + colour = Colour.blurple(), + description = f"**Started**: {start_timestamp} \n" + f"**Ended**: {end_timestamp} \n" + f"**Member Count (highest)**: {member_count}", + title = f"Group Instance {instance_id} - {world_name}", + ) + + # Set a thumbnail if it's available + if thumbnail_url is not None: + embed.set_thumbnail(url=thumbnail_url) + + async with aiohttp.ClientSession() as session: + webhook_url = os.getenv("DISCORD_WEBHOOK") + if not webhook_url: + raise ValueError("DISCORD_WEBHOOK env variable not found") + + webhook = Webhook.from_url(webhook_url, session=session) + try: + await webhook.send(username='Group Instance Logger', embed=embed) + return True + except Exception as e: + logging.error(f"Exception sending webhook message: {e}") + return False \ No newline at end of file