Discord.py命令在特定if语句上冷却

2024-04-28 15:15:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我还在琢磨,如果满足某些条件,如何使命令冷却。我将使用此代码作为示例

@client.command()
async def test(ctx):
    role1 = discord.utils.get(ctx.guild.roles, name='Test Role')
    if role1 in ctx.message.author.roles:
        em1 = discord.Embed(title = 'Test Title', description = f'You are in {role1.mention}, wait for 5 minutes before sending this command again.',color = ctx.author.color)
        await ctx.send(embed = em1)
    else:
        em2 = discord.Embed(title = 'Test Title', description = f'You are not in {role1.mention}.',color = ctx.author.color)
        await ctx.send(embed = em2)

我希望冷却时间只适用于ctx.author.message.roles中的“If role1:”one,而不适用于“else:”。当我使用“@commands.cooldown”时,它适用于整个语句


Tags: intestmessagetitleembeddescriptionem1command
1条回答
网友
1楼 · 发布于 2024-04-28 15:15:27

else中,可以使用test.reset_cooldown(ctx)重置冷却时间。 但是如果首先执行if role1 in ctx.message.author.roles:之后的内容,仍然会有冷却时间,因此需要一个处理程序,该处理程序也会执行代码的第二部分:

@test.error
async def test_handler(ctx, error):
    if isinstance(error, discord.ext.commands.CommandOnCooldown):
        if role1 in ctx.message.author.roles:
             #here you could write a message to discord saying "This command is currently on cooldown" or something similar.
        else:
            em2 = discord.Embed(title = 'Test Title', description = f'You are not in {role1.mention}.',color = ctx.author.color)
            await ctx.send(embed = em2)
    else:
        print(error)

因此,您的最终代码是:

@client.command()
@commands.cooldown(1, 300, commands.BucketType.user) #whatever you want to use here
async def test(ctx):
    role1 = discord.utils.get(ctx.guild.roles, name='Test Role')
    if role1 in ctx.message.author.roles:
        em1 = discord.Embed(title = 'Test Title', description = f'You are in {role1.mention}, wait for 5 minutes before sending this command again.',color = ctx.author.color)
        await ctx.send(embed = em1)
    else:
        test.reset_cooldown(ctx)
        em2 = discord.Embed(title = 'Test Title', description = f'You are not in {role1.mention}.',color = ctx.author.color)
        await ctx.send(embed = em2)


@test.error
async def test_handler(ctx, error):
    if isinstance(error, discord.ext.commands.CommandOnCooldown):
        if role1 in ctx.message.author.roles:
             #here you could write a message to discord saying "This command is currently on cooldown" or something similar.
        else:
            em2 = discord.Embed(title = 'Test Title', description = f'You are not in {role1.mention}.',color = ctx.author.color)
            await ctx.send(embed = em2)
    else:
        print(error)

相关问题 更多 >