Rapptz / discord.py

An API wrapper for Discord written in Python.
http://discordpy.rtfd.org/en/latest
MIT License
14.72k stars 3.74k forks source link

`cog_before_invoke` and `cog_after_invoke`-like method for application commands inside `discord.ext.commands.Cog` #8420

Open hitblast opened 2 years ago

hitblast commented 2 years ago

Summary

A proposal for two new methods inside discord.ext.commands.Cog to allow execution of code before-and-after the invocation of an application command.

What is the feature request for?

discord.ext.commands

The Problem

Imagine you have a Discord Bot that only has text commands. You have a greet command inside a cog that looks something like this:

from discord.ext import commands

class SomeRandomCog(commands.Cog):
    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.command(name='greet', help='Greets you!')
    async def _greet(self, ctx: commands.Context) -> None:
        await ctx.send('Hello!')

Now as you can see that this command is pretty straightforward. Now imagine that you would like to do something before your code runs. When it comes to text commands, the action is going to be as simple as this:

    # comes after __init__()
    async def cog_before_invoke(self, ctx: commands.Context) -> None:
        async with ctx.typing():
            await ctx.send('Greeting ...')

However, if you decide to switch to slash commands in the future some time, things might get pretty rough with the current version of discord.py as there's no such method for application commands (deriving from discord.Interaction).

The Ideal Solution

The idea in this case is to add two special methods inside discord.ext.commands.Cog which could apparently be coded like this:

async def cog_before_slash_invoke(self, interaction: discord.Interaction):
    await interaction.response.send_message('Greeting ...')

@app_commands.command(name='greet', description='Greets!')
async def _greet_slash(self, interaction: discord.Interaction):
    await interaction.followup.send('Hello!')

The Current Solution

No response

Additional Context

No response

nigamanthsrivatsan commented 2 years ago

Couldn't you just invoke the code that you have to on the on_ready event of the cog?

DMcP89 commented 1 year ago

@nigamanthsrivatsan wouldn't that only fire once though? It wouldn't work if you have code that you want to run every time a command gets called prior to the command logic running.