This commit is contained in:
Slipstream 2025-06-05 15:58:37 -06:00
commit a151890ee9
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -1,6 +1,6 @@
import discord
from discord.ext import commands, tasks
from discord import ui
from discord import ui, AllowedMentions
import datetime
import asyncio
import aiohttp # Added for webhook sending
@ -203,6 +203,7 @@ class LoggingCog(commands.Cog):
view=embed,
username=f"{self.bot.user.name} Logs",
avatar_url=self.bot.user.display_avatar.url,
allowed_mentions=AllowedMentions.none(),
)
# log.debug(f"Sent log embed via webhook for guild {guild.id}") # Can be noisy
except ValueError as e:
@ -285,10 +286,16 @@ class LoggingCog(commands.Cog):
# 1. Check bot permissions
if not channel.permissions_for(me).manage_webhooks:
await ctx.send(f"❌ I don't have the 'Manage Webhooks' permission in {channel.mention}. Please grant it and try again.")
await ctx.send(
f"❌ I don't have the 'Manage Webhooks' permission in {channel.mention}. Please grant it and try again.",
allowed_mentions=AllowedMentions.none(),
)
return
if not channel.permissions_for(me).send_messages:
await ctx.send(f"❌ I don't have the 'Send Messages' permission in {channel.mention}. Please grant it and try again (needed for webhook creation confirmation).")
await ctx.send(
f"❌ I don't have the 'Send Messages' permission in {channel.mention}. Please grant it and try again (needed for webhook creation confirmation).",
allowed_mentions=AllowedMentions.none(),
)
return
# 2. Check existing webhook setting
@ -299,15 +306,27 @@ class LoggingCog(commands.Cog):
if not self.session or self.session.closed: self.session = aiohttp.ClientSession() # Ensure session exists
existing_webhook = await discord.Webhook.from_url(existing_url, session=self.session).fetch()
if existing_webhook.channel_id == channel.id:
await ctx.send(f"✅ Logging is already configured for {channel.mention} using webhook `{existing_webhook.name}`.")
await ctx.send(
f"✅ Logging is already configured for {channel.mention} using webhook `{existing_webhook.name}`.",
allowed_mentions=AllowedMentions.none(),
)
return
else:
await ctx.send(f"⚠️ Logging webhook is currently set for a different channel (<#{existing_webhook.channel_id}>). I will create a new one for {channel.mention}.")
await ctx.send(
f"⚠️ Logging webhook is currently set for a different channel (<#{existing_webhook.channel_id}>). I will create a new one for {channel.mention}.",
allowed_mentions=AllowedMentions.none(),
)
except (discord.NotFound, discord.Forbidden, ValueError, aiohttp.ClientError):
await ctx.send(f"⚠️ Could not verify the existing webhook URL. It might be invalid or deleted. I will create a new one for {channel.mention}.")
await ctx.send(
f"⚠️ Could not verify the existing webhook URL. It might be invalid or deleted. I will create a new one for {channel.mention}.",
allowed_mentions=AllowedMentions.none(),
)
except Exception as e:
log.exception(f"Error fetching existing webhook during setup for guild {guild.id}")
await ctx.send(f"⚠️ An error occurred while checking the existing webhook. Proceeding to create a new one for {channel.mention}.")
await ctx.send(
f"⚠️ An error occurred while checking the existing webhook. Proceeding to create a new one for {channel.mention}.",
allowed_mentions=AllowedMentions.none(),
)
# 3. Create new webhook
@ -324,17 +343,26 @@ class LoggingCog(commands.Cog):
log.info(f"Created logging webhook '{webhook_name}' in channel {channel.id} for guild {guild.id}")
except discord.HTTPException as e:
log.error(f"Failed to create webhook in {channel.mention} for guild {guild.id}: {e}")
await ctx.send(f"❌ Failed to create webhook. Error: {e}. This could be due to hitting the channel webhook limit (15).")
await ctx.send(
f"❌ Failed to create webhook. Error: {e}. This could be due to hitting the channel webhook limit (15).",
allowed_mentions=AllowedMentions.none(),
)
return
except Exception as e:
log.exception(f"Unexpected error creating webhook in {channel.mention} for guild {guild.id}")
await ctx.send("❌ An unexpected error occurred while creating the webhook.")
await ctx.send(
"❌ An unexpected error occurred while creating the webhook.",
allowed_mentions=AllowedMentions.none(),
)
return
# 4. Save webhook URL
success = await settings_manager.set_logging_webhook(guild.id, new_webhook.url)
if success:
await ctx.send(f"✅ Successfully configured logging to send messages to {channel.mention} via the new webhook `{new_webhook.name}`.")
await ctx.send(
f"✅ Successfully configured logging to send messages to {channel.mention} via the new webhook `{new_webhook.name}`.",
allowed_mentions=AllowedMentions.none(),
)
# Test send (optional)
try:
test_view = self._create_log_embed(
@ -346,13 +374,20 @@ class LoggingCog(commands.Cog):
view=test_view,
username=webhook_name,
avatar_url=self.bot.user.display_avatar.url,
allowed_mentions=AllowedMentions.none(),
)
except Exception as e:
log.error(f"Failed to send test message via new webhook for guild {guild.id}: {e}")
await ctx.send("⚠️ Could not send a test message via the new webhook, but the URL has been saved.")
await ctx.send(
"⚠️ Could not send a test message via the new webhook, but the URL has been saved.",
allowed_mentions=AllowedMentions.none(),
)
else:
log.error(f"Failed to save webhook URL {new_webhook.url} to database for guild {guild.id}")
await ctx.send("❌ Successfully created the webhook, but failed to save its URL to my settings. Please try again or contact support.")
await ctx.send(
"❌ Successfully created the webhook, but failed to save its URL to my settings. Please try again or contact support.",
allowed_mentions=AllowedMentions.none(),
)
# Attempt to delete the created webhook to avoid orphans
try:
await new_webhook.delete(reason="Failed to save URL to settings")
@ -374,7 +409,10 @@ class LoggingCog(commands.Cog):
event_key = event_key.lower() # Ensure case-insensitivity
if event_key not in ALL_EVENT_KEYS:
await ctx.send(f"❌ Invalid event key: `{event_key}`. Use `{ctx.prefix}log list_keys` to see valid keys.")
await ctx.send(
f"❌ Invalid event key: `{event_key}`. Use `{ctx.prefix}log list_keys` to see valid keys.",
allowed_mentions=AllowedMentions.none(),
)
return
# Determine the new status
@ -390,9 +428,15 @@ class LoggingCog(commands.Cog):
if success:
status_str = "ENABLED" if new_status else "DISABLED"
await ctx.send(f"✅ Logging for event `{event_key}` is now **{status_str}**.")
await ctx.send(
f"✅ Logging for event `{event_key}` is now **{status_str}**.",
allowed_mentions=AllowedMentions.none(),
)
else:
await ctx.send(f"❌ Failed to update setting for event `{event_key}`. Please check logs or try again.")
await ctx.send(
f"❌ Failed to update setting for event `{event_key}`. Please check logs or try again.",
allowed_mentions=AllowedMentions.none(),
)
@log_group.command(name="status")
@commands.has_permissions(administrator=True)
@ -414,7 +458,7 @@ class LoggingCog(commands.Cog):
for line in lines:
if len(description) + len(line) + 1 > 4000: # Embed description limit (approx)
embed.description = description
await ctx.send(embed=embed)
await ctx.send(embed=embed, allowed_mentions=AllowedMentions.none())
description = line + "\n" # Start new description
embed = discord.Embed(color=discord.Color.blue()) # New embed for continuation
else:
@ -422,7 +466,7 @@ class LoggingCog(commands.Cog):
if description: # Send the last embed page
embed.description = description.strip()
await ctx.send(embed=embed)
await ctx.send(embed=embed, allowed_mentions=AllowedMentions.none())
@log_group.command(name="list_keys")
@ -446,12 +490,15 @@ class LoggingCog(commands.Cog):
parts.append(current_part)
embed.description = parts[0]
await ctx.send(embed=embed)
await ctx.send(embed=embed, allowed_mentions=AllowedMentions.none())
for part in parts[1:]:
await ctx.send(embed=discord.Embed(description=part, color=discord.Color.purple()))
await ctx.send(
embed=discord.Embed(description=part, color=discord.Color.purple()),
allowed_mentions=AllowedMentions.none(),
)
else:
embed.description = keys_text
await ctx.send(embed=embed)
await ctx.send(embed=embed, allowed_mentions=AllowedMentions.none())
# --- Thread Events ---