代码之家  ›  专栏  ›  技术社区  ›  Sergey Ronin

尝试编辑电报消息时出错

  •  3
  • Sergey Ronin  · 技术社区  · 8 年前

    我有一个项目列表,我随机选择一个项目并将其发送给用户。然后,我在文本消息下方有一个内联按钮,可以再次无序排列项目列表。

    像这样:

    keyboard = types.InlineKeyboardMarkup()
    shuffle_button = types.InlineKeyboardButton(text='Shuffle Again', callback_data='shuffle_action')
    keyboard.add(shuffle_button)
    
    @bot.message_handler(commands=['shuffle'])
    def display_shuffle(message):
        cid = message.chat.id
        bot.send_message(cid, random_song(), reply_markup=keyboard, parse_mode='HTML')
    

    然后,我制作了一个回调查询处理程序,如果用户再次请求将发送的消息随机化,它会更改消息的内容:

    @bot.callback_query_handler(func=lambda c: c.data == 'next_action')
    def shuffle_more(call):
        cid = call.message.chat.id
        mid = call.message.message_id
    
        bot.edit_message_text(chat_id=cid, message_id=mid, text=random_song(), reply_markup=keyboard)
    

    我面临的最大问题是 random_song() 我用来洗牌列表的函数有时会随机返回与上次显示的消息完全相同的消息。由于您无法将消息编辑为同一消息,因此我收到一个错误。

    如何更改代码以避免这种情况发生? P、 我在py3中使用pyTelegramBotAPI包装器。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Maak    8 年前

    这个 CallbackQuery 包含当前 Message 因此有一个字段 text 包含当前文本。

    您应该能够使用 call.message.text 并调整 random_song() 确保它不一样。

        2
  •  0
  •   Sergey Ronin    8 年前

    这不是我想到的最优雅的解决方案,但它很有效:

    chosen_song = random_song()
    
    while True:
        try:
            bot.edit_message_text(cid, mid, chosen_song)
        except:
            chosen_song = random_song()