refactor: Convert all cogs to use hybrid commands - Update birthday cog to use hybrid commands - Update overseerr cog to use hybrid commands - Update videoarchiver to use hybrid command group

This commit is contained in:
pacnpal
2024-11-15 01:19:03 +00:00
parent f5a76bbd11
commit e133fc6366
3 changed files with 182 additions and 177 deletions

View File

@@ -22,80 +22,80 @@ class Birthday(commands.Cog):
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
self.birthday_tasks = {} self.birthday_tasks = {}
@app_commands.command(name="setrole") @commands.hybrid_command(name="setrole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role="The role to set as the birthday role") @app_commands.describe(role="The role to set as the birthday role")
@checks.is_owner() @checks.is_owner()
async def set_role(self, interaction: discord.Interaction, role: discord.Role): async def set_role(self, ctx: commands.Context, role: discord.Role):
"""Set the birthday role.""" """Set the birthday role."""
await self.config.guild(interaction.guild).birthday_role.set(role.id) await self.config.guild(ctx.guild).birthday_role.set(role.id)
await interaction.response.send_message(f"Birthday role set to {role.name}") await ctx.send(f"Birthday role set to {role.name}")
@app_commands.command(name="settimezone") @commands.hybrid_command(name="settimezone")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(tz="The timezone for role expiration (e.g., UTC, America/New_York)") @app_commands.describe(tz="The timezone for role expiration (e.g., UTC, America/New_York)")
@checks.is_owner() @checks.is_owner()
async def set_timezone(self, interaction: discord.Interaction, tz: str): async def set_timezone(self, ctx: commands.Context, tz: str):
"""Set the timezone for the birthday role expiration.""" """Set the timezone for the birthday role expiration."""
try: try:
ZoneInfo(tz) ZoneInfo(tz)
await self.config.guild(interaction.guild).timezone.set(tz) await self.config.guild(ctx.guild).timezone.set(tz)
await interaction.response.send_message(f"Timezone set to {tz}") await ctx.send(f"Timezone set to {tz}")
except ZoneInfoNotFoundError: except ZoneInfoNotFoundError:
await interaction.response.send_message(f"Invalid timezone: {tz}. Please use a valid IANA time zone identifier.") await ctx.send(f"Invalid timezone: {tz}. Please use a valid IANA time zone identifier.")
@app_commands.command(name="setchannel") @commands.hybrid_command(name="setchannel")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The channel for birthday announcements") @app_commands.describe(channel="The channel for birthday announcements")
@checks.is_owner() @checks.is_owner()
async def set_channel(self, interaction: discord.Interaction, channel: discord.TextChannel): async def set_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the channel for birthday announcements.""" """Set the channel for birthday announcements."""
await self.config.guild(interaction.guild).birthday_channel.set(channel.id) await self.config.guild(ctx.guild).birthday_channel.set(channel.id)
await interaction.response.send_message(f"Birthday announcement channel set to {channel.mention}") await ctx.send(f"Birthday announcement channel set to {channel.mention}")
@app_commands.command(name="addrole") @commands.hybrid_command(name="addrole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role="The role to allow using the birthday command") @app_commands.describe(role="The role to allow using the birthday command")
async def add_allowed_role(self, interaction: discord.Interaction, role: discord.Role): async def add_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Add a role that can use the birthday command.""" """Add a role that can use the birthday command."""
async with self.config.guild(interaction.guild).allowed_roles() as allowed_roles: async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id not in allowed_roles: if role.id not in allowed_roles:
allowed_roles.append(role.id) allowed_roles.append(role.id)
await interaction.response.send_message(f"Added {role.name} to the list of roles that can use the birthday command.") await ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.")
@app_commands.command(name="removerole") @commands.hybrid_command(name="removerole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role="The role to remove from using the birthday command") @app_commands.describe(role="The role to remove from using the birthday command")
async def remove_allowed_role(self, interaction: discord.Interaction, role: discord.Role): async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Remove a role from using the birthday command.""" """Remove a role from using the birthday command."""
async with self.config.guild(interaction.guild).allowed_roles() as allowed_roles: async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles:
if role.id in allowed_roles: if role.id in allowed_roles:
allowed_roles.remove(role.id) allowed_roles.remove(role.id)
await interaction.response.send_message(f"Removed {role.name} from the list of roles that can use the birthday command.") await ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.")
@app_commands.command(name="birthday") @commands.hybrid_command(name="birthday")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(member="The member to give the birthday role to") @app_commands.describe(member="The member to give the birthday role to")
async def birthday(self, interaction: discord.Interaction, member: discord.Member): async def birthday(self, ctx: commands.Context, member: discord.Member):
"""Assign the birthday role to a user until midnight in the set timezone.""" """Assign the birthday role to a user until midnight in the set timezone."""
# Check if the user has permission to use this command # Check if the user has permission to use this command
allowed_roles = await self.config.guild(interaction.guild).allowed_roles() allowed_roles = await self.config.guild(ctx.guild).allowed_roles()
if not any(role.id in allowed_roles for role in interaction.user.roles): if not any(role.id in allowed_roles for role in ctx.author.roles):
return await interaction.response.send_message("You don't have permission to use this command.", ephemeral=True) return await ctx.send("You don't have permission to use this command.", ephemeral=True)
birthday_role_id = await self.config.guild(interaction.guild).birthday_role() birthday_role_id = await self.config.guild(ctx.guild).birthday_role()
if not birthday_role_id: if not birthday_role_id:
return await interaction.response.send_message("The birthday role hasn't been set. An admin needs to set it using `/setrole`.", ephemeral=True) return await ctx.send("The birthday role hasn't been set. An admin needs to set it using `/setrole`.", ephemeral=True)
birthday_role = interaction.guild.get_role(birthday_role_id) birthday_role = ctx.guild.get_role(birthday_role_id)
if not birthday_role: if not birthday_role:
return await interaction.response.send_message("The birthday role doesn't exist anymore. Please ask an admin to set it again.", ephemeral=True) return await ctx.send("The birthday role doesn't exist anymore. Please ask an admin to set it again.", ephemeral=True)
# Assign the role, ignoring hierarchy # Assign the role, ignoring hierarchy
try: try:
await member.add_roles(birthday_role, reason="Birthday role") await member.add_roles(birthday_role, reason="Birthday role")
except discord.Forbidden: except discord.Forbidden:
return await interaction.response.send_message("I don't have permission to assign that role.", ephemeral=True) return await ctx.send("I don't have permission to assign that role.", ephemeral=True)
# Generate birthday message with random cakes (or pie) # Generate birthday message with random cakes (or pie)
cakes = random.randint(0, 5) cakes = random.randint(0, 5)
@@ -105,55 +105,55 @@ class Birthday(commands.Cog):
message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes message = f"🎉 Happy Birthday, {member.mention}! Here's your cake{'s' if cakes > 1 else ''}: " + "🎂" * cakes
# Get the birthday announcement channel # Get the birthday announcement channel
birthday_channel_id = await self.config.guild(interaction.guild).birthday_channel() birthday_channel_id = await self.config.guild(ctx.guild).birthday_channel()
if birthday_channel_id: if birthday_channel_id:
channel = self.bot.get_channel(birthday_channel_id) channel = self.bot.get_channel(birthday_channel_id)
if not channel: # If the set channel doesn't exist anymore if not channel: # If the set channel doesn't exist anymore
channel = interaction.channel channel = ctx.channel
else: else:
channel = interaction.channel channel = ctx.channel
await channel.send(message) await channel.send(message)
await interaction.response.send_message("Birthday role assigned!", ephemeral=True) await ctx.send("Birthday role assigned!", ephemeral=True)
# Schedule role removal # Schedule role removal
timezone = await self.config.guild(interaction.guild).timezone() timezone = await self.config.guild(ctx.guild).timezone()
try: try:
tz = ZoneInfo(timezone) tz = ZoneInfo(timezone)
except ZoneInfoNotFoundError: except ZoneInfoNotFoundError:
await interaction.followup.send("Warning: Invalid timezone set. Defaulting to UTC.", ephemeral=True) await ctx.send("Warning: Invalid timezone set. Defaulting to UTC.", ephemeral=True)
tz = ZoneInfo("UTC") tz = ZoneInfo("UTC")
now = datetime.now(tz) now = datetime.now(tz)
midnight = datetime.combine(now.date() + timedelta(days=1), time.min).replace(tzinfo=tz) midnight = datetime.combine(now.date() + timedelta(days=1), time.min).replace(tzinfo=tz)
await self.schedule_birthday_role_removal(interaction.guild, member, birthday_role, midnight) await self.schedule_birthday_role_removal(ctx.guild, member, birthday_role, midnight)
@app_commands.command(name="bdaycheck") @commands.hybrid_command(name="bdaycheck")
@app_commands.guild_only() @app_commands.guild_only()
async def bdaycheck(self, interaction: discord.Interaction): async def bdaycheck(self, ctx: commands.Context):
"""Check the upcoming birthday role removal tasks.""" """Check the upcoming birthday role removal tasks."""
# Check if the user has permission to use this command # Check if the user has permission to use this command
allowed_roles = await self.config.guild(interaction.guild).allowed_roles() allowed_roles = await self.config.guild(ctx.guild).allowed_roles()
if not any(role.id in allowed_roles for role in interaction.user.roles): if not any(role.id in allowed_roles for role in ctx.author.roles):
return await interaction.response.send_message("You don't have permission to use this command.", ephemeral=True) return await ctx.send("You don't have permission to use this command.", ephemeral=True)
scheduled_tasks = await self.config.guild(interaction.guild).scheduled_tasks() scheduled_tasks = await self.config.guild(ctx.guild).scheduled_tasks()
if not scheduled_tasks: if not scheduled_tasks:
return await interaction.response.send_message("There are no scheduled tasks.", ephemeral=True) return await ctx.send("There are no scheduled tasks.", ephemeral=True)
message = "Upcoming birthday role removal tasks:\n" message = "Upcoming birthday role removal tasks:\n"
for member_id, task_info in scheduled_tasks.items(): for member_id, task_info in scheduled_tasks.items():
member = interaction.guild.get_member(int(member_id)) member = ctx.guild.get_member(int(member_id))
if not member: if not member:
continue continue
role = interaction.guild.get_role(task_info["role_id"]) role = ctx.guild.get_role(task_info["role_id"])
if not role: if not role:
continue continue
remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(interaction.guild).timezone())) remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(ctx.guild).timezone()))
message += f"- {member.display_name} ({member.id}): {role.name} will be removed at {remove_at}\n" message += f"- {member.display_name} ({member.id}): {role.name} will be removed at {remove_at}\n"
await interaction.response.send_message(message, ephemeral=True) await ctx.send(message, ephemeral=True)
async def schedule_birthday_role_removal(self, guild, member, role, when): async def schedule_birthday_role_removal(self, guild, member, role, when):
"""Schedule the removal of the birthday role.""" """Schedule the removal of the birthday role."""

View File

@@ -17,44 +17,44 @@ class Overseerr(commands.Cog):
} }
self.config.register_global(**default_global) self.config.register_global(**default_global)
@app_commands.command(name="seturl") @commands.hybrid_command(name="seturl")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(url="The URL of your Overseerr instance") @app_commands.describe(url="The URL of your Overseerr instance")
@commands.admin() @commands.admin()
async def set_url(self, interaction: discord.Interaction, url: str): async def set_url(self, ctx: commands.Context, url: str):
"""Set the Overseerr URL.""" """Set the Overseerr URL."""
url = url.rstrip('/') url = url.rstrip('/')
await self.config.overseerr_url.set(url) await self.config.overseerr_url.set(url)
await interaction.response.send_message(f"Overseerr URL set to: {url}") await ctx.send(f"Overseerr URL set to: {url}")
@app_commands.command(name="setapikey") @commands.hybrid_command(name="setapikey")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(api_key="Your Overseerr API key") @app_commands.describe(api_key="Your Overseerr API key")
@commands.admin() @commands.admin()
async def set_apikey(self, interaction: discord.Interaction, api_key: str): async def set_apikey(self, ctx: commands.Context, api_key: str):
"""Set the Overseerr API key.""" """Set the Overseerr API key."""
await self.config.overseerr_api_key.set(api_key) await self.config.overseerr_api_key.set(api_key)
await interaction.response.send_message("Overseerr API key has been set.") await ctx.send("Overseerr API key has been set.")
@app_commands.command(name="setadminrole") @commands.hybrid_command(name="setadminrole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role_name="The name of the admin role") @app_commands.describe(role_name="The name of the admin role")
@commands.admin() @commands.admin()
async def set_adminrole(self, interaction: discord.Interaction, role_name: str): async def set_adminrole(self, ctx: commands.Context, role_name: str):
"""Set the admin role name for Overseerr approvals.""" """Set the admin role name for Overseerr approvals."""
await self.config.admin_role_name.set(role_name) await self.config.admin_role_name.set(role_name)
await interaction.response.send_message(f"Admin role for Overseerr approvals set to: {role_name}") await ctx.send(f"Admin role for Overseerr approvals set to: {role_name}")
@app_commands.command(name="request") @commands.hybrid_command(name="request")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(query="The name of the movie or TV show to search for") @app_commands.describe(query="The name of the movie or TV show to search for")
async def request(self, interaction: discord.Interaction, query: str): async def request(self, ctx: commands.Context, query: str):
"""Search and request a movie or TV show on Overseerr.""" """Search and request a movie or TV show on Overseerr."""
overseerr_url = await self.config.overseerr_url() overseerr_url = await self.config.overseerr_url()
overseerr_api_key = await self.config.overseerr_api_key() overseerr_api_key = await self.config.overseerr_api_key()
if not overseerr_url or not overseerr_api_key: if not overseerr_url or not overseerr_api_key:
await interaction.response.send_message("Overseerr is not configured. Please ask an admin to set it up using `/seturl` and `/setapikey`.", ephemeral=True) await ctx.send("Overseerr is not configured. Please ask an admin to set it up using `/seturl` and `/setapikey`.", ephemeral=True)
return return
search_url = f"{overseerr_url}/api/v1/search" search_url = f"{overseerr_url}/api/v1/search"
@@ -63,27 +63,27 @@ class Overseerr(commands.Cog):
"Content-Type": "application/json" "Content-Type": "application/json"
} }
# Defer the response since this might take a while # Send initial response
await interaction.response.defer() initial_message = await ctx.send("Searching...")
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.get(search_url, headers=headers, params={"query": query}) as resp: async with session.get(search_url, headers=headers, params={"query": query}) as resp:
if resp.status != 200: if resp.status != 200:
await interaction.followup.send(f"Error from Overseerr API: {resp.status}", ephemeral=True) await initial_message.edit(content=f"Error from Overseerr API: {resp.status}")
return return
try: try:
search_results = await resp.json() search_results = await resp.json()
except Exception as e: except Exception as e:
await interaction.followup.send(f"Failed to parse JSON: {e}", ephemeral=True) await initial_message.edit(content=f"Failed to parse JSON: {e}")
return return
if 'results' not in search_results: if 'results' not in search_results:
await interaction.followup.send(f"No results found for '{query}'. API Response: {search_results}", ephemeral=True) await initial_message.edit(content=f"No results found for '{query}'. API Response: {search_results}")
return return
if not search_results['results']: if not search_results['results']:
await interaction.followup.send(f"No results found for '{query}'.", ephemeral=True) await initial_message.edit(content=f"No results found for '{query}'.")
return return
# Create select menu for results # Create select menu for results
@@ -114,6 +114,10 @@ class Overseerr(commands.Cog):
) )
async def select_callback(select_interaction: discord.Interaction): async def select_callback(select_interaction: discord.Interaction):
if select_interaction.user != ctx.author:
await select_interaction.response.send_message("This menu is not for you!", ephemeral=True)
return
selected_index = int(select_interaction.data['values'][0]) selected_index = int(select_interaction.data['values'][0])
selected_result = search_results['results'][selected_index] selected_result = search_results['results'][selected_index]
media_type = selected_result['mediaType'] media_type = selected_result['mediaType']
@@ -157,23 +161,23 @@ class Overseerr(commands.Cog):
select.callback = select_callback select.callback = select_callback
view = discord.ui.View() view = discord.ui.View()
view.add_item(select) view.add_item(select)
await interaction.followup.send("Search results:", view=view) await initial_message.edit(content="Search results:", view=view)
@app_commands.command(name="approve") @commands.hybrid_command(name="approve")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(request_id="The ID of the request to approve") @app_commands.describe(request_id="The ID of the request to approve")
async def approve(self, interaction: discord.Interaction, request_id: int): async def approve(self, ctx: commands.Context, request_id: int):
"""Approve a request on Overseerr.""" """Approve a request on Overseerr."""
admin_role_name = await self.config.admin_role_name() admin_role_name = await self.config.admin_role_name()
if not any(role.name == admin_role_name for role in interaction.user.roles): if not any(role.name == admin_role_name for role in ctx.author.roles):
await interaction.response.send_message(f"You need the '{admin_role_name}' role to approve requests.", ephemeral=True) await ctx.send(f"You need the '{admin_role_name}' role to approve requests.", ephemeral=True)
return return
overseerr_url = await self.config.overseerr_url() overseerr_url = await self.config.overseerr_url()
overseerr_api_key = await self.config.overseerr_api_key() overseerr_api_key = await self.config.overseerr_api_key()
if not overseerr_url or not overseerr_api_key: if not overseerr_url or not overseerr_api_key:
await interaction.response.send_message("Overseerr is not configured. Please ask an admin to set it up using `/seturl` and `/setapikey`.", ephemeral=True) await ctx.send("Overseerr is not configured. Please ask an admin to set it up using `/seturl` and `/setapikey`.", ephemeral=True)
return return
approve_url = f"{overseerr_url}/api/v1/request/{request_id}/approve" approve_url = f"{overseerr_url}/api/v1/request/{request_id}/approve"
@@ -185,9 +189,9 @@ class Overseerr(commands.Cog):
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
async with session.post(approve_url, headers=headers) as resp: async with session.post(approve_url, headers=headers) as resp:
if resp.status == 200: if resp.status == 200:
await interaction.response.send_message(f"Request {request_id} has been approved!") await ctx.send(f"Request {request_id} has been approved!")
else: else:
await interaction.response.send_message(f"Failed to approve request {request_id}. Please check the request ID and try again.", ephemeral=True) await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.", ephemeral=True)
async def get_media_status(self, media_id, media_type): async def get_media_status(self, media_id, media_type):
overseerr_url = await self.config.overseerr_url() overseerr_url = await self.config.overseerr_url()

View File

@@ -15,182 +15,183 @@ class VideoArchiverCommands(commands.Cog):
self.processor = processor self.processor = processor
super().__init__() super().__init__()
@app_commands.command(name="settings") @commands.hybrid_group(name="videoarchiver", aliases=["va"], fallback="settings")
@app_commands.guild_only() @app_commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def settings(self, interaction: discord.Interaction): async def videoarchiver(self, ctx: commands.Context):
"""Show VideoArchiver settings""" """Video Archiver configuration commands"""
embed = await self.config.format_settings_embed(interaction.guild) if ctx.invoked_subcommand is None:
await interaction.response.send_message(embed=embed) embed = await self.config.format_settings_embed(ctx.guild)
await ctx.send(embed=embed)
@app_commands.command(name="updateytdlp") @videoarchiver.command(name="updateytdlp")
@app_commands.guild_only() @app_commands.guild_only()
@checks.is_owner() @checks.is_owner()
async def update_ytdlp(self, interaction: discord.Interaction): async def update_ytdlp(self, ctx: commands.Context):
"""Update yt-dlp to the latest version""" """Update yt-dlp to the latest version"""
success, message = await self.update_checker.update_yt_dlp() success, message = await self.update_checker.update_yt_dlp()
await interaction.response.send_message("" + message if success else "" + message) await ctx.send("" + message if success else "" + message)
@app_commands.command(name="toggleupdates") @videoarchiver.command(name="toggleupdates")
@app_commands.guild_only() @app_commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def toggle_update_check(self, interaction: discord.Interaction): async def toggle_update_check(self, ctx: commands.Context):
"""Toggle yt-dlp update notifications""" """Toggle yt-dlp update notifications"""
state = await self.config.toggle_setting(interaction.guild.id, "disable_update_check") state = await self.config.toggle_setting(ctx.guild.id, "disable_update_check")
status = "disabled" if state else "enabled" status = "disabled" if state else "enabled"
await interaction.response.send_message(f"Update notifications {status}") await ctx.send(f"Update notifications {status}")
@app_commands.command(name="addrole") @videoarchiver.command(name="addrole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role="The role to allow (leave empty for @everyone)") @app_commands.describe(role="The role to allow (leave empty for @everyone)")
async def add_allowed_role(self, interaction: discord.Interaction, role: Optional[discord.Role] = None): async def add_allowed_role(self, ctx: commands.Context, role: Optional[discord.Role] = None):
"""Add a role that's allowed to trigger archiving""" """Add a role that's allowed to trigger archiving"""
if not role: if not role:
# If no role is specified, clear the list to allow everyone # If no role is specified, clear the list to allow everyone
await self.config.update_setting(interaction.guild.id, "allowed_roles", []) await self.config.update_setting(ctx.guild.id, "allowed_roles", [])
await interaction.response.send_message("Allowed role set to @everyone (all users can trigger archiving)") await ctx.send("Allowed role set to @everyone (all users can trigger archiving)")
return return
await self.config.add_to_list(interaction.guild.id, "allowed_roles", role.id) await self.config.add_to_list(ctx.guild.id, "allowed_roles", role.id)
await interaction.response.send_message(f"Added {role.name} to allowed roles") await ctx.send(f"Added {role.name} to allowed roles")
@app_commands.command(name="removerole") @videoarchiver.command(name="removerole")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(role="The role to remove") @app_commands.describe(role="The role to remove")
async def remove_allowed_role(self, interaction: discord.Interaction, role: discord.Role): async def remove_allowed_role(self, ctx: commands.Context, role: discord.Role):
"""Remove a role from allowed roles""" """Remove a role from allowed roles"""
await self.config.remove_from_list(interaction.guild.id, "allowed_roles", role.id) await self.config.remove_from_list(ctx.guild.id, "allowed_roles", role.id)
await interaction.response.send_message(f"Removed {role.name} from allowed roles") await ctx.send(f"Removed {role.name} from allowed roles")
@app_commands.command(name="listroles") @videoarchiver.command(name="listroles")
@app_commands.guild_only() @app_commands.guild_only()
async def list_allowed_roles(self, interaction: discord.Interaction): async def list_allowed_roles(self, ctx: commands.Context):
"""List all roles allowed to trigger archiving""" """List all roles allowed to trigger archiving"""
roles = await self.config.get_setting(interaction.guild.id, "allowed_roles") roles = await self.config.get_setting(ctx.guild.id, "allowed_roles")
if not roles: if not roles:
await interaction.response.send_message( await ctx.send(
"No roles are currently set (all users can trigger archiving)" "No roles are currently set (all users can trigger archiving)"
) )
return return
role_names = [ role_names = [
r.name if r else "@everyone" r.name if r else "@everyone"
for r in [interaction.guild.get_role(role_id) for role_id in roles] for r in [ctx.guild.get_role(role_id) for role_id in roles]
] ]
await interaction.response.send_message(f"Allowed roles: {', '.join(role_names)}") await ctx.send(f"Allowed roles: {', '.join(role_names)}")
@app_commands.command(name="setconcurrent") @videoarchiver.command(name="setconcurrent")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(count="Number of concurrent downloads (1-5)") @app_commands.describe(count="Number of concurrent downloads (1-5)")
async def set_concurrent_downloads(self, interaction: discord.Interaction, count: app_commands.Range[int, 1, 5]): async def set_concurrent_downloads(self, ctx: commands.Context, count: app_commands.Range[int, 1, 5]):
"""Set the number of concurrent downloads""" """Set the number of concurrent downloads"""
await self.config.update_setting(interaction.guild.id, "concurrent_downloads", count) await self.config.update_setting(ctx.guild.id, "concurrent_downloads", count)
await interaction.response.send_message(f"Concurrent downloads set to {count}") await ctx.send(f"Concurrent downloads set to {count}")
@app_commands.command(name="setchannel") @videoarchiver.command(name="setchannel")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The archive channel") @app_commands.describe(channel="The archive channel")
async def set_archive_channel(self, interaction: discord.Interaction, channel: discord.TextChannel): async def set_archive_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the archive channel""" """Set the archive channel"""
await self.config.update_setting(interaction.guild.id, "archive_channel", channel.id) await self.config.update_setting(ctx.guild.id, "archive_channel", channel.id)
await interaction.response.send_message(f"Archive channel set to {channel.mention}") await ctx.send(f"Archive channel set to {channel.mention}")
@app_commands.command(name="setnotification") @videoarchiver.command(name="setnotification")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The notification channel") @app_commands.describe(channel="The notification channel")
async def set_notification_channel(self, interaction: discord.Interaction, channel: discord.TextChannel): async def set_notification_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the notification channel (where archive messages appear)""" """Set the notification channel (where archive messages appear)"""
await self.config.update_setting( await self.config.update_setting(
interaction.guild.id, "notification_channel", channel.id ctx.guild.id, "notification_channel", channel.id
) )
await interaction.response.send_message(f"Notification channel set to {channel.mention}") await ctx.send(f"Notification channel set to {channel.mention}")
@app_commands.command(name="setlogchannel") @videoarchiver.command(name="setlogchannel")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The log channel") @app_commands.describe(channel="The log channel")
async def set_log_channel(self, interaction: discord.Interaction, channel: discord.TextChannel): async def set_log_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Set the log channel for error messages and notifications""" """Set the log channel for error messages and notifications"""
await self.config.update_setting(interaction.guild.id, "log_channel", channel.id) await self.config.update_setting(ctx.guild.id, "log_channel", channel.id)
await interaction.response.send_message(f"Log channel set to {channel.mention}") await ctx.send(f"Log channel set to {channel.mention}")
@app_commands.command(name="addmonitor") @videoarchiver.command(name="addmonitor")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The channel to monitor (leave empty to monitor all channels)") @app_commands.describe(channel="The channel to monitor (leave empty to monitor all channels)")
async def add_monitored_channel(self, interaction: discord.Interaction, channel: Optional[discord.TextChannel] = None): async def add_monitored_channel(self, ctx: commands.Context, channel: Optional[discord.TextChannel] = None):
"""Add a channel to monitor for videos""" """Add a channel to monitor for videos"""
if not channel: if not channel:
# If no channel is specified, clear the list to monitor all channels # If no channel is specified, clear the list to monitor all channels
await self.config.update_setting(interaction.guild.id, "monitored_channels", []) await self.config.update_setting(ctx.guild.id, "monitored_channels", [])
await interaction.response.send_message("Now monitoring all channels for videos") await ctx.send("Now monitoring all channels for videos")
return return
await self.config.add_to_list(interaction.guild.id, "monitored_channels", channel.id) await self.config.add_to_list(ctx.guild.id, "monitored_channels", channel.id)
await interaction.response.send_message(f"Now monitoring {channel.mention} for videos") await ctx.send(f"Now monitoring {channel.mention} for videos")
@app_commands.command(name="removemonitor") @videoarchiver.command(name="removemonitor")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(channel="The channel to stop monitoring") @app_commands.describe(channel="The channel to stop monitoring")
async def remove_monitored_channel(self, interaction: discord.Interaction, channel: discord.TextChannel): async def remove_monitored_channel(self, ctx: commands.Context, channel: discord.TextChannel):
"""Remove a channel from monitoring""" """Remove a channel from monitoring"""
await self.config.remove_from_list( await self.config.remove_from_list(
interaction.guild.id, "monitored_channels", channel.id ctx.guild.id, "monitored_channels", channel.id
) )
await interaction.response.send_message(f"Stopped monitoring {channel.mention}") await ctx.send(f"Stopped monitoring {channel.mention}")
@app_commands.command(name="setformat") @videoarchiver.command(name="setformat")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(format="The video format (e.g., mp4, webm)") @app_commands.describe(format="The video format (e.g., mp4, webm)")
async def set_video_format(self, interaction: discord.Interaction, format: Literal["mp4", "webm"]): async def set_video_format(self, ctx: commands.Context, format: Literal["mp4", "webm"]):
"""Set the video format""" """Set the video format"""
await self.config.update_setting(interaction.guild.id, "video_format", format.lower()) await self.config.update_setting(ctx.guild.id, "video_format", format.lower())
await interaction.response.send_message(f"Video format set to {format.lower()}") await ctx.send(f"Video format set to {format.lower()}")
@app_commands.command(name="setquality") @videoarchiver.command(name="setquality")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(quality="Maximum video quality in pixels (e.g., 1080)") @app_commands.describe(quality="Maximum video quality in pixels (e.g., 1080)")
async def set_video_quality(self, interaction: discord.Interaction, quality: app_commands.Range[int, 144, 4320]): async def set_video_quality(self, ctx: commands.Context, quality: app_commands.Range[int, 144, 4320]):
"""Set the maximum video quality""" """Set the maximum video quality"""
await self.config.update_setting(interaction.guild.id, "video_quality", quality) await self.config.update_setting(ctx.guild.id, "video_quality", quality)
await interaction.response.send_message(f"Maximum video quality set to {quality}p") await ctx.send(f"Maximum video quality set to {quality}p")
@app_commands.command(name="setmaxsize") @videoarchiver.command(name="setmaxsize")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(size="Maximum file size in MB") @app_commands.describe(size="Maximum file size in MB")
async def set_max_file_size(self, interaction: discord.Interaction, size: app_commands.Range[int, 1, 100]): async def set_max_file_size(self, ctx: commands.Context, size: app_commands.Range[int, 1, 100]):
"""Set the maximum file size""" """Set the maximum file size"""
await self.config.update_setting(interaction.guild.id, "max_file_size", size) await self.config.update_setting(ctx.guild.id, "max_file_size", size)
await interaction.response.send_message(f"Maximum file size set to {size}MB") await ctx.send(f"Maximum file size set to {size}MB")
@app_commands.command(name="toggledelete") @videoarchiver.command(name="toggledelete")
@app_commands.guild_only() @app_commands.guild_only()
async def toggle_delete_after_repost(self, interaction: discord.Interaction): async def toggle_delete_after_repost(self, ctx: commands.Context):
"""Toggle whether to delete local files after reposting""" """Toggle whether to delete local files after reposting"""
state = await self.config.toggle_setting(interaction.guild.id, "delete_after_repost") state = await self.config.toggle_setting(ctx.guild.id, "delete_after_repost")
await interaction.response.send_message(f"Delete after repost: {state}") await ctx.send(f"Delete after repost: {state}")
@app_commands.command(name="setduration") @videoarchiver.command(name="setduration")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(hours="Duration in hours (0 for permanent)") @app_commands.describe(hours="Duration in hours (0 for permanent)")
async def set_message_duration(self, interaction: discord.Interaction, hours: app_commands.Range[int, 0, 720]): async def set_message_duration(self, ctx: commands.Context, hours: app_commands.Range[int, 0, 720]):
"""Set how long to keep archive messages""" """Set how long to keep archive messages"""
await self.config.update_setting(interaction.guild.id, "message_duration", hours) await self.config.update_setting(ctx.guild.id, "message_duration", hours)
await interaction.response.send_message(f"Archive message duration set to {hours} hours") await ctx.send(f"Archive message duration set to {hours} hours")
@app_commands.command(name="settemplate") @videoarchiver.command(name="settemplate")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(template="Message template using {author}, {url}, and {original_message}") @app_commands.describe(template="Message template using {author}, {url}, and {original_message}")
async def set_message_template(self, interaction: discord.Interaction, template: str): async def set_message_template(self, ctx: commands.Context, template: str):
"""Set the archive message template""" """Set the archive message template"""
await self.config.update_setting(interaction.guild.id, "message_template", template) await self.config.update_setting(ctx.guild.id, "message_template", template)
await interaction.response.send_message(f"Archive message template set to:\n{template}") await ctx.send(f"Archive message template set to:\n{template}")
@app_commands.command(name="enablesites") @videoarchiver.command(name="enablesites")
@app_commands.guild_only() @app_commands.guild_only()
@app_commands.describe(sites="Sites to enable (leave empty for all sites)") @app_commands.describe(sites="Sites to enable (leave empty for all sites)")
async def enable_sites(self, interaction: discord.Interaction, sites: Optional[str] = None): async def enable_sites(self, ctx: commands.Context, *, sites: Optional[str] = None):
"""Enable specific sites""" """Enable specific sites"""
if sites is None: if sites is None:
await self.config.update_setting(interaction.guild.id, "enabled_sites", []) await self.config.update_setting(ctx.guild.id, "enabled_sites", [])
await interaction.response.send_message("All sites enabled") await ctx.send("All sites enabled")
return return
site_list = [s.strip().lower() for s in sites.split()] site_list = [s.strip().lower() for s in sites.split()]
@@ -200,19 +201,19 @@ class VideoArchiverCommands(commands.Cog):
valid_sites = set(ie.IE_NAME.lower() for ie in ydl._ies) valid_sites = set(ie.IE_NAME.lower() for ie in ydl._ies)
invalid_sites = [s for s in site_list if s not in valid_sites] invalid_sites = [s for s in site_list if s not in valid_sites]
if invalid_sites: if invalid_sites:
await interaction.response.send_message( await ctx.send(
f"Invalid sites: {', '.join(invalid_sites)}\nValid sites: {', '.join(valid_sites)}" f"Invalid sites: {', '.join(invalid_sites)}\nValid sites: {', '.join(valid_sites)}"
) )
return return
await self.config.update_setting(interaction.guild.id, "enabled_sites", site_list) await self.config.update_setting(ctx.guild.id, "enabled_sites", site_list)
await interaction.response.send_message(f"Enabled sites: {', '.join(site_list)}") await ctx.send(f"Enabled sites: {', '.join(site_list)}")
@app_commands.command(name="listsites") @videoarchiver.command(name="listsites")
@app_commands.guild_only() @app_commands.guild_only()
async def list_sites(self, interaction: discord.Interaction): async def list_sites(self, ctx: commands.Context):
"""List all available sites and currently enabled sites""" """List all available sites and currently enabled sites"""
enabled_sites = await self.config.get_setting(interaction.guild.id, "enabled_sites") enabled_sites = await self.config.get_setting(ctx.guild.id, "enabled_sites")
embed = discord.Embed( embed = discord.Embed(
title="Video Sites Configuration", color=discord.Color.blue() title="Video Sites Configuration", color=discord.Color.blue()
@@ -240,14 +241,14 @@ class VideoArchiverCommands(commands.Cog):
inline=False, inline=False,
) )
await interaction.response.send_message(embed=embed) await ctx.send(embed=embed)
@app_commands.command(name="queue") @videoarchiver.command(name="queue")
@app_commands.guild_only() @app_commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def show_queue(self, interaction: discord.Interaction): async def show_queue(self, ctx: commands.Context):
"""Show current queue status with basic metrics""" """Show current queue status with basic metrics"""
status = self.processor.queue_manager.get_queue_status(interaction.guild.id) status = self.processor.queue_manager.get_queue_status(ctx.guild.id)
embed = discord.Embed( embed = discord.Embed(
title="Video Processing Queue Status", title="Video Processing Queue Status",
@@ -278,15 +279,15 @@ class VideoArchiverCommands(commands.Cog):
inline=False inline=False
) )
embed.set_footer(text="Use /queuemetrics for detailed performance metrics") embed.set_footer(text="Use /videoarchiver queuemetrics for detailed performance metrics")
await interaction.response.send_message(embed=embed) await ctx.send(embed=embed)
@app_commands.command(name="queuemetrics") @videoarchiver.command(name="queuemetrics")
@app_commands.guild_only() @app_commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def show_queue_metrics(self, interaction: discord.Interaction): async def show_queue_metrics(self, ctx: commands.Context):
"""Show detailed queue performance metrics""" """Show detailed queue performance metrics"""
status = self.processor.queue_manager.get_queue_status(interaction.guild.id) status = self.processor.queue_manager.get_queue_status(ctx.guild.id)
metrics = status['metrics'] metrics = status['metrics']
embed = discord.Embed( embed = discord.Embed(
@@ -330,12 +331,12 @@ class VideoArchiverCommands(commands.Cog):
) )
embed.set_footer(text="Metrics are updated in real-time as videos are processed") embed.set_footer(text="Metrics are updated in real-time as videos are processed")
await interaction.response.send_message(embed=embed) await ctx.send(embed=embed)
@app_commands.command(name="clearqueue") @videoarchiver.command(name="clearqueue")
@app_commands.guild_only() @app_commands.guild_only()
@commands.admin_or_permissions(administrator=True) @commands.admin_or_permissions(administrator=True)
async def clear_queue(self, interaction: discord.Interaction): async def clear_queue(self, ctx: commands.Context):
"""Clear the video processing queue for this guild""" """Clear the video processing queue for this guild"""
cleared = await self.processor.queue_manager.clear_guild_queue(interaction.guild.id) cleared = await self.processor.queue_manager.clear_guild_queue(ctx.guild.id)
await interaction.response.send_message(f"Cleared {cleared} items from the queue") await ctx.send(f"Cleared {cleared} items from the queue")