gpt4 book ai didi

python - 如何保存命令冷却时间?

转载 作者:太空宇宙 更新时间:2023-11-04 02:23:05 25 4
gpt4 key购买 nike

下面的代码为命令添加了冷却时间,但是当机器人重新启动时,冷却时间会重置。那么我怎样才能让机器人记住以前的使用情况呢?如果冷却时间限制是每天 5 次,并且如果成员使用了 3 次,并且如果机器人重新启动,它应该从它为所有成员留下的地方开始。

import discord
from discord.ext import commands
import random

from utils import Bot
from utils import CommandWithCooldown

class Members():
def __init__(self, bot):
self.bot = bot


@commands.command(pass_context=True, cls=CommandWithCooldown)
@commands.cooldown(1, 600, commands.BucketType.user)
async def ping(self, ctx):
msg = "Pong {0.author.mention}".format(ctx.message)
await self.bot.say(msg)


def setup(bot):
bot.add_cog(Members(bot))

最佳答案

与 Patrick Haugh 的建议类似,冷却时间映射存储在 Command._buckets 中。您可以在机器人启动前对桶进行 pickle,并在机器人完成后保存它。为了您的方便,将 Bot 类替换为以下内容(又名“moneypatching”):

token = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
prefix = "?"
cooldown_info_path = "cd.pkl"

from discord.ext import commands


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()


bot = Bot(prefix)
# everything else as usual

@bot.event
async def on_ready():
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')


@bot.command(pass_context=True)
@commands.cooldown(1, 3600, commands.BucketType.user)
async def hello(ctx):
msg = "Hello... {0.author.mention}".format(ctx.message)
await bot.say(msg)


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

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


bot.add_cog(ACog(bot))
bot.run(token)

当机器人正确注销时,这会将冷却时间数据保存到“cd.pkl”。

关于python - 如何保存命令冷却时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51117681/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com