python-3.x - 如何为命令添加冷却时间
问题描述
我对编码很陌生,只想在我从互联网上下载的代码中添加一个命令计时器。我不知道该怎么做,而且我发现的所有其他代码对我来说太多了。我只是希望能够为每个命令添加大约 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('')
解决方案
另一个用户建议的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
推荐阅读
- android - 我们可以从 Flutter 应用程序更改我们的移动设置吗?
- reactjs - FieldValue.arrayUnion() 未处理的拒绝
- typescript - 与参数类型匹配的函数返回类型(使用扩展运算符时)?
- android - Android Theme - 如何声明多个具有通用样式的主题?
- python - ModuleNotFoundError,当我尝试将模型导入另一个自定义文件夹时
- java - 使用 Rest Assured response.jsonPath().getObject() 进行序列化返回 null
- python - 如何从函数 QSystemTrayIcon 将操作添加到上下文菜单
- javascript - Javascript 在递归调用中通过引用传递问题
- python - 使用熊猫在 tkinter 中的树视图上从 excel 更改/编辑信息?
- python - 需要帮助 python (mqtt-paho) 中的 client.loop_forever() 错误