β‘ SLASH COMMANDS & MODERN INTERACTIONS CHEAT SHEET #
Ultra-Condensed Enlightenment Guide
π HYBRID COMMAND ARCHITECTURE #
- π― Core Framework: Red’s HybridCommand & HybridGroup classes extending discord.py 2.0
- π§ Dual Nature: Commands work as both prefix commands and slash commands simultaneously
- π Command Tree: RedTree class manages global app command registration and sync
- π¨ Auto-Sync: Built-in sync management with guild-specific and global command handling
- π State Management: Disabled commands stored separately for dynamic enable/disable
- π‘οΈ Permission Inheritance: Slash commands inherit Red’s permission system automatically
- π¦ Error Handling: Specialized error handlers for interaction-specific failures
- π― Context Adaptation: Commands receive appropriate Context for prefix or Interaction for slash
Hybrid Command Definition #
@commands.hybrid_command(name="example")
async def example_cmd(self, ctx: commands.Context, user: discord.Member):
\"\"\"Example hybrid command that works as both prefix and slash\"\"\"
await ctx.send(f"Hello {user.mention}!")
@commands.hybrid_group(name="config")
async def config_group(self, ctx: commands.Context):
\"\"\"Hybrid group with subcommands\"\"\"
if ctx.invoked_subcommand is None:
await ctx.send_help(ctx.command)
@config_group.command(name="set")
async def config_set(self, ctx: commands.Context, option: str, value: str):
\"\"\"Set configuration option\"\"\"
await ctx.send(f"Set {option} to {value}")
π― APP COMMAND OPTIMIZATION #
Parameter Decoration & Types #
@app_commands.describe(
user="The user to greet",
message="Custom greeting message",
private="Send as ephemeral message"
)
@commands.hybrid_command()
async def greet(
self,
ctx: commands.Context,
user: discord.Member,
message: str = "Hello!",
private: bool = False
):
await ctx.send(message, ephemeral=private)
Advanced Parameter Patterns #
- π§ Type Hints: Union types, Optional parameters, Literal enums
- π Range Validation: app_commands.Range[int, 1, 100] for bounded integers
- π¨ Transform System: Custom transformers for complex data conversion
- π Choice Lists: app_commands.Choice for predefined option sets
- π‘οΈ Permission Checks: Inherit Red’s @commands.has_permissions system
- π¦ Context Types: Context.interaction property for slash-specific behavior
π€ AUTOCOMPLETION MASTERY #
Dynamic Autocompletion #
@app_commands.autocomplete(option_name='autocomplete_function')
@commands.hybrid_command()
async def search(self, ctx: commands.Context, query: str):
\"\"\"Command with autocomplete\"\"\"
await ctx.send(f"Searching for: {query}")
async def autocomplete_function(
self,
interaction: discord.Interaction,
current: str
) -> List[app_commands.Choice[str]]:
\"\"\"Provide dynamic autocomplete options\"\"\"
options = await self.get_search_options(current)
return [
app_commands.Choice(name=option.name, value=option.id)
for option in options[:25] # Max 25 choices
]
Autocompletion Best Practices #
- π― Response Time: Keep autocomplete functions under 3 seconds
- π§ Caching: Cache frequently used autocomplete data
- π Filtering: Filter results based on current input
- π¨ Contextual: Consider guild, user permissions in autocomplete
- π Error Handling: Graceful fallbacks for autocomplete failures
- π‘οΈ Rate Limiting: Avoid excessive API calls in autocomplete
- π¦ Relevance: Sort results by relevance to user input
π LOCALIZATION & INTERNATIONALIZATION #
Command Localization #
from discord import app_commands, Locale
@app_commands.describe(
user=app_commands.locale_str("user_description", key="USER_DESC"),
amount=app_commands.locale_str("amount_description", key="AMOUNT_DESC")
)
@commands.hybrid_command(
name=app_commands.locale_str("pay", key="PAY_COMMAND")
)
async def pay_command(self, ctx, user: discord.Member, amount: int):
\"\"\"Localized payment command\"\"\"
await ctx.send(f"Paid {amount} to {user}")
Localization Patterns #
- π― Locale Support: Support for discord.Locale enum values
- π§ Key Management: Centralized translation key systems
- π Fallback Logic: English fallbacks for missing translations
- π¨ Dynamic Content: Localize response messages not just command descriptions
- π Context Awareness: Use interaction.locale for user-specific language
- π‘οΈ Guild Preferences: Respect guild language settings where applicable
π ADVANCED PERMISSION PATTERNS #
Slash-Specific Permission Checks #
@app_commands.default_permissions(manage_guild=True)
@app_commands.guild_only()
@commands.hybrid_command()
async def admin_only(self, ctx: commands.Context):
\"\"\"Admin-only command with app command permissions\"\"\"
await ctx.send("Admin command executed!")
# Custom interaction checks
async def is_moderator(interaction: discord.Interaction) -> bool:
\"\"\"Custom check for moderator role\"\"\"
return any(role.name == "Moderator" for role in interaction.user.roles)
@app_commands.check(is_moderator)
@commands.hybrid_command()
async def moderate(self, ctx: commands.Context):
\"\"\"Moderator command with custom check\"\"\"
await ctx.send("Moderation action performed!")
Permission Integration Patterns #
- π― Default Permissions: Set initial permission state for commands
- π§ Guild Override: Allow guild admins to customize command permissions
- π Role-Based: Integrate with Discord’s role permission system
- π¨ Dynamic Checks: Runtime permission validation
- π Red Integration: Leverage Red’s existing permission framework
- π‘οΈ Inheritance: Command group permissions cascade to subcommands
β‘ INTERACTION RESPONSE PATTERNS #
Response Type Mastery #
@commands.hybrid_command()
async def interactive(self, ctx: commands.Context):
if ctx.interaction:
# Slash command - use interaction response
await ctx.interaction.response.send_message("Processing...", ephemeral=True)
await asyncio.sleep(2)
await ctx.interaction.edit_original_response(content="Complete!")
else:
# Prefix command - normal response
message = await ctx.send("Processing...")
await asyncio.sleep(2)
await message.edit(content="Complete!")
# Deferred responses for long operations
@commands.hybrid_command()
async def long_task(self, ctx: commands.Context):
if ctx.interaction:
await ctx.interaction.response.defer()
# Long processing...
await ctx.interaction.followup.send("Task completed!")
else:
async with ctx.typing():
# Long processing...
await ctx.send("Task completed!")
Response Optimization #
- π― Response Time: Always respond within 3 seconds or defer
- π§ Ephemeral Messages: Use ephemeral for error/confirmation messages
- π Edit Patterns: Edit original response instead of sending followups
- π¨ Rich Content: Leverage embeds, files, views in responses
- π Error Recovery: Handle interaction timeouts gracefully
- π‘οΈ State Tracking: Track interaction response state properly
π οΈ ERROR HANDLING & DEBUGGING #
Slash Command Error Patterns #
class MyCog(commands.Cog):
@commands.Cog.listener()
async def on_app_command_error(
self,
interaction: discord.Interaction,
error: app_commands.AppCommandError
):
\"\"\"Handle app command specific errors\"\"\"
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message(
f"Command on cooldown. Retry in {error.retry_after:.1f}s",
ephemeral=True
)
elif isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message(
"You don't have permission to use this command",
ephemeral=True
)
else:
# Log unexpected errors
logger.exception("Unexpected app command error", exc_info=error)
Debug & Development Tools #
- π― Sync Management: Use bot’s sync command to deploy changes
- π§ Guild Testing: Test commands in development guilds first
- π Interaction Logging: Log interaction details for debugging
- π¨ Error Tracking: Comprehensive error logging and user feedback
- π Validation: Type checking and parameter validation
- π‘οΈ Graceful Degradation: Fallback behavior for interaction failures
π PERFORMANCE & SCALABILITY #
Command Tree Optimization #
- π― Selective Sync: Sync only changed commands, not entire tree
- π§ Guild Isolation: Separate guild-specific from global commands
- π Command Grouping: Organize related commands into logical groups
- π¨ Lazy Loading: Load command data only when needed
- π Cache Strategy: Cache command metadata and permissions
- π‘οΈ Rate Limiting: Respect Discord’s command sync rate limits
- π¦ Memory Management: Clean up unused command references
Advanced Patterns #
# Command with complex parameter handling
@app_commands.describe(
action=app_commands.locale_str("The action to perform"),
target=app_commands.locale_str("The target for the action")
)
@app_commands.choices(action=[
app_commands.Choice(name="kick", value="kick"),
app_commands.Choice(name="ban", value="ban"),
app_commands.Choice(name="timeout", value="timeout")
])
@commands.hybrid_command()
async def moderate_user(
self,
ctx: commands.Context,
action: Literal["kick", "ban", "timeout"],
target: discord.Member,
reason: str = "No reason provided"
):
\"\"\"Advanced moderation command with choices\"\"\"
await self.perform_moderation(action, target, reason)
π₯ RED-DISCORDBOT INTEGRATION MASTERY #
Core Integration Points #
- π― Config System: Slash commands integrate with Red’s config API
- π§ Permission Framework: Inherit Red’s sophisticated permission system
- π Cog Architecture: Hybrid commands work seamlessly in Red cogs
- π¨ Error Handling: Leverage Red’s centralized error management
- π Help System: Automatic help generation for hybrid commands
- π‘οΈ Check System: Use Red’s @commands.check decorators
- π¦ Bank Integration: Economic commands work with Red’s banking system
Migration Best Practices #
- π― Gradual Migration: Convert commands to hybrid incrementally
- π§ Backward Compatibility: Maintain prefix command support
- π User Education: Guide users through slash command adoption
- π¨ Feature Parity: Ensure slash commands have same functionality
- π Testing Strategy: Comprehensive testing for both interaction types
- π‘οΈ Rollback Plan: Ability to disable slash commands if issues arise
β‘ Master Red-DiscordBot’s cutting-edge slash command system for next-generation Discord bot interactions!