【问题标题】:discord.py storing command cooldownsdiscord.py 存储命令冷却时间
【发布时间】:2021-11-26 19:59:49
【问题描述】:

我正在尝试为我的命令设置冷却时间,但是当我重新启动机器人时,冷却时间会丢失。 我正在尝试找到一种方法来存储冷却时间并重复使用它们,但我无法通过查看文档来实现它

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)

在 Stack 上找到此代码,但它不起作用... 任何帮助将不胜感激

【问题讨论】:

  • 在我的脑海中,您可以通过在机器人断开连接时获取每个命令的冷却时间并将信息仅保存在 txtjson 文件中来实现这一点。但是,这会有点混乱,因为您必须跟踪每个用户的冷却时间。
  • 但总的来说,你为什么想要这个功能呢?除非您出于测试目的而频繁重启机器人。
  • 机器人功能正常,但是当我更新机器人并重新启动它时,我失去了用户冷却时间
  • 我明白这一点。因此,我假设您正在更新和重新启动机器人,因为您正在测试事物。我不会尝试破解获得用户冷却时间的方法,而是使用齿轮。我知道你已经有一个齿轮,但它似乎没有被充分利用。您可以重新加载 cog 而无需重新启动整个机器人,因此您可以更新函数、重新加载该 cog,然后对其进行测试。如果您发现自己经常进行测试,那么纯粹出于测试目的使用 cog 可能是值得的。
  • 但是,我仍然想知道如何为用户保存冷却时间,因为我不想只更新 cog 中的命令,也不想更新主文件中的命令,即使我在 10 天后重新启动机器人我仍然想要用户保留他们的 CD 就像有一个每周的命令,我不希望人们使用它 :(

标签: discord.py


【解决方案1】:

我以前做过这样的系统。 我所做的是在 JSON 文件中存储一个大字典。 键是用户 ID,值是他们最后一次使用命令的时间戳。

命令本身的代码在这里:

@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-03-11
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2021-03-30
    • 2021-05-15
    • 2021-04-25
    相关资源
    最近更新 更多