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