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
相关产品推荐
相关产品推荐

