You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

python-telegram-bot中无法导入Filters的问题及解决咨询

修复 ImportError: cannot import name 'Filters' from 'telegram.ext' 错误

问题原因

你安装的是python-telegram-bot v20及以上版本,这个版本彻底重构了模块结构:旧的Filters类被移除,相关功能移到了小写的telegram.ext.filters模块中,同时API风格从同步改为异步。

解决方案

1. 适配新版本API(推荐)

修改导入语句,并调整代码适配异步语法:

  • 替换旧导入:

    # 旧写法(v13及以下)
    from telegram.ext import Filters
    

    为:

    # 新写法(v20+)
    from telegram.ext import filters
    
  • 使用新的过滤器类(注意类名现在是大驼峰格式),比如:

    • 旧:Filters.text → 新:filters.Text
    • 旧:Filters.command → 新:filters.Command
    • 旧:Filters.chat_type.private → 新:filters.ChatType.PRIVATE

    示例完整代码:

    from telegram.ext import ApplicationBuilder, CommandHandler, filters
    
    async def start(update, context):
        await update.message.reply_text('Hello!')
    
    def main():
        # 替换原Updater为ApplicationBuilder
        application = ApplicationBuilder().token('你的机器人Token').build()
        # 使用filters.ChatType.PRIVATE替代原Filters.chat_type.private
        application.add_handler(CommandHandler('start', start, filters.ChatType.PRIVATE))
        application.run_polling()
    
    if __name__ == '__main__':
        main()
    

2. 降级到旧版本(不推荐)

如果暂时不想修改代码,可以降级到最后一个支持Filters的稳定版本(v13.15):

pip install python-telegram-bot==13.15

注意:旧版本不再接收安全更新和功能迭代,长期来看建议适配新版本。

内容的提问来源于stack exchange,提问作者lolernso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 18:58:14