首页 > 解决方案 > 如何为命令添加冷却时间

问题描述

我对编码很陌生,只想在我从互联网上下载的代码中添加一个命令计时器。我不知道该怎么做,而且我发现的所有其他代码对我来说太多了。我只是希望能够为每个命令添加大约 10 秒的冷却时间。

import discord

import asyncio

from discord.ext import commands

import datetime as DT

import discord.utils

class MyClient (discord.Client):

    async def on_ready(self):

        print('Logged in as')
        print(self.user.name)
        print(self.user.id)
        print('------')

    async def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('!discord'): # I want to add a timer
            channel = client.get_user(message.author.id)
            await channel.send(''.format(message))

    async def on_member_join(self, member):
        guild = member.guild
        if guild.system_channel is not None:
            to_send = 'Welcome {0.mention} to {1.name}!'.format(member, guild)
            await guild.system_channel.send(to_send)

client = MyClient()

client.run('')

标签: python-3.xtimer

解决方案


另一个用户建议的time.sleep()功能是阻塞调用。这意味着它将阻止整个线程运行。我不确定 Discord 框架是如何工作的,但我想线程阻塞可能是个问题。

我认为更好的解决方案是使用asyncio,特别是因为您已经导入了它。它将允许程序在等待 10 秒的同时执行其他操作。如果你有兴趣,另一个 Stackoverflow 线程

if message.content.startswith('!discord'):
            channel = client.get_user(message.author.id)
            await asyncio.sleep(10)
            await channel.send(''.format(message))

编辑

您可以保存上次调用该函数的时间,并使用 IF 语句检查自上次调用以来是否已过去 10 秒。

class MyClient (discord.Client):

    last_called = None

    async def on_ready(self):
        # other stuff

    async def on_message(self, message):
        # check if 10 seconds have passed since the last call
        if MyClient.last_called and DT.datetime.now() < MyClient.last_called + DT.timedelta(seconds=10):
            return

        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('!discord'):
            channel = client.get_user(message.author.id)
            await channel.send(''.format(message))
            MyClient.last_called = DT.datetime.now()  # save the last call time

推荐阅读