使用asyncio运行discord bot时不显示运行时错误



我正在开发discord.py==2.1.0.

我使用cog来编写我想要使用的主要函数,但是我发现当整个bot被封装在异步函数中并由asyncio.run()调用时,当我的cog脚本中有任何运行错误时,我的终端不会显示任何错误消息。

下面是示例应用程序。我将bot令牌存储在环境变量中。

  • bot.py
import os
import discord
from discord.ext import commands
import asyncio
token = os.environ["BOT_TOKEN"]
class Bot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True

description = "bot example."
super().__init__(
command_prefix=commands.when_mentioned_or('!'), 
intents=intents,
description=description
)
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = Bot()
async def load_extensions():
for f in os.listdir("./cogs"):
if f.endswith(".py"):
await bot.load_extension("cogs." + f[:-3])
async def main():
async with bot:
await load_extensions()
await bot.start(token)
asyncio.run(main())
  • 。/齿轮/my_cog.py
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
print("Ready")

@commands.command()
async def command(self, ctx):
test_error_message()   # An runtime error example
print("Command")
async def setup(client):
await client.add_cog(Test(client))
  • 我在终端运行启动bot的命令。
python bot.py
  • 当我在不和谐通道中输入!command时,终端没有显示错误信息,但是没有"Command"打印出来,所以我确定代码停在行我叫test_error_message()
  • 我期望它应该正常显示错误消息,但我找不到有用的参考来使它工作:(
  • 有一个原因我需要使用asyncio,我有一个任务循环在bot中运行,就像下面的代码。
from discord.ext import tasks
@tasks.loop(seconds=10)
async def avatar_update():
# code here
async def main():
async with bot:
avatar_update.start()
await load_extensions()
await bot.start(token)
  • 我很想知道在这种情况下是否有一些很好的实践来处理错误。

谢谢!

Client.start()不配置日志记录,所以如果您想使用它,那么您必须自己做(有setup_logging添加基本配置)。run()为您配置日志。

更多信息,请阅读文档。https://discordpy.readthedocs.io/en/stable/logging.html?highlight=logging

最新更新