Aiogram 3调用set_my_commands启动报错求助
解决Aiogram 3中set_my_commands触发的ValidationError问题
错误信息
raise validation_error pydantic.error_wrappers.ValidationError: 1 validation error for BotCommand description field required (type=value_error.missing) Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0424A148> Traceback (most recent call last): File "D:\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 116, in __del__ File "D:\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 108, in close File "D:\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 711, in call_soon File "D:\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 504, in _check_closed RuntimeError: Event loop is closed
核心代码片段
project.core.utils.commands/commands.py
from aiogram import Bot from aiogram.types import BotCommand, BotCommandScopeDefault async def set_commands(bot: Bot): commands = [BotCommand(command='start', descriptions='Begin work')] await bot.set_my_commands(commands, BotCommandScopeDefault())
core.handlers.basic.py
from aiogram.types import Message async def get_start(message: Message): await message.answer(f'Hi {message.from_user.first_name}. Welcome!')
project.main.py
from aiogram import Bot, Dispatcher from core.handlers.basic import get_start import asyncio from core.settings import settings from aiogram.filters import Command from core.utils.commands import set_commands async def start_bot(bot: Bot): print('Bot started!') await set_commands(bot) async def stop_bot(bot: Bot): print('Bot stopped!') async def start(): bot = Bot(token=settings.bots.bot_token, parse_mode='HTML') dp = Dispatcher() dp.startup.register(start_bot) dp.shutdown.register(stop_bot) dp.message.register(get_start, Command(commands=['start'])) try: await dp.start_polling(bot) finally: await bot.session.close() if __name__ == "__main__": asyncio.run(start())
关键信息
- 仅调用
await set_commands(bot)时触发错误,移除后机器人正常运行 RuntimeError: Event loop is closed片段重复出现10次- 代码基于视频教程,但使用了更新版本的依赖库
- 依赖版本:Python 3.8、aiogram 3.0.0.b7、asyncio 3.4.3、aiohttp 3.8.4、Windows 10
已尝试的解决方法
- 搜索到的方案多与aiohttp/FastApi相关,不适用
- 在finally块后添加
await asyncio.sleep(0.1) - 替换
asyncio.run(start())的写法 - 尝试多种非官方建议
- 拒绝通过BotFather添加命令(无法设置
BotCommandScope) - 对比教程代码,仅依赖版本有差异
解决方案
错误原因
Aiogram 3中BotCommand类的参数名是**description(单数)**,你代码里写的是descriptions(复数),导致Pydantic验证时找不到必填的description字段,直接抛出ValidationError,进而导致程序提前退出,后续出现事件循环已关闭的RuntimeError。教程代码无报错是因为旧版本Aiogram使用的是descriptions参数,新版本做了字段名修改。
修复代码
修改commands.py中的BotCommand初始化代码,把descriptions改成description:
from aiogram import Bot from aiogram.types import BotCommand, BotCommandScopeDefault async def set_commands(bot: Bot): # 把descriptions改为description commands = [BotCommand(command='start', description='Begin work')] await bot.set_my_commands(commands, BotCommandScopeDefault())
修改后重新启动机器人,ValidationError会消失,后续的RuntimeError也会因为程序正常执行而不再出现。
内容的提问来源于stack exchange,提问作者RobinGoood
相关产品推荐
相关产品推荐

