[英]how to make discord.py bot to send a specific message if the command is on cooldown
I'm trying to make a discord.py bot have a command which a user can use only once an hour.我试图让 discord.py 机器人有一个用户每小时只能使用一次的命令。 I want the bot to send a message "The command is on cooldown" when someone uses the command more than once an hour.
当有人每小时使用命令超过一次时,我希望机器人发送消息“命令正在冷却”。 This is the code for the command:
这是命令的代码:
bot = discord.Client()
@bot.event
@commands.cooldown(1, 3600, commands.BucketType.user)
async def on_message(message):
await message.channel.send("hello")
bot.run("xxxxxxxxxxxx")
How do I achieve that?我该如何做到这一点?
If you want to create commands for your bot - you better use ext.commands
extension part of the discord.py
library.如果您想为您的机器人创建命令 - 您最好使用
discord.py
库的ext.commands
扩展部分。 It prevents spaghetti code, gives better perfomance, it's easier to understand and there is command cooldown functionality, needed for your question and many more benefits.它可以防止意大利面条式代码,提供更好的性能,更容易理解,并且有命令冷却功能,这是您的问题所需要的,还有更多好处。 Thus I should send you to read docs for
ext.commands
or part of the library FAQ about it因此,我应该让您阅读
ext.commands
的文档或有关它的库常见问题解答的一部分
Anyway, you already figured out that cooldowns are made with @commands.cooldown(1, 3600, commands.BucketType.user)
but the way it works - it triggers error commands.CommandOnCooldown
when user is on cooldown and thus we need to write error handler to catch that and send specific message as an answer.无论如何,您已经发现冷却是用
@commands.cooldown(1, 3600, commands.BucketType.user)
进行的,但它的工作方式 - 它会在用户处于冷却状态时触发错误commands.CommandOnCooldown
,因此我们需要编写错误处理程序来捕获它并发送特定消息作为答案。 Again, link to read , gist .再次, 链接阅读, 要点。 But in my example below I use local error handler for the
!test
command and if error
is indeed of type commands.CommandOnCooldown
- the bot will send "The command is on cooldown."但在下面的示例中,我对
!test
命令使用本地错误处理程序,如果error
确实属于commands.CommandOnCooldown
- 机器人将发送“命令正在冷却”。 as a response.作为回应。
So MRE would look something like this.所以 MRE 看起来像这样。
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True # dont forget to optin them on dev portal
bot = commands.Bot(
command_prefix='!',
intents=intents
)
@commands.cooldown(1, 60*60, commands.BucketType.user)
@bot.command()
async def test(ctx: commands.Context):
await ctx.send("hello")
@test.error
async def test_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"The command is on cooldown.")
bot.run("xxxxxxxxxxxx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.