E
E
estry2021-09-28 17:18:47
Python
estry, 2021-09-28 17:18:47

How to pass an object to another Python file?

Hey!
There is a project in Python.
The start.py file from which the entire project starts. Here is its content:

from aiogram import Bot, Dispatcher

from tgbot.handlers.hello import hello_user

def create_pool(user, password, database, host, echo):
    raise NotImplementedError  # TODO check your db connector


async def main():
 
    bot = Bot(token=config.tg_bot.token)
    dp = Dispatcher(bot, storage=storage)

    hello_user(dp)

   
if __name__ == '__main__':
    try:
        asyncio.get_event_loop().run_until_complete(main())
        #asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logger.error("Bot stopped!")


There is a hello.py file in the handlers folder. Its content:
from aiogram import Dispatcher
from aiogram import types


async def user_hello(m: types.Message):
    await m.answer('Привет, ' + m.from_user.username + ', выбери с чего хочешь начать:')


def hello_user(dp: Dispatcher):
    dp.register_message_handler(user_hello, commands=['start'])


I need to pass the bot object from the start.py file to the hello.py file. Tried through import, from bot import bot - it doesn't work.
How can I implement the transfer of the bot object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-09-29
@MEDIOFF

Take out the bot declaration in a separate file like bot.py, and then import it into both main.py and hello.py

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question