wait_for()
函数是 discord.py
库中的一个非常有用的功能,它允许你等待某个事件发生,比如用户的反应或者消息发送。在 cogs
(即插件)中使用 wait_for()
函数可以帮助你创建交互式的命令。
wait_for()
函数的基本语法如下:
await bot.wait_for(event, check=None, timeout=None)
event
: 这是你想要等待的事件类型,比如 on_message
或者 on_reaction_add
。check
: 这是一个可选的函数,用于检查事件是否满足特定条件。它应该返回一个布尔值。timeout
: 这是一个可选的超时时间,如果在指定时间内没有发生事件,wait_for()
将会抛出一个 asyncio.TimeoutError
。wait_for()
函数常用于以下场景:
下面是一个简单的例子,展示了如何在 cogs
中使用 wait_for()
函数来等待用户回复:
import discord
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ask(self, ctx):
await ctx.send('你最喜欢的水果是什么?')
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
msg = await self.bot.wait_for('on_message', timeout=30.0, check=check)
except asyncio.TimeoutError:
await ctx.send('你没有在30秒内回答。')
else:
await ctx.send(f'你最喜欢的水果是 {msg.content}!')
def setup(bot):
bot.add_cog(MyCog(bot))
在这个例子中,当用户输入 !ask
命令时,机器人会发送一条消息询问用户最喜欢的水果。然后,它会等待用户在同一个频道中回复。如果在30秒内没有收到回复,机器人会发送一条超时消息。如果收到了回复,机器人会确认用户最喜欢的水果。
check
函数足够严格,以避免错误地匹配到其他用户的消息或事件。通过这种方式,你可以创建更加动态和互动的 Discord 机器人。
领取专属 10元无门槛券
手把手带您无忧上云