Answer the question
In order to leave comments, you need to log in
How do decorators work in aiogram?
I'm making a bot for VK using vk_api . Previously, I only worked with telegram through aiogram . Everything was clear there - you write a function through a decorator, for example , and it itself is called at the right time, in this case, in any state and the / start command .
And VK has nothing of the kind. There simply in a cycle you check an event.
So, I wanted to ask how these decorators work in aiogram? Maybe I'll try to do something similar on my own, so that the function itself is called at the right time, but for this I need to understand how it is implemented by aiogram.
Answer the question
In order to leave comments, you need to log in
In fact, it is through decorators aiogram (not the only library that does this) that registers a command handler.
An example of such an implementation:
class Bot:
def __init__(self):
self.handlers = dict()
self.on_message = None
def on(self, command):
def decorator(func):
self.handlers[command] = func
return func
return decorator
def handle(self, event)
if event["object"]["message"]["text"] in self.handlers:
self.handlers[event["object"]["message"]["text"]](event["object"])
elif self.on_message is not None:
self.on_message(event["object"])
bot = Bot()
@bot.on("привет")
def hello_handler(msg):
print(f"Hello: {msg}")
# Для ответа можете реализовать отдельную функцию, которая обращается к vk_api
def on_message(msg):
print(msg)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question