-
I'd like to store different message functions in different files, and then call them once DP says it's time to do so. Is that an option? Because right now I have a bunch of spaghetti code which is a mixture of message/callback handlers in one 600+ lines file. If I want to add any functionality in the future, it would just visually clog up the bot.py file even more. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
I've found what I was looking for, though, it surprises me how little info there's on the framework online. Though, I'll try to give my own explanation on the topic.
Here's your from handlers.message import message_handler
from handlers.callback import callback_handler
...
if __name__ == '__main__':
message_handler.setup(dp)
callback_handler.setup(dp)
executor.start_polling(dp, skip_updates=True) Here's async def hi(message: aiogram.types.Message, state: aiogram.dispatcher.FSMContext):
await message.answer('Hi~!')
def setup(dp: Dispatcher):
dp.register_message_handler(hi, content_types=['text'], state='*') Here's async def some_callback(call: aiogram.types.CallbackQuery, state: aiogram.dispatcher.FSMContext):
await bot.answer_callback_query(call.id)
await message.answer('Hi~! But from an inline button')
def setup(dp: Dispatcher):
dp.register_callback_query_handler(some_callback, lambda call: call.data == 'some_callback_data') Once you distribute them all like that, you should be good to go. Just make sure you don't import anything from |
Beta Was this translation helpful? Give feedback.
-
Best solution# file_1.py
from aiogram import Router
router = Router()
@router.message(CommandStart())
async def command_start_handler(message: Message) -> None:
pass # main.py
from file1 import router
dp = Dispatcher()
dp.include_router(tg_router)
dp.start_polling(bot) |
Beta Was this translation helpful? Give feedback.
I've found what I was looking for, though, it surprises me how little info there's on the framework online.
If anyone wonders how to do it, here is the topic that helped me: #378
Though, I'll try to give my own explanation on the topic.
You should have your entry point, i.e. your main file (
__main__.py
in my case), and the modules that you want (e.g.message_handler.py
,callback_handler.py
). You might want to put the message and the callback handlers separately.My folder structure looks like this:
Here's your
__main__
: