L
L
lleballex2020-07-01 16:47:22
Python
lleballex, 2020-07-01 16:47:22

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 @dp.message_handler(commands=['start'], state='*'), 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

2 answer(s)
C
cython, 2020-07-01
@lleballex

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)

Here you also need to implement the initialization of the bot, the main loop and launch.

B
buvanenko, 2020-09-20
@buvanenko

The solution is simple: don't use vk_api. Even its developer advises to use more advanced analogs with support for asynchrony, such as vkbottle.
And after aiogram it will be easy for you to change seats.
https://github.com/timoniq/vkbottle

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question