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

Telegram机器人InlineKeyboardMarkup无法JSON序列化问题求助

解决Telegram Bot内联键盘JSON序列化错误

我的代码

async def options(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """发送附带两个内联按钮的消息"""
    keyboard = [[InlineKeyboardButton(text = "选项1", callback_data="1"),InlineKeyboardButton(text = "选项2", callback_data="2")]]
    reply_markup = InlineKeyboardMarkup(inline_keyboard=keyboard)
    #InlineKeyboardMarkup([[keyboard]], **kwargs)

    await update.message.reply_text("请选择:", reply_markup=reply_markup)

问题描述

我已尝试查找可能的解决方案,但仍出现相同的错误。

错误信息

2024-01-17 01:13:30,998 - telegram.ext.Application - ERROR - 未注册错误处理器,记录异常。
Traceback (most recent call last):
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\site-packages\telegram\request\_baserequest.py", line 330, in _request_wrapper
    code, payload = await self.do_request(
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\site-packages\telegram\request\_httpxrequest.py", line 242, in do_request
    data = request_data.json_parameters if request_data else None
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\site-packages\telegram\request\_requestdata.py", line 74, in json_parameters
    return {
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\site-packages\telegram\request\_requestdata.py", line 77, in <dictcomp>
    if param.json_value is not None
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\site-packages\telegram\request\_requestparameter.py", line 76, in json_value
    return json.dumps(self.value)
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\json\__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "C:\Users\arkgn\anaconda3\envs\rsi_master\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type InlineKeyboardMarkup is not JSON serializable

解决方案

该错误源于python-telegram-bot库无法正确将InlineKeyboardMarkup对象序列化为JSON格式,可通过以下方式修复:

  • 转换为字典格式传递
    调用reply_text时,将reply_markup参数改为对象的to_dict()方法返回值:

    await update.message.reply_text("请选择:", reply_markup=reply_markup.to_dict())
    
  • 升级库版本
    确保使用python-telegram-bot最新稳定版(v20.x及以上),旧版本存在序列化兼容问题。执行升级命令:

    pip install --upgrade python-telegram-bot
    
  • 确认导入正确性
    检查代码开头的导入语句,确保从官方库导入所需类:

    from telegram import InlineKeyboardButton, InlineKeyboardMarkup
    from telegram.ext import Update, ContextTypes
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:49:53