I
I
Interessnosnuy2018-08-22 00:56:13
Python
Interessnosnuy, 2018-08-22 00:56:13

How to correctly describe the “Go back” action in a telegram bot in Python?

Hello!
Tell me how to do it right. There are many menus with a "Go back" button, how to make it so that only with a certain (of many) menus with a "Go back" button will return to a certain (of many) menus.

@bot.message_handler(commands=['start'])

def handle_text1(message):
    user_markup = telebot.types.ReplyKeyboardMarkup(True, False)
    user_markup.row("Каталог", "Акция")
    user_markup.row("Корзина", "Доставка")
    bot.send_message(message.from_user.id, "Здравствуй, {0}!".format(message.from_user.first_name),reply_markup=user_markup)
    bot.send_message(message.from_user.id, "Выберете раздел", reply_markup=user_markup)

Class Keyboard   
    def __init__(self, bot):
        self.bot = bot

    def main_menu(self,message):
        user_markup = telebot.types.ReplyKeyboardMarkup(True, False)
        user_markup.row("Каталог", "Акция")
        user_markup.row("Корзина", "Доставка")
        user_markup.row("/start")
        self.bot.send_message(message.from_user.id, "Выберете раздел", reply_markup=user_markup)

    def katalog_menu(self, message):
        catdog_markup = telebot.types.ReplyKeyboardMarkup(True, False)
        catdog_markup.row("Корм для собак", "Корм для кошек")
        catdog_markup.row("Вернуться назад")
        catdog_markup.row("Главная")
        self.bot.send_message(message.from_user.id, "Выберете раздел", reply_markup=catdog_markup)


    def katalog_dog(self, message):
        dog_markup = telebot.types.ReplyKeyboardMarkup(True, False)
        dog_markup.row("Для щенков и юниоров")
        dog_markup.row("Для взрослых", "Для пожилых")
        dog_markup.row("Вернуться назад")
        dog_markup.row("Главная")
        self.bot.send_message(message.from_user.id, "Выберете раздел", reply_markup=dog_markup)

@bot.message_handler(func=lambda mess: 'Вернуться назад' == mess.text, content_types=['text'])
def handle_text(message):
    user_position = Keyboard
    if user_position(keyboard.katalog_menu(message)):
        keyboard.main_menu(message)
    elif user_position(keyboard.katalog_dog(message)): 
            keyboard.katalog_menu(message)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
A
AlmazKayum, 2018-08-24
@AlmazKayum

In such cases, I make two different buttons, for example: "Go back", "Back".
Go back leads to the main menu.
Back to submenu.
But I subscribed to the question, it’s really interesting how to competently do such things, if the hierarchy is large, then it’s more refined to do it the way you plan.

O
Odil Davronov, 2018-08-27
@odilbukh

I'm interested too!

C
CheXnik, 2021-06-10
@CheXnik

I implement it like this:
if you need to return to the main menu, then:

if 'Назад' in message.text:
    await message.answer("Ты вернулся в главное меню", reply_markup=kb.markup_home)

submenu:
When a person is in some state, then I check what he sent, if "Back", then I transfer him to the previous state, and display the desired keyboard. Here is the code:
@dp.message_handler(state=Update_account.UpdateFirstName)
async def answer_first_name(message: types.Message, state: FSMContext):
    text = message.text
    if text == "Назад":
        await message.answer('Ты вернулся назад', reply_markup=kb.update_account)
        await Update_account.Update.set()
    else:
        <тут действие если не нажата кнопка "Назад">

A
Alexander, 2018-08-30
@AlexMine

If I understand your question correctly, then the solution is to store the state (in the database, for example) at what stage the user is and when the 'Back' button is pressed, simply switch to the previous item.

T
Tahircik, 2018-09-05
@Tahircik

I hope you don't throw sticks because this is the way I get out. in general, each message is an object that has its own buttons and so on, I also predefined the buttons from the pytelegrambotapi module, so that each button would have its own message object, and naturally implemented a state machine, which allowed me to create a dictionary in which the key is the position from the automaton where the object of the message and the buttons are located, as well as the key to the previous message.
This allows you to implement the back button in this way: when the button is pressed, it looks at what position the automaton is in, finds it in the dictionary and looks at the previous message and then calls it, that's all.
I hope I helped someone, do not swear for grammar :)
link = {
    1:{
        'message' : MLanguage_1.Message_language ,
        'prev' : None ,
        'rus' : BRus.Rus ,
        'eng' : BEng.Eng ,
    } ,

    2:{
        'message' : MAgreement_2.Message_Agreement ,
        'prev' : None,
        'agreement' : BAgreement.Agreement ,
        'agree' : BAgree.Agree ,
        'ignore' : BIgnore.Ignore
    } ,

    -2:{
        'message' : MIgnore__2.Message_Ignor ,
        'prev' : 2 ,
        'back' : BReturn.Return,
    } ,

    3:{
        'message' : MMain.Message_Main_Menu ,
        'prev' : None ,
        'trading' : BTrading.Trading ,
        'panic' : BPanic.Panic ,
        'settings' : BSettings.Settings ,
        'help' : BHelp.Help ,
        'referal' : BReferal.Referal ,
        'cabinet' : BCabinet.Cabinet
    } ,

    7:{
        'message' : MHelp.Message_Help, #сам обьект сообшения
        'prev' : 3 , #значение предидушкго сообщения
        # кнопки
        'faq' : BFAQ.FAQ ,
        'service' : BService.Service ,
        'back' : BBack.Back
    }
# при нажатии кнопки назад
bot.send_message(chat_id=self.data.from_user.id , 
message=link[link[self.status]['prev']]['message']())

here is the dictionary :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question