как выйти из хэндлера telebot до следующего вызова

Всем привет. Подскажите пожалуйста как "выключить" хандлер до следующего вызова команды. В коде бота в телеграмм написал игру в камень ножницы бумага но не могу понять как выйти из игры что бы можно было спокойно использовать другие функции. Вот код:

@bot.message_handler(commands=['game']) # игра в камень ножницы бумага
def game(message):
    markup = types.ReplyKeyboardMarkup(row_width=3)
    markup.add(types.KeyboardButton('?'), types.KeyboardButton('✂️'), types.KeyboardButton('?'), types.KeyboardButton('❌'))
    bot.reply_to(message, "Добро пожаловать в игру 'Камень, ножницы, бумага'! Для игры используйте кнопки ниже:", reply_markup=markup)
    bot.register_next_step_handler(message, callback=play_game)

@bot.message_handler(func=lambda message: True)
def play_game(message):
    user_choice = message.text
    bot_choice = random.choice(['?', '✂️', '?', '❌'])
    if user_choice not in ['?', '✂️', '?', '❌']:
        bot.reply_to(message, "Пожалуйста, используйте кнопки для выбора камня, ножниц или бумаги.")
        return

    if user_choice == bot_choice:
        bot.reply_to(message, f"Вы выбрали {user_choice}, а я выбрал {bot_choice}. Ничья!")
    elif (user_choice == '?' and bot_choice == '✂️') or (user_choice == '✂️' and bot_choice == '?') or (user_choice == '?' and bot_choice == '?'):
        bot.reply_to(message, f"Вы выбрали {user_choice}, а я выбрал {bot_choice}. Вы победили! ?")
    else:
        bot.reply_to(message, f"Вы выбрали {user_choice}, а я выбрал {bot_choice}. Я победил! ?")
    if message.text == '❌':
        a = types.ReplyKeyboardRemove()
        msg=bot.send_message(message.chat.id, 'Игра окончена! Возвращайся ещё', reply_markup=a)

Если сменить

func=lambda message: True

На

func=lambda commands: commands == 'game'

То хандлер с игрой запускается лишь на один раз. Как обойти захват сообщений этим хандлером и нормально играть до прерывания игры командой

if message.text == '❌':

В кодах я хуже чем ноль а бота пишу чисто для себя. Не бейте тапками


Ответы (1 шт):

Автор решения: Amgarak

Идея в чем, пока не нажмем ❌, мы будем перерегистрировать следующий обработчик на нашу же функцию с игрой bot.register_next_step_handler(message, callback=play_game).

После того как нажимаем ❌, мы снимаем bot.clear_step_handler_by_chat_id(message.chat.id) регистрацию следующего шага с игры и получаем доступ к основному обработчику сообщений.

import telebot
from telebot import types
import random

TOKEN = 'Token'
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(commands=['game']) # игра в камень ножницы бумага
def game(message):
    markup = types.ReplyKeyboardMarkup(row_width=3)
    markup.add(types.KeyboardButton('?'), types.KeyboardButton('✂️'), types.KeyboardButton('?'), types.KeyboardButton('❌'))
    bot.reply_to(message, "Добро пожаловать в игру 'Камень, ножницы, бумага'! Для игры используйте кнопки ниже:", reply_markup=markup)
    bot.register_next_step_handler(message, callback=play_game)
    
@bot.message_handler(func=lambda message: True)
def handle_messages(message):
    bot.reply_to(message, "Привет, я приглашаю тебя сыгрыть в игру /game")        

def play_game(message):
    user_choice = message.text
    bot_choice = random.choice(['?', '✂️', '?'])
    if user_choice not in ['?', '✂️', '?', '❌']:
        bot.reply_to(message, "Пожалуйста, используйте кнопки для выбора камня, ножниц или бумаги.")
        bot.register_next_step_handler(message, callback=play_game)

    if user_choice == bot_choice:
        bot.reply_to(message, f"Вы выбрали {user_choice}, и я выбрал {bot_choice}. Ничья!")
        bot.register_next_step_handler(message, callback=play_game)
    elif (user_choice == '?' and bot_choice == '✂️') or (user_choice == '✂️' and bot_choice == '?') or (user_choice == '?' and bot_choice == '?'):
        bot.reply_to(message, f"Вы выбрали {user_choice}, а я выбрал {bot_choice}. Вы победили! ?")
        bot.register_next_step_handler(message, callback=play_game)
    else:
        bot.reply_to(message, f"Вы выбрали {user_choice}, а я выбрал {bot_choice}. Я победил! ?")
        bot.register_next_step_handler(message, callback=play_game)
    if message.text == '❌':  
        a = types.ReplyKeyboardRemove()
        msg=bot.send_message(message.chat.id, 'Игра окончена! Возвращайся ещё', reply_markup=a)
        bot.clear_step_handler_by_chat_id(message.chat.id)
        
bot.polling()
→ Ссылка