feat: Implement proper slash commands across all cogs - Use app_commands for better slash command support - Add command and parameter descriptions - Improve interaction handling - Add select menus for better UX

This commit is contained in:
pacnpal
2024-11-15 00:47:39 +00:00
parent ba71081687
commit a760bef25d
2 changed files with 175 additions and 133 deletions

View File

@@ -1,5 +1,5 @@
import discord import discord
from redbot.core import commands, checks from redbot.core import commands, checks, app_commands
from redbot.core.bot import Red from redbot.core.bot import Red
from redbot.core.config import Config from redbot.core.config import Config
from datetime import datetime, time, timedelta from datetime import datetime, time, timedelta
@@ -22,75 +22,86 @@ class Birthday(commands.Cog):
self.config.register_guild(**default_guild) self.config.register_guild(**default_guild)
self.birthday_tasks = {} self.birthday_tasks = {}
@commands.hybrid_group() birthdayset = app_commands.Group(
@checks.admin_or_permissions(manage_roles=True) name="birthdayset",
async def birthdayset(self, ctx): description="Birthday cog settings",
"""Birthday cog settings.""" guild_only=True
if ctx.invoked_subcommand is None: )
await ctx.send_help()
@birthdayset.command() @birthdayset.command(name="role")
@app_commands.guild_only()
@app_commands.describe(role="The role to set as the birthday role")
@checks.is_owner() @checks.is_owner()
async def role(self, ctx, role: discord.Role): async def set_role(self, interaction: discord.Interaction, role: discord.Role):
"""Set the birthday role.""" """Set the birthday role."""
await self.config.guild(ctx.guild).birthday_role.set(role.id) await self.config.guild(interaction.guild).birthday_role.set(role.id)
await ctx.send(f"Birthday role set to {role.name}") await interaction.response.send_message(f"Birthday role set to {role.name}")
@birthdayset.command() @birthdayset.command(name="timezone")
@app_commands.guild_only()
@app_commands.describe(tz="The timezone for role expiration (e.g., UTC, America/New_York)")
@checks.is_owner() @checks.is_owner()
async def timezone(self, ctx, tz: str): async def set_timezone(self, interaction: discord.Interaction, 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(ctx.guild).timezone.set(tz) await self.config.guild(interaction.guild).timezone.set(tz)
await ctx.send(f"Timezone set to {tz}") await interaction.response.send_message(f"Timezone set to {tz}")
except ZoneInfoNotFoundError: except ZoneInfoNotFoundError:
await ctx.send(f"Invalid timezone: {tz}. Please use a valid IANA time zone identifier.") await interaction.response.send_message(f"Invalid timezone: {tz}. Please use a valid IANA time zone identifier.")
@birthdayset.command() @birthdayset.command(name="channel")
@app_commands.guild_only()
@app_commands.describe(channel="The channel for birthday announcements")
@checks.is_owner() @checks.is_owner()
async def channel(self, ctx, channel: discord.TextChannel): async def set_channel(self, interaction: discord.Interaction, channel: discord.TextChannel):
"""Set the channel for birthday announcements.""" """Set the channel for birthday announcements."""
await self.config.guild(ctx.guild).birthday_channel.set(channel.id) await self.config.guild(interaction.guild).birthday_channel.set(channel.id)
await ctx.send(f"Birthday announcement channel set to {channel.mention}") await interaction.response.send_message(f"Birthday announcement channel set to {channel.mention}")
@birthdayset.command() @birthdayset.command(name="addrole")
async def addrole(self, ctx, role: discord.Role): @app_commands.guild_only()
@app_commands.describe(role="The role to allow using the birthday command")
async def add_allowed_role(self, interaction: discord.Interaction, 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(ctx.guild).allowed_roles() as allowed_roles: async with self.config.guild(interaction.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 ctx.send(f"Added {role.name} to the list of roles that can use the birthday command.") await interaction.response.send_message(f"Added {role.name} to the list of roles that can use the birthday command.")
@birthdayset.command() @birthdayset.command(name="removerole")
async def removerole(self, ctx, role: discord.Role): @app_commands.guild_only()
@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):
"""Remove a role from using the birthday command.""" """Remove a role from using the birthday command."""
async with self.config.guild(ctx.guild).allowed_roles() as allowed_roles: async with self.config.guild(interaction.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 ctx.send(f"Removed {role.name} from the list of roles that can use the birthday command.") await interaction.response.send_message(f"Removed {role.name} from the list of roles that can use the birthday command.")
@commands.hybrid_command() @app_commands.command(name="birthday")
async def birthday(self, ctx, member: discord.Member): @app_commands.guild_only()
@app_commands.describe(member="The member to give the birthday role to")
async def birthday(self, interaction: discord.Interaction, 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(ctx.guild).allowed_roles() allowed_roles = await self.config.guild(interaction.guild).allowed_roles()
if not any(role.id in allowed_roles for role in ctx.author.roles): if not any(role.id in allowed_roles for role in interaction.user.roles):
return await ctx.send("You don't have permission to use this command.") return await interaction.response.send_message("You don't have permission to use this command.", ephemeral=True)
birthday_role_id = await self.config.guild(ctx.guild).birthday_role() birthday_role_id = await self.config.guild(interaction.guild).birthday_role()
if not birthday_role_id: if not birthday_role_id:
return await ctx.send("The birthday role hasn't been set. An admin needs to set it using `/birthdayset role`.") return await interaction.response.send_message("The birthday role hasn't been set. An admin needs to set it using `/birthdayset role`.", ephemeral=True)
birthday_role = ctx.guild.get_role(birthday_role_id) birthday_role = interaction.guild.get_role(birthday_role_id)
if not birthday_role: if not birthday_role:
return await ctx.send("The birthday role doesn't exist anymore. Please ask an admin to set it again.") return await interaction.response.send_message("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 ctx.send("I don't have permission to assign that role.") return await interaction.response.send_message("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)
@@ -100,53 +111,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(ctx.guild).birthday_channel() birthday_channel_id = await self.config.guild(interaction.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 = ctx.channel channel = interaction.channel
else: else:
channel = ctx.channel channel = interaction.channel
await channel.send(message) await channel.send(message)
await interaction.response.send_message("Birthday role assigned!", ephemeral=True)
# Schedule role removal # Schedule role removal
timezone = await self.config.guild(ctx.guild).timezone() timezone = await self.config.guild(interaction.guild).timezone()
try: try:
tz = ZoneInfo(timezone) tz = ZoneInfo(timezone)
except ZoneInfoNotFoundError: except ZoneInfoNotFoundError:
await ctx.send(f"Warning: Invalid timezone set. Defaulting to UTC.") await interaction.followup.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(ctx.guild, member, birthday_role, midnight) await self.schedule_birthday_role_removal(interaction.guild, member, birthday_role, midnight)
@commands.hybrid_command() @app_commands.command(name="bdaycheck")
async def bdaycheck(self, ctx): @app_commands.guild_only()
async def bdaycheck(self, interaction: discord.Interaction):
"""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(ctx.guild).allowed_roles() allowed_roles = await self.config.guild(interaction.guild).allowed_roles()
if not any(role.id in allowed_roles for role in ctx.author.roles): if not any(role.id in allowed_roles for role in interaction.user.roles):
return await ctx.send("You don't have permission to use this command.") return await interaction.response.send_message("You don't have permission to use this command.", ephemeral=True)
scheduled_tasks = await self.config.guild(ctx.guild).scheduled_tasks() scheduled_tasks = await self.config.guild(interaction.guild).scheduled_tasks()
if not scheduled_tasks: if not scheduled_tasks:
return await ctx.send("There are no scheduled tasks.") return await interaction.response.send_message("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 = ctx.guild.get_member(int(member_id)) member = interaction.guild.get_member(int(member_id))
if not member: if not member:
continue continue
role = ctx.guild.get_role(task_info["role_id"]) role = interaction.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(ctx.guild).timezone())) remove_at = datetime.fromisoformat(task_info["remove_at"]).replace(tzinfo=ZoneInfo(await self.config.guild(interaction.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 ctx.send(message) await interaction.response.send_message(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

@@ -1,9 +1,10 @@
import aiohttp import aiohttp
from redbot.core import commands, Config from redbot.core import commands, Config, app_commands
from redbot.core.bot import Red from redbot.core.bot import Red
import asyncio import asyncio
import json import json
import urllib.parse import urllib.parse
import discord
class Overseerr(commands.Cog): class Overseerr(commands.Cog):
def __init__(self, bot: Red): def __init__(self, bot: Red):
@@ -16,44 +17,50 @@ class Overseerr(commands.Cog):
} }
self.config.register_global(**default_global) self.config.register_global(**default_global)
### GROUP: SETTINGS COMMANDS ### overseerr = app_commands.Group(
name="overseerr",
description="Overseerr configuration commands",
guild_only=True
)
@commands.hybrid_group() @overseerr.command(name="url")
@app_commands.guild_only()
@app_commands.describe(url="The URL of your Overseerr instance")
@commands.admin() @commands.admin()
async def overseerr(self, ctx: commands.Context): async def set_url(self, interaction: discord.Interaction, url: str):
"""Base command group for Overseerr configuration."""
if ctx.invoked_subcommand is None:
await ctx.send_help()
@overseerr.command()
async def 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 ctx.send(f"Overseerr URL set to: {url}") await interaction.response.send_message(f"Overseerr URL set to: {url}")
@overseerr.command() @overseerr.command(name="apikey")
async def apikey(self, ctx: commands.Context, api_key: str): @app_commands.guild_only()
@app_commands.describe(api_key="Your Overseerr API key")
@commands.admin()
async def set_apikey(self, interaction: discord.Interaction, 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 ctx.send("Overseerr API key has been set.") await interaction.response.send_message("Overseerr API key has been set.")
@overseerr.command() @overseerr.command(name="adminrole")
async def adminrole(self, ctx: commands.Context, role_name: str): @app_commands.guild_only()
@app_commands.describe(role_name="The name of the admin role")
@commands.admin()
async def set_adminrole(self, interaction: discord.Interaction, 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 ctx.send(f"Admin role for Overseerr approvals set to: {role_name}") await interaction.response.send_message(f"Admin role for Overseerr approvals set to: {role_name}")
### REQUEST & APPROVAL COMMANDS ### @app_commands.command(name="request")
@app_commands.guild_only()
@commands.hybrid_command() @app_commands.describe(query="The name of the movie or TV show to search for")
async def request(self, ctx: commands.Context, *, query: str): async def request(self, interaction: discord.Interaction, 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 ctx.send("Overseerr is not configured. Please ask an admin to set it up using `/overseerr url` and `/overseerr apikey`.") await interaction.response.send_message("Overseerr is not configured. Please ask an admin to set it up using `/overseerr url` and `/overseerr apikey`.", ephemeral=True)
return return
search_url = f"{overseerr_url}/api/v1/search" search_url = f"{overseerr_url}/api/v1/search"
@@ -62,93 +69,117 @@ class Overseerr(commands.Cog):
"Content-Type": "application/json" "Content-Type": "application/json"
} }
# Defer the response since this might take a while
await interaction.response.defer()
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 ctx.send(f"Error from Overseerr API: {resp.status}") await interaction.followup.send(f"Error from Overseerr API: {resp.status}", ephemeral=True)
return return
try: try:
search_results = await resp.json() search_results = await resp.json()
except Exception as e: except Exception as e:
await ctx.send(f"Failed to parse JSON: {e}") await interaction.followup.send(f"Failed to parse JSON: {e}", ephemeral=True)
return return
if 'results' not in search_results: if 'results' not in search_results:
await ctx.send(f"No results found for '{query}'. API Response: {search_results}") await interaction.followup.send(f"No results found for '{query}'. API Response: {search_results}", ephemeral=True)
return return
if not search_results['results']: if not search_results['results']:
await ctx.send(f"No results found for '{query}'.") await interaction.followup.send(f"No results found for '{query}'.", ephemeral=True)
return return
# Display search results with availability status # Create select menu for results
result_message = "Please choose a result by reacting with the corresponding number:\n\n" options = []
for i, result in enumerate(search_results['results'][:5], start=1): for i, result in enumerate(search_results['results'][:25]): # Discord limit is 25 options
media_type = result['mediaType'] media_type = result['mediaType']
title = result['title'] title = result['title']
release_date = result.get('releaseDate', 'N/A') release_date = result.get('releaseDate', 'N/A')
status = await self.get_media_status(result['id'], media_type) status = await self.get_media_status(result['id'], media_type)
result_message += f"{i}. [{media_type.upper()}] {title} ({release_date}) - {status}\n"
# Truncate description if needed (Discord has a 100-character limit for option descriptions)
description = f"[{media_type.upper()}] ({release_date}) - {status}"
if len(description) > 100:
description = description[:97] + "..."
options.append(
discord.SelectOption(
label=title[:100], # Discord has a 100-character limit for labels
description=description,
value=str(i)
)
)
result_msg = await ctx.send(result_message) select = discord.ui.Select(
placeholder="Choose a title to request...",
options=options,
custom_id="media_select"
)
# Add reaction options async def select_callback(select_interaction: discord.Interaction):
reactions = ['1', '2', '3', '4', '5'] selected_index = int(select_interaction.data['values'][0])
for i in range(min(len(search_results['results']), 5)): selected_result = search_results['results'][selected_index]
await result_msg.add_reaction(reactions[i]) media_type = selected_result['mediaType']
def check(reaction, user): # Check if the media is already available or requested
return user == ctx.author and str(reaction.emoji) in reactions status = await self.get_media_status(selected_result['id'], media_type)
if "Available" in status:
await select_interaction.response.send_message(
f"'{selected_result['title']}' is already available. No need to request!",
ephemeral=True
)
return
elif "Requested" in status:
await select_interaction.response.send_message(
f"'{selected_result['title']}' has already been requested. No need to request again!",
ephemeral=True
)
return
try: # Make the request
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check) request_url = f"{overseerr_url}/api/v1/request"
except asyncio.TimeoutError: request_data = {
await ctx.send("Search timed out. Please try again.") "mediaId": selected_result['id'],
return "mediaType": media_type
}
selected_index = reactions.index(str(reaction.emoji)) async with aiohttp.ClientSession() as session:
selected_result = search_results['results'][selected_index] async with session.post(request_url, headers=headers, json=request_data) as resp:
media_type = selected_result['mediaType'] if resp.status == 200:
response_data = await resp.json()
request_id = response_data.get('id')
await select_interaction.response.send_message(
f"Successfully requested {media_type} '{selected_result['title']}'! Request ID: {request_id}"
)
else:
await select_interaction.response.send_message(
f"Failed to request {media_type} '{selected_result['title']}'. Please try again later.",
ephemeral=True
)
# Check if the media is already available or requested select.callback = select_callback
status = await self.get_media_status(selected_result['id'], media_type) view = discord.ui.View()
if "Available" in status: view.add_item(select)
await ctx.send(f"'{selected_result['title']}' is already available. No need to request!") await interaction.followup.send("Search results:", view=view)
return
elif "Requested" in status:
await ctx.send(f"'{selected_result['title']}' has already been requested. No need to request again!")
return
# Make the request @app_commands.command(name="approve")
request_url = f"{overseerr_url}/api/v1/request" @app_commands.guild_only()
request_data = { @app_commands.describe(request_id="The ID of the request to approve")
"mediaId": selected_result['id'], async def approve(self, interaction: discord.Interaction, request_id: int):
"mediaType": media_type
}
async with aiohttp.ClientSession() as session:
async with session.post(request_url, headers=headers, json=request_data) as resp:
if resp.status == 200:
response_data = await resp.json()
request_id = response_data.get('id')
await ctx.send(f"Successfully requested {media_type} '{selected_result['title']}'! Request ID: {request_id}")
else:
await ctx.send(f"Failed to request {media_type} '{selected_result['title']}'. Please try again later.")
@commands.hybrid_command()
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 ctx.author.roles): if not any(role.name == admin_role_name for role in interaction.user.roles):
await ctx.send(f"You need the '{admin_role_name}' role to approve requests.") await interaction.response.send_message(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 ctx.send("Overseerr is not configured. Please ask an admin to set it up using `/overseerr url` and `/overseerr apikey`.") await interaction.response.send_message("Overseerr is not configured. Please ask an admin to set it up using `/overseerr url` and `/overseerr apikey`.", 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"
@@ -160,12 +191,10 @@ 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 ctx.send(f"Request {request_id} has been approved!") await interaction.response.send_message(f"Request {request_id} has been approved!")
else: else:
await ctx.send(f"Failed to approve request {request_id}. Please check the request ID and try again.") await interaction.response.send_message(f"Failed to approve request {request_id}. Please check the request ID and try again.", ephemeral=True)
### HELPER FUNCTION TO CHECK MEDIA STATUS ###
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()
overseerr_api_key = await self.config.overseerr_api_key() overseerr_api_key = await self.config.overseerr_api_key()