尝试编辑电报消息时出错

Error when trying to edit a Telegram message

我有一个项目列表,我 select 随机将其发送给用户。然后,我在文本消息下方有一个内联按钮,用于再次随机排列项目列表。

像这样:

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() 我用来随机排列列表的函数 returns 与我之前显示的完全相同的消息时间。由于您无法将消息编辑为同一消息,因此出现错误。

如何更改我的代码以防止这种情况发生? P.S。我在 py3 中使用 pyTelegramBotAPI 包装器。

CallbackQuery contains the current Message 因此有一个包含当前文本的字段 text

您应该能够使用 call.message.text 阅读当前文本并调整 random_song() 以确保它不一样。

这不是我想出的最优雅的解决方案,但它确实有效:

chosen_song = random_song()

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