Z
Z
Zero None2021-11-05 22:18:35
Telegram
Zero None, 2021-11-05 22:18:35

Are there kogi or something similar in Telegram?

I used to work with telegram bots, but I wrote everything in one file, since the code was not too cumbersome. Then I moved to Discord, where I made bigger bots, and I learned from kogah, with which you can divide the bot into parts and scatter these very parts into files. The fact is that, unlike telebot, discord.py has such a function, and I was wondering if there are cogs (or can they be made) for telegram bots? (I understand that everything can be done, but the method itself is interesting to me) After all, large bots somehow work, and I very much doubt that they are shoved into one file.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-11-05
@Vindicar

You can do it yourself.
Look, a key feature in most bot libraries is registering how the bot reacts to events. And most often it is done by a decorator like @bot.command in discord.py or its equivalent in aiogram.
But what is a decorator? If it has no parameters, then

@some_decorator
def some_func():
    pass

it's the same as
def some_func():
    pass
some_func = some_decorator(some_func)

For decorators with parameters a little more complicated
@some_decorator(params)
def some_func():
    pass

will turn into
def some_func():
    pass
wrapper = some_decorator(params)
some_func = wrapper(some_func)

Hence the conclusion. A decorator is a function and can be stored in variables, called, and so on.
Then you can do this trick: write a proxy decorator that remembers what method we are decorating, and with what. More or less like this:
def proxy(storage, *args, **kwargs):
    def wrapper(func):
        storage.append((func.__name__, args, kwargs))
        return func
    return wrapper

And apply it like this:
class MyCustomCog:
    methods = []
    def __init__(self, bot):
        #задача конструктора - прочитать список отмеченных методов класса, 
        #и отдекорировать методы своего экземпляра класса (не одно и то же)
        for fn, args, kwargs in self.methods:
            #а тут вызываем декоратор вручную
            #что там вместо bot.event? можно сделать несколько прокси, или добавить еще один параметр
            decorator = bot.event(*args, **kwargs) 
            decorator(getattr(self, fn)) #теперь бот знает про наши обработчики событий
    #декоратор-прокси запоминает все декорированые методы в список methods
    #это можно реализовать и по другому, не суть. Главное, что мы запоминаем,
    #с какими параметрами потом вызывать декоратор реального бота - всё, что после methods
    @proxy(methods, "параметры", for="декоратора бота")
    async def some_handler(self, params):
        pass #обработчик того или иного события

This logic can be hidden in the base class, and inherited from it, so as not to be repeated a hundred times. And the proxy() itself can be made a method of this base class.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question