Y
Y
Yevgeni2018-05-25 20:19:48
Python
Yevgeni, 2018-05-25 20:19:48

How to implement 'back' button in telegram bot?

You are welcome!
Help implement the transition from one menu to another using the back buttons

from telebot import TeleBot, types
from config import TELEGRAM_API_TOKEN
import json

bot = TeleBot(TELEGRAM_API_TOKEN)



@bot.message_handler(commands=['start'])
def search_vanacies(message):
    start_search_keyabord = types.ReplyKeyboardMarkup(
        resize_keyboard=True, row_width=2)
    button = types.KeyboardButton(' Поиск вакансий')
    start_search_keyabord.add(button)
    msg = bot.send_message(message.chat.id, '.',
                           reply_markup=start_search_keyabord)
    bot.register_next_step_handler(msg, city_selector)


def city_selector(message):
    select_city_keyaboard = types.ReplyKeyboardMarkup(
        resize_keyboard=True, row_width=2)
    c = open('cities.json', encoding='utf-8')
    cities = json.load(c)
    pairs = [cities[i:i+2] for i in range(0, len(cities), 2)]
    # print(pairs)
    back = types.KeyboardButton('назад')
    select_city_keyaboard.row(back)
    for i in pairs:
        btn1 = types.KeyboardButton(i[0]['city'])
        btn2 = types.KeyboardButton(i[1]['city'])
        select_city_keyaboard.row(btn1, btn2)
    msg = bot.send_message(message.chat.id, 'Выберете интересующий вас город',
                           reply_markup=select_city_keyaboard)
    bot.register_next_step_handler(msg, region_selector)


def region_selector(message):

    c = open('cities.json', encoding='utf-8')
    cities = json.load(c)
    for r in cities:
        if message.text == r['city']:
            regions = r['regions']
            pairs = [regions[i:i+2] for i in range(0, len(regions), 2)]
            select_region_keyboard = types.ReplyKeyboardMarkup(
                resize_keyboard=True, row_width=2)
            back = types.KeyboardButton(' <- назад')
            select_region_keyboard.row(back)

            for i in pairs:
                try:
                    btn1 = types.KeyboardButton(i[0])
                    btn2 = types.KeyboardButton(i[1])
                    select_region_keyboard.row(btn1, btn2)
                except Exception:
                    btn = types.KeyboardButton(i[0])
                    select_region_keyboard.row(btn1)

            bot.send_message(message.chat.id, 'Теперь выберете район',
                             reply_markup=select_region_keyboard)


if __name__ == '__main__':
    bot.remove_webhook()
    bot.polling()

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question