how to pass variable or object to dp.message_handler decorated function? #551
Answered
by
Olegt0rr
TonyZhang03
asked this question in
Q&A
-
I can't find an example provided by the package helpful to build a real chatbot. Can anyone here help to explain how or give an example? here is my problem. Thank you in advance. |
Beta Was this translation helpful? Give feedback.
Answered by
Olegt0rr
Mar 31, 2021
Replies: 1 comment
-
If you wanna pass a function to your handler just import it and use it directly. Direct usagedef generate_text():
return "generated text"
async def handler(message: Message):
text = generate_text()
await message.answer(text) Middleware usageCreate a middlewarefrom aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message
class YourMiddleware(BaseMiddleware):
async def on_pre_process_message(self, message: Message, data: dict):
# `text` is a name of var passed to handler
data["text"] = generate_text() Register it via Dispatcher (on_startup)dp.middleware.setup(YourMiddleware()) Get
|
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
JrooTJunior
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you wanna pass a function to your handler just import it and use it directly.
If you wanna apply it for some handlers, you should use a middleware.
Direct usage
Middleware usage
Create a middleware
Register it via Dispatcher (on_startup)