Manoj A
Manoj A

Reputation: 432

Run Another Function When Any Command Is Called discord.py

I need to run a common function whenever my discord bot commands are called! like the common function should execute first then it should run the command function
EXAMPLE:

async def common():
    #some code

@client.command()
async def something(ctx):
    #command code

So, When ever the something() function is called like '!something' by the user in discord, the common() function should execute first and then it should execute the something() function and in my bot i have tons of commands so i cant able to type common() on top of every command functions!.
Thanks in advance!

Upvotes: 0

Views: 4357

Answers (2)

AbdurJ
AbdurJ

Reputation: 1033

Try using the before_invoke decorator on your common function. You can read more on it here.

@client.before_invoke
async def common(message):
    await message.channel.send("This is the common function")


@client.command()
async def test(ctx):
    await ctx.send("This is the test command")

enter image description here

Upvotes: 4

Deru
Deru

Reputation: 1173

There is an event that is triggered everytime a command is executed: on_command.

So if you wanted to run the common function when any command is called you could create an on_command event:

async def on_command(ctx):
    common() # execute common function

Upvotes: 2

Related Questions