pyTelegramBotAPI как структурировать хэндлеры

Как разнести хэндлеры, отвечающие за разные части проекта по разным файлам? Чтобы файл main.py содержал только примерно это.

from .handlers import *
import telebot
bot = telebot.Telebot(TOKEN)
bot.polling()

В то время как

@bot.message_handler(regexp='Something about user')

и

@bot.message_handler(regexp='Something about product')

Были внутри разных скриптов?


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

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

Можно использовать систему похожую на коги в discord.py.

Структура папки с ботом:

handlers/ # folder with your handlers
    hand1.py # handler file
main.py # main

main.py:

import os

import telebot
bot = telebot.Telebot(TOKEN)

for x in os.listdir("./handlers/"): # looking for files in ./handlers/ folder
    if x.endswith(".py"): # ignore non-python files
        cog = __import__("handlers." + x[:-3]) # __import__ is a built-in python function that allows dynamic imports
                                               # x[:-3] removes ".py" at the end of the files' names
        cog.run(bot) # run cog, so all handlers in it will be registered on a `bot` Telebot instance

bot.polling()

handlers/hand1.py:

def run(bot): # main cog's function
              # when you call it, all handlers inside it will be registered
              # on a `bot` Telebot instance
    @bot.message_handler(regexp='Something about user')
    def handler_name(message):
        pass # put your handler's code here
→ Ссылка