如何保存命令冷却时间?

时间:2018-06-30 18:53:34

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

以下代码为命令添加了一个冷却时间,但是当bot重新启动时,冷却时间将重置。那么,如何使机器人记起以前的用法呢?如果冷却时间限制是每天5次,并且该成员使用了3次,并且如果bot重新启动,则应该从为所有成员保留的位置开始。

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

1 个答案:

答案 0 :(得分:2)

类似于Patrick Haugh的建议,冷却时间映射存储在Command._buckets中。您可以在机器人启动之前为存储桶腌制,并在机器人完成之后将其保存。为了方便起见,请将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”。

相关问题