在discord.py中避免破坏循环的一种解决方法是使用Bot.wait_for()
方法。这个方法允许你在不破坏循环的情况下等待特定的事件。
下面是一个示例代码,展示了如何在discord.py中使用Bot.wait_for()
方法来等待用户输入:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print('Bot is ready.')
@bot.command()
async def test(ctx):
await ctx.send('请输入您的回答:')
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
try:
# 等待用户输入,超时时间为10秒
message = await bot.wait_for('message', check=check, timeout=10)
await ctx.send(f'您的回答是:{message.content}')
except asyncio.TimeoutError:
await ctx.send('您没有输入任何内容。')
bot.run('YOUR_BOT_TOKEN')
在上面的示例中,test
命令将发送一条消息给用户,并等待用户在相同的文本频道中输入回答。check
函数用于检查消息是否满足条件(来自同一用户和相同文本频道)。wait_for
方法将等待用户回答,超时时间为10秒。
这种方法可以让你在等待用户回答时保持循环的运行,而不会破坏循环。