简体   繁体   中英

How to design python code for telegram (telebot lib)?

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 ?

也许函数看不到您的变量尝试在代码的开头使您的变量成为全局变量:

global your variable, another variable

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM