如何保存命令冷却时间? [英] How to save command cooldown?

查看:30
本文介绍了如何保存命令冷却时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below adds a cooldown for command, but when bot restarts, the cooldown resets. So how can I make the bot remember from previous usage? If the cooldown limit is 5 times per day and if the member used 3 times and if bot restarts it should start from where it was left for all members.

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 中.您可以在机器人启动之前为存储桶酸洗,并在机器人完成之后将其保存.为了方便起见,请将Bot类替换为以下内容(也称为"moneypatching"):

Similar to what Patrick Haugh suggested, the cooldown mapping is stored in Command._buckets. You can pickle the bucket before the bot starts and save it after the bot finishes. For your convenience, replace the Bot class with the following (a.k.a "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".


This will save the cooldown data to "cd.pkl" when the bot is properly logged out.

这篇关于如何保存命令冷却时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆