Страница 1 из 2 12 ПоследняяПоследняя
Показано с 1 по 10 из 11

Тема: Как зарегистрировать next step handler в telebot на Python?

  1. Как зарегистрировать next step handler в telebot на Python?

    Привет, ребята! Я тут делаю своего первого бота на Python с помощью библиотеки telebot и застрял на моменте с next step handler. Вижу, что есть методы register_next_step_handler и всякие вариации, но не понимаю, как правильно их применять. Хотелось бы более подробного объяснения или пример. Заранее спасибо!



  2. Ждём вас в нашем чате в Телеграмм ==>> @pythoneer_chat

    А ТАКЖЕ: Канал о Python, статьи и книги ==>>
    @pythoneer_ru

  3. Привет! Да тут всё просто, бро. Вот примерчик для понимания:

    [PHP]
    def start_message(message):
    bot.send_message(message.chat.id, 'Введите что-то:')
    bot.register_next_step_handler(message, process_step)

    def process_step(message):
    response = message.text
    bot.send_message(message.chat.id, f'Вы ввели: {response}')

    bot.polling()
    [PHP]

    Сначала создаешь функцию start_message, потом регаешь её телеги next step handler. Профит!

  4. Цитата Сообщение от ClockworkGenius303
    Привет! Да тут всё просто, бро. Вот примерчик для понимания:

    [PHP]
    def start_message(message):
    bot.send_message(message.chat.id, 'Введите что-то:')
    bot.register_next_step_handler(message, process_step)

    def process_step(message):
    response = message.text
    bot.send_message(message.chat.id, f'Вы ввели: {response}')

    bot.polling()
    [PHP]

    Сначала создаешь функцию start_message, потом регаешь её телеги next step handler. Профит!
    Хороший пример, бро. Главное - не забывать про bot.polling(), а то у меня сначала не работало ?*♂️.

  5. Эй! А ты помнишь, что надо handle только после вызова функции, а то не поймёт чего откуда. Вот пример для более сложных сценариев:

    [PHP]
    def start_command(message):
    bot.send_message(message.chat.id, 'Привет! Напиши своё имя:')
    bot.register_next_step_handler(message, ask_for_name)

    def ask_for_name(message):
    name = message.text
    msg = bot.send_message(message.chat.id, f'Приятно познакомиться, {name}! Сколько тебе лет?')
    bot.register_next_step_handler(msg, ask_for_age)

    def ask_for_age(message):
    age = message.text
    bot.send_message(message.chat.id, f'Ого, тебе {age} лет, круто!')

    bot.polling()
    [PHP]

    Настройка цепочки шагов, короче говоря.

  6. Цитата Сообщение от Анастасия Сергеевна
    Эй! А ты помнишь, что надо handle только после вызова функции, а то не поймёт чего откуда. Вот пример для более сложных сценариев:

    [PHP]
    def start_command(message):
    bot.send_message(message.chat.id, 'Привет! Напиши своё имя:')
    bot.register_next_step_handler(message, ask_for_name)

    def ask_for_name(message):
    name = message.text
    msg = bot.send_message(message.chat.id, f'Приятно познакомиться, {name}! Сколько тебе лет?')
    bot.register_next_step_handler(msg, ask_for_age)

    def ask_for_age(message):
    age = message.text
    bot.send_message(message.chat.id, f'Ого, тебе {age} лет, круто!')

    bot.polling()
    [PHP]

    Настройка цепочки шагов, короче говоря.
    О! Это то, что нужно! Цепочки реально важны, когда сценарий сложный. Спасибо за пример!

  7. Йоу, не забудь, что можно юзать context-менеджеры. Это делает код чище:

    [PHP]
    from telebot import types

    user_data = {}

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

    def send_welcome(message):
    msg = bot.reply_to(message, 'Привет, введи своё имя')
    bot.register_next_step_handler(msg, process_name_step)

    def process_name_step(message):
    chat_id = message.chat.id
    name = message.text
    user_data[chat_id] = name
    msg = bot.reply_to(message, 'Понятно, теперь укажи свой возраст')
    bot.register_next_step_handler(msg, process_age_step)

    def process_age_step(message):
    chat_id = message.chat.id
    age = message.text
    name = user_data.get(chat_id)
    bot.send_message(message.chat.id, f'Принято, {name}, тебе {age} лет')

    bot.polling()
    [PHP]

    Так код становится более логичным и понятным.

  8. Цитата Сообщение от SpiderGwen
    Йоу, не забудь, что можно юзать context-менеджеры. Это делает код чище:

    [PHP]
    from telebot import types

    user_data = {}

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

    def send_welcome(message):
    msg = bot.reply_to(message, 'Привет, введи своё имя')
    bot.register_next_step_handler(msg, process_name_step)

    def process_name_step(message):
    chat_id = message.chat.id
    name = message.text
    user_data[chat_id] = name
    msg = bot.reply_to(message, 'Понятно, теперь укажи свой возраст')
    bot.register_next_step_handler(msg, process_age_step)

    def process_age_step(message):
    chat_id = message.chat.id
    age = message.text
    name = user_data.get(chat_id)
    bot.send_message(message.chat.id, f'Принято, {name}, тебе {age} лет')

    bot.polling()
    [PHP]

    Так код становится более логичным и понятным.
    Совсем забыл про этот способ! Базара нет, намного читабельнее получается.

  9. Слышь, а у меня был трабл с несколькими ботами одновременно. Reinitializer-паттерн помогает. Вот пример:

    [PHP]
    def start_dialog(message, bot_instance):
    msg = bot_instance.send_message(message.chat.id, 'Введите данные:')
    bot_instance.register_next_step_handler(msg, next_step, bot_instance)

    def next_step(message, bot_instance):
    response = message.text
    bot_instance.send_message(message.chat.id, f'Ваш ответ: {response}')

    bot_instance = telebot.TeleBot('YOUR_API_TOKEN')
    start_dialog(message, bot_instance)
    [PHP]

    Так у каждого инстанса своя логика сохраняется.

  10. Цитата Сообщение от Анжела
    Слышь, а у меня был трабл с несколькими ботами одновременно. Reinitializer-паттерн помогает. Вот пример:

    [PHP]
    def start_dialog(message, bot_instance):
    msg = bot_instance.send_message(message.chat.id, 'Введите данные:')
    bot_instance.register_next_step_handler(msg, next_step, bot_instance)

    def next_step(message, bot_instance):
    response = message.text
    bot_instance.send_message(message.chat.id, f'Ваш ответ: {response}')

    bot_instance = telebot.TeleBot('YOUR_API_TOKEN')
    start_dialog(message, bot_instance)
    [PHP]

    Так у каждого инстанса своя логика сохраняется.
    Интересный подход, main. Никогда не задумывался о multiple instances в боте. Надо будет попробовать!

Страница 1 из 2 12 ПоследняяПоследняя