Reputation: 776
I have a list of items which I select one randomly and send it to the user. Then, I have an inline button just below the text message to shuffle the list of items once again.
Like this:
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')
Then I've made a callback query handler that changes the contents of the sent message if the user requests to randomize it once again:
@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)
The enormous problem I'm having with this is that sometimes the random_song()
function I'm using to shuffle the list sometimes randomly returns the same exact message as I've displayed the previous time. Since you cannot edit a message to the same message, I get an error.
How can I change my code so this does not happen? P.S. I'm using the pyTelegramBotAPI wrapper in py3.
Upvotes: 3
Views: 1825
Reputation: 776
This is not the most elegant solution I've come up with, but it works:
chosen_song = random_song()
while True:
try:
bot.edit_message_text(cid, mid, chosen_song)
except:
chosen_song = random_song()
Upvotes: 0
Reputation: 5038
The CallbackQuery contains the current Message and therefore has a field text
containing the current text.
You should be able to read the current text with call.message.text
and adapt the random_song()
to make sure it's not the same.
Upvotes: 1