Answer the question
In order to leave comments, you need to log in
How to display messages from the list in a Telegram bot at the user's command?
Hello.
I want to write a fairly simple bot for Telegram. I use telebot. I ran into a problem that I haven't been able to solve on my own.
There is a list with messages. The bot should issue them in order when the user clicks on the "Next task" button. To wait for a response, there is an understandable bot.register_next_step_handler. But how to wrap it in a loop? Or is there some other method.
test_lst = ["test_" + str(i) for i in range(1, 6)]
def next_quest_gui(m):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(*[types.KeyboardButton(name) for name in ["Следующее задание", "Выход"]])
bot.send_message(m.chat.id, 'Выберите действие', reply_markup=markup)
def action(m):
send = bot.send_message(m.chat.id, 'Выберите действие')
bot.register_next_step_handler(send, cycle)
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, test_lst[0])
next_quest_gui(m)
@bot.message_handler(content_types=["text"])
def cycle(m):
index = 0
if m.text == "Следующее задание":
index += 1
bot.send_message(m.chat.id, test_lst[index])
action(m)
else:
bot.send_message(m.chat.id, 'Ваш прогресс сохранен')
Answer the question
In order to leave comments, you need to log in
Taki found the solution himself: use an iterator for the list. My example code then becomes:
test_lst = ["test_" + str(i) for i in range(1, 6)]
itr = iter(test_lst)
def next_quest_gui(m):
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(*[types.KeyboardButton(name) for name in ["Следующее задание", "Выход"]])
bot.send_message(m.chat.id, 'Выберите действие', reply_markup=markup)
def action(m):
send = bot.send_message(m.chat.id, 'Выберите действие')
bot.register_next_step_handler(send, cycle)
@bot.message_handler(commands=["start"])
def start(m, res=False):
bot.send_message(m.chat.id, next(itr))
next_quest_gui(m)
@bot.message_handler(content_types=["text"])
def cycle(m):
if m.text == "Следующее задание":
msg = bot.send_message(m.chat.id, next(itr))
bot.register_next_step_handler(msg, cycle)
else:
bot.send_message(m.chat.id, 'Ваш прогресс сохранен')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question