Discord.py 存储指令的冷却时间

0

的问题

我试图设置的冷却我的命令但是,当我重新启动机器人的冷却时间丢失。 我试图找到一种方式储存的冷却时间和重新使用它们但我不可能实现它通过查看文档

import discord 
from discord.ext import commands
cooldown_info_path = "cd.pkl"
class Bot(commands.Bot):

    async def start(self, *args, **kwargs):
        import os, pickle
        if os.path.exists(cooldown_info_path):  # on the initial run where "cd.pkl" file hadn't been created yet
            with open(cooldown_info_path, 'rb') as f:
                d = pickle.load(f)
                for name, func in self.commands.items():
                    if name in d:  # if the Command name has a CooldownMapping stored in file, override _bucket
                        self.commands[name]._buckets = d[name]
        return await super().start(*args, **kwargs)

    async def logout(self):
        import pickle
        with open(cooldown_info_path, 'wb') as f:
            # dumps a dict of command name to CooldownMapping mapping
            pickle.dump({name: func._buckets for name, func in self.commands.items()}, f)
        return await super().logout()

client = Bot(command_prefix=">")


@client.event
async def on_ready():
    print("Ready!")


@client.command()
@commands.cooldown(1, 3600, commands.BucketType.user)
async def hello(ctx):
    await ctx.send("HEY")

class ACog(commands.Cog):
    def __init__(self, client):
        self.bot = client

    @commands.command()
    @commands.cooldown(1, 600, commands.BucketType.user)
    async def ping(self, ctx):
        msg = "Pong {0.author.mention}".format(ctx)
        await ctx.send(msg)


client.add_cog(ACog(client))
client.run(token)

找到这段代码堆栈上的但是它不工作... 任何帮助将可以理解的

discord.py
2021-11-23 15:52:34
1

最好的答案

0

我已经做了一个这样的系统之前。 我要做的就是储存的一个大词典在一个星文件。 钥匙的用户名和价值的时间戳他们最后一次使用的命令。

代码的命令本身是在这里:

@client.command()
async def hello(ctx):
    last_used_time = get_last_used(ctx.author.id)
    available_time = last_used_time + timedelta(hours=1)
    if not available_time < datetime.utcnow():
        return

    await ctx.send("HEY")

    set_last_used(ctx.author.id)

注意到 timedelta(hours=1) 是的话的冷却时间。

get_last_usedset_last_used 被定义为:

def get_last_used(user_id: int):
    with open('data/TimelyCooldowns.json') as cooldowns_file:
        cooldowns = json.loads(cooldowns_file.read())

    time_string = cooldowns.get(str(user_id))
    if time_string is not None:
        return datetime.strptime(time_string, fmt)
    else:
        return datetime.min
def set_last_used(user_id: int):
    with open('data/TimelyCooldowns.json') as cooldowns_file:
        cooldowns = json.loads(cooldowns_file.read())

    cooldowns[str(user_id)] = datetime.strftime(datetime.utcnow(), fmt)
    with open('data/TimelyCooldowns.json', 'w') as cooldowns_file:
        cooldowns_file.write(json.dumps(cooldowns, indent=4))
2021-11-26 11:59:49

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................