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

标签 python python-3.x discord discord.py

下面的代码添加了命令的冷却时间,但是当机器人重新启动时,冷却时间会重置。那么如何让机器人记住以前的使用情况呢?如果冷却时间限制为每天 5 次,并且如果成员(member)使用了 3 次,并且机器人重新启动,则应从为所有成员(member)保留的位置开始。

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/

相关文章:

python - 无法在仅 tensorflow CPU 安装上加载动态库 'cudart64_101.dll'

python - 细数汉诺塔的 Action

javascript - Discord.js 机器人在 channel 中发送 10 条消息后发送消息

python - 如何计算 Pandas Dataframe 中所有列的哈希值?

Python读取LTspice图导出

python - Discord.py 和 youtube_dl、 "Read error"和 "The session has been invalidated for some reason"

javascript - 离开命令 Discord JS

python - 在曲面图上画线

python - 如何将文本文件中的数据转换为列表?

python - 在 Python Tkinter 中获取父窗口小部件的父窗口