VS Code运行Telegram机器人报错:找不到aiogram库求助
解决aiogram模块找不到的问题(ModuleNotFoundError)
运行Telegram机器人代码时,执行from aiogram import Bot, Dispatcher抛出ModuleNotFoundError: No module named 'aiogram',VS Code环境下此前代码可正常运行,修改玩家统计输出后出现该问题,重装库无效。
用户代码如下:
import asyncio from aiogram import Bot, Dispatcher from bot_handlers import dp from database import create_tables API_TOKEN = '7219879832:AAH2izLkXz1E92R9oFt5W7r5C-Pwn_b-7S0' async def on_startup(dispatcher): await create_tables() async def main(): bot = Bot(token=API_TOKEN) dp = Dispatcher() dp.startup.register(on_startup) await dp.start_polling(bot) if __name__ == '__main__': asyncio.run(main())
解决步骤:
- 检查VS Code的Python解释器:点击VS Code左下角显示的Python版本,确认当前选中的解释器是安装了aiogram的环境(比如虚拟环境)。如果使用虚拟环境,先在终端激活它:Linux/macOS执行
source venv/bin/activate,Windows执行venv\Scripts\activate。 - 重新在当前环境安装aiogram:激活正确环境后,先执行
pip uninstall aiogram彻底卸载,再执行pip install aiogram。如果使用的是aiogram 3.x版本,需指定版本号,比如pip install aiogram==3.4.0。 - 验证库是否安装成功:在终端进入Python交互模式,输入
import aiogram,无报错则说明库已正确安装,问题出在VS Code环境配置。 - 注意代码变量冲突:代码中同时从
bot_handlers导入dp,又在main函数中重新定义dp = Dispatcher(),虽然不是模块找不到的直接原因,但可能引发其他逻辑问题,建议修改变量名避免冲突。
内容的提问来源于stack exchange,提问作者KALEBALKA
相关产品推荐
相关产品推荐

