python-telegram-bot导入报错:无法从telegram.ext导入Filters
解决ImportError: cannot import name 'Filters' from 'telegram.ext'
问题原因
你安装的是python-telegram-bot的v20及以上版本,该版本对模块结构做了调整,Filters不再属于telegram.ext,而是被移到了telegram模块下。
解决方案
方案1:适配新版本,修改导入语句
将原来的导入代码拆分,把Filters从telegram模块导入:
from telegram import Filters from telegram.ext import Updater, CommandHandler, MessageHandler, CallbackContext
注意:v20+版本中Updater已被标记为弃用,官方推荐使用Application类构建Bot,示例代码如下:
from telegram import Update, Filters from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, CallbackContext async def start(update: Update, context: CallbackContext): await update.message.reply_text('Hello!') if __name__ == '__main__': # 替换为你的Bot Token application = ApplicationBuilder().token('YOUR_BOT_TOKEN').build() start_handler = CommandHandler('start', start) application.add_handler(start_handler) application.run_polling()
方案2:安装兼容旧代码的版本
如果不想修改现有代码,可以安装v13.x版本(该版本为长期支持版,匹配大多数旧教程代码):
pip install python-telegram-bot==13.7
内容的提问来源于stack exchange,提问作者Adil Akram
相关产品推荐
相关产品推荐

