首页 > 解决方案 > 虽然循环崩溃机器人

问题描述

while condition:
            try:
                msg = await self.client.wait_for('message', check=check, timeout = 60)
            except asyncio.TimeoutError:
                condition = False
                break
            else:
                my_num = msg.content.split(' ')
                if len(my_num) > 2:
                    await ctx.send("Seems like you added too many arguments... Only use `category` `number`", delete_after=2)
                category = my_num[0]
                try:
                    index = int(my_num[1])
                except ValueError:
                     await ctx.send("The second argument needs to be an integer", delete_after=2)
                except IndexError:
                     await ctx.send("Provide two arguments: `category` `number`  (example: plants 3)")
                if category.lower() == "plants":
                    try:
                        my_query = new_list[index-1]
                    except IndexError:
                        await ctx.send("the number you wrote doesn't exist!", delete_after=2)
                    queried_potion = all_items[my_query]
                    try:
                        signs = queried_potion['sign']
                    except KeyError:
                        signs = []
                    try:
                        symbols = queried_potion['symbol']
                    except KeyError:
                        symbols = []
                    sign = " | ".join(signs) if len(signs) != 0 else "None"
                    symbol = " | ".join(symbols) if len(symbols) != 0 else "None"      
                    em = discord.Embed(title=f"Information for: {my_query}", description= f"**Symbols:** \n{symbol} \n\n**Signs:**\n {sign}", color = self.client.theme)
                    await mess.edit(embed=em)

以上是我为某人编写的代码,循环执行了我打算执行的操作,但出现了问题。在 " wait_for" 超时后,机器人由于某种原因而崩溃。我似乎找不到任何理由。

使用的所有变量都已定义,并且机器人在超时后就死掉了,没有错误。

知道为什么会这样吗?

在此处输入图像描述

bot 崩溃后的终端图像:[编辑]

在此处输入图像描述

标签: pythondiscorddiscord.py

解决方案


根据wait_for 文档,提供超时时间(默认为无)将引发asyncio.TimeoutError.

在您的代码中:

try:
   msg = await self.client.wait_for('message', check=check, timeout = 60)
except asyncio.TimeoutError:
   condition = False
   break

这会导致您跳出 while 循环(请注意,将条件设置为 false 不会改变任何内容,因为您无论如何都已退出循环)。它看起来不像机器人正在崩溃,它看起来更像是机器人只是完成了程序的执行。

也许你想要的是不设置timeout


推荐阅读