首页 > 解决方案 > 禁止命令的 discord.py 命令冷却时间

问题描述

我的机器人有这个代码,它允许禁止某些人的用户。但是,有没有办法让工作人员每 2 小时只能使用一次禁令命令。我希望所有其他命令都没有冷却时间,但对于禁止命令,有一种方法只能允许每个用户每 2 小时使用一次。这是我到目前为止的代码:

@commands.has_permissions(administrator=True)
async def pogoban (ctx, member:discord.User=None, *, reason =None):
    if member == None or member == ctx.message.author:
        await ctx.channel.send("You cannot ban yourself")
        return
    if reason == None:
        reason = "For breaking the rules."
    message = f"You have been banned from {ctx.guild.name} for {reason}"
    await member.send(message)
    await ctx.guild.ban(member, reason=reason)
    await ctx.channel.send(f"{member} is banned!")

我需要添加/更改什么来为该命令添加每个用户 2 小时的命令冷却时间。我试过环顾四周,但我只找到了让所有命令都有冷却时间的方法,而不是这个特定的命令。谢谢!

标签: pythondiscord.py

解决方案


像这样的东西怎么样:

cooldown = []

@client.command()
async def pogoban(ctx, member: discord.Member = None, *, reason = None):
    author = str(ctx.author)
    if author in cooldown:
        await ctx.send('Calm down! You\'ve already banned someone less that two hours ago.')
        return

    try:
        if reason == None:
            reason = 'breaking the rules.'
        await member.send(f'You have been banned from **{ctx.guild.name}** for **{reason}**')
        await member.ban(reason = reason)
        await ctx.send(f'{member.mention} has been banned.')
        cooldown.append(author)
        await asyncio.sleep(2 * 60 * 60)    #The argument is in seconds. 2hr = 7200s
        cooldown.remove(author)
    except:
        await ctx.send('Sorry, you aren\'t allowed to do that.')

注意:记得导入asyncio. 另请记住,一旦您的机器人离线,存储在列表中的所有用户都将被删除。


请阅读

更好的方法是将禁止时间与作者姓名一起存储,并检查当前时间是否比保存的时间至少多一个小时。为了更安全,作者姓名和时间可以保存在数据库或外部文本文件中,这样如果机器人离线,您的数据就不会被删除。


推荐阅读