命令 discord.py 中的客户端事件

时间:2021-03-15 16:04:07

标签: python discord discord.py

我目前正在制作一个带有教程的不和谐机器人,我希望如果成员输入“下一步”,则下一步发送。

代码:

async def pytutorial(ctx):
    embed=discord.Embed(title="Help for Wolf-Hosting Bot", description="panel.wolf-hosting.nl", color=0x0400ff)
    embed.set_thumbnail(url="https://cdn.discordapp.com/icons/807978904727191572/0704feeefd7a91c1abb2c37f9c9cc4f4.webp?size=256")
    embed.add_field(name="Welcome to the Wolf Hosting python tutorial!", value="We are first going to start with chosing an editor. I prefer using VSCode.", inline=True)
    embed.add_field(name='Type "next" for the next step.', value="Don't include the """, inline=True)
    embed.add_field(name="Download VSCode:", value="https://code.visualstudio.com/download", inline=False)
    await ctx.send(embed=embed)
    @client.event
    async def on_message(message):
        if "next" in message.content:
            embed=discord.Embed(title="Help for Wolf-Hosting Bot", description="panel.wolf-hosting.nl", color=0x0400ff)
            embed.set_thumbnail(url="https://cdn.discordapp.com/icons/807978904727191572/0704feeefd7a91c1abb2c37f9c9cc4f4.webp?size=256")
            embed.add_field(name="Installing discord.py", value='First click on Terminal in VSCode. Type "py -3 -m pip install -U discord.py".', inline=True)
            embed.add_field(name='Type "next" for the next step.', value="Don't include the """, inline=True)
            embed.add_field(name="More advanced explaining:", value="https://discordpy.readthedocs.io/en/latest/intro.html#installing", inline=False)
            await ctx.send(embed=embed)

问题:on_message 事件不断运行,人们无法再运行其他命令。 问题:如何在命令中创建事件(或更好的编码此 xd 的方法)

1 个答案:

答案 0 :(得分:1)

等待消息或任何 discord.py 事件可以通过 bot.wait_for

完成
@bot.command() #assuming bot since you haven't specified
async def command(ctx):
   #show help or some embed here
   try: 
      msg = await bot.wait_for('message', check = lambda x: 'next' in x.content and x.author == ctx.author, timeout = 30) #use self.bot.wait_for in cogs
   except asyncio.TimeoutError:
      await ctx.send('You took too long to respond')
   finally:
      #do other stuff here
      await msg.channel.send('hi')

使用 bot.wait_for

  1. 第一个参数是你正在等待的事件,所有这样的事件都被传递
  2. 事件的检查,检查函数采用与 on_event 函数相同的参数。 Ex on_messagemessage 作为参数。 check 函数应该返回一个布尔值。如果消息包含 next 并且作者与命令作者相同,我们的检查函数将返回 true。
  3. 超时参数告诉机器人等待多长时间,如果超时,则引发 asyncio.TimeoutError,我们通过 try 和 except 来捕获。

参考:

相关问题