skip to Main Content

I am developing a telegram bot, and I have many handlers for responses from the user.

Since there are many handlers and many different dialogs are also possible. I moved some of the handlers into different classes (Dialogs)

import telebot
bot = telebot.TeleBot(tg_api_key)

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

def buy(message):

    from dialogs.buy_something
    import Buy_Dialog
    w = Buy_Dialog(bot, message)

and:

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

def sell(message):
    from dialogs.sell_something 
    import Sell_Dialog
    w = Sell_Dialog(bot, message)

Inside the dialog classes I can send questions to the user and get answers from them by using:

self.m = self.bot.send_message(message.chat.id, "Some question")
self.bot.register_next_step_handler(self.m, self.enter_your_name)

But now I need to get from user callback from button click:

@bot.callback_query_handler(func=lambda call: True)
def button_click_yes_or_no(self, call):

So I can catch them only from main.py, not inside the dialog.

How to redesign code to get clear logic and code with the ability to catch button_callback?

2

Answers


  1. maybe the function can’t see your variable try to make your variable global in the beginning of the code :

    global your variable, another variable
    
    Login or Signup to reply.
  2. You cannot catch callbacks from inside the class instance.

    But you can follow the same logic as for commands: create a decorated general function for catch all calls and pass each one to proper class instance based on call’s content (call.data or call.message.chat.id).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search