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

python-telegram-bot v20.x 报错TypeError: bad operand type for unary ~: 'type'

解决python-telegram-bot v20.x中的TypeError问题

你的错误来自两个关键问题,对应修改方案如下:

错误原因及修复点

  • 过滤器用法错误:v20版本中,filters.Text和filters.Command是类,不能直接进行~位运算操作,需要使用现成的实例常量filters.TEXT和filters.COMMAND。
  • 处理函数不符合异步要求:v20版本要求消息处理函数必须是异步函数,需要用async def定义。

修改后的完整代码

from telegram.ext import MessageHandler
from telegram.ext import filters
from telegram.ext import Application
from telegram import Update
from telegram.ext import ContextTypes
from decouple import config

async def testFunc(update: Update, context: ContextTypes.DEFAULT_TYPE):
    print('Hi')
    
def main():
    BOT_TOKEN = config('TELE_BOT_API_KEY_2')
    application = Application.builder().token(BOT_TOKEN).build()
    
    # 使用正确的过滤器实例
    application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, testFunc))
    
    application.run_polling()

if __name__ == '__main__':
    main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 05:45:39