⚑ SLASH COMMANDS & MODERN INTERACTIONS CHEAT SHEET

⚑ 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!