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

Telegram机器人报错:InlineKeyboardButton无法JSON序列化

问题解决:Telegram机器人JSON序列化错误

错误原因

你在发送带内联键盘的消息时犯了关键错误:直接把按钮数组传给了InlineKeyboardButton,但正确做法是用InlineKeyboardMarkup包装按钮数组。Telegram API要求回复标记必须是对应Markup类的实例,而非单个按钮或按钮数组,这才导致了JSON序列化失败。

另外queryHandler里还有笔误:dislike += 1应该写成dislikes += 1,否则会触发变量未定义错误。

修正后的完整代码

from telegram import *
from telegram.ext import *
from requests import *

updater = Updater(token='')  # 此处填写你的机器人Token
dispatcher = updater.dispatcher

randomPeopleText = 'Random Person'
randomImageText = 'Random Image'

randomPeopleUrl = 'https://thispersondoesnotexist.com/image'
randomImageUrl  = 'https://picsum.photos/400'

likes = 0
dislikes = 0

def startCommand(update: Update, context: CallbackContext):
    buttons = [[KeyboardButton('Random Image')],[KeyboardButton('Random Person')]]
    context.bot.send_message(chat_id=update.effective_chat.id, text='Welcome to my bot!',
                             reply_markup=ReplyKeyboardMarkup(buttons))

def messageHandler(update: Update, context: CallbackContext):
    image = None
    if randomPeopleText in update.message.text:
        image = get(randomPeopleUrl).content
    if randomImageText in update.message.text:
        image = get(randomImageUrl).content
    if image:
        context.bot.sendMediaGroup(chat_id=update.effective_chat.id, 
                                   media=[InputMediaPhoto(image, caption='')])
        
        buttons = [
                [InlineKeyboardButton('like', callback_data='like'),
                InlineKeyboardButton('dislike', callback_data='dislike')]
                ]
        
        # 修正:用InlineKeyboardMarkup包裹按钮数组
        context.bot.send_message(chat_id=update.effective_chat.id, 
        reply_markup = InlineKeyboardMarkup(buttons), 
        text='Did you like the image?')
        
def queryHandler(update: Update, context: CallbackContext):
    query = update.callback_query.data
    update.callback_query.answer()
    
    global likes, dislikes
    if 'like' in query:
        likes += 1
        
    if 'dislike' in query:
        dislikes += 1  # 修正变量名拼写错误
        
    print(f"likes => {likes} and dislikes => {dislikes}")
        
dispatcher.add_handler(CommandHandler('start', startCommand))
dispatcher.add_handler(MessageHandler(Filters.text, messageHandler))
dispatcher.add_handler(CallbackQueryHandler(queryHandler))

updater.start_polling()

额外优化提示

  • 初始化image为None,避免用户输入非指定文本时出现变量未定义错误
  • 确保已将机器人Token正确填入Updater的参数中

内容的提问来源于stack exchange,提问作者Loh Boon How

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 04:20:18