user9840885
user9840885

Reputation:

Cancelling commands

I am making a command to enable/disable bot commands per-channel. Though having problems cancelling the command if found in the database.

@Nao.event
async def on_command(ctx):
    if ctx.command.parent is None:
        database = mysql.connector.connect(
            host='',
            user='',
            passwd='',
            database=''
        )
        cursor = database.cursor()
        query = "SELECT command FROM cmdsdisabled WHERE channel = %s AND command = %s"
        values = (ctx.channel.id, ctx.command.name,)
        cursor.execute(query, values)
        result = cursor.fetchall()
        for command in result:
            await ctx.send('That command is disabled in this channel.')
        cursor.close()
        return

The code works, it checks if the command is in the database and if so, the bot says "That command is disabled in this channel." however, continues to execute the actual command.

I am wanting it to not continue to execute the actual command and only say "That command is disabled in this channel." if the command is found in the database.

Upvotes: 0

Views: 457

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61052

You can write a check that raises a custom exception, then handle that exception in a custom exception handler across all of your commands. The below code just requires you to write some command_is_disabled function to actually determine if the command is disabled.

from discord.ext.commands import DisabledCommand, check, Bot

bot = Bot("!")

class DisabledInChannel(DisabledCommand):
    pass

def check_disabled():
    def predicate(ctx):
        if command_is_disabled(ctx.command.name, ctx.channel.id):
            raise DisabledInChannel(f"{ctx.command.name} is disabled in {ctx.channel.name}")
        return True
    return check(predicate)

@bot.command()
@check_disabled()
async def some_command(ctx):
    ...

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, DisabledInChannel):
        await ctx.send(error.message)
    else:
        raise error

Upvotes: 1

Related Questions