Ошибка на Ubuntu 20.04 python aiogram, ValueError: set_wakeup_fd only works in main thread of the main interpreter

Вот полный код(убрал оттуда лишнее, чтобы не мешало).

async def main() -> None:
    await dp.start_polling(bot)


def create_new_bot(token, char_id, char_name, bots, greeting):
    async def start_bot(dp, bot):
        event_loop.create_task(dp.start_polling(bot))

    def bot_init(event_loop, token, char_name, char_id, greeting):
        bot = Bot(token=token)
        dp = Dispatcher()

        event_loop.run_until_complete(start_bot(dp, bot))

    if __name__ == '__main__':
        event_loop = asyncio.new_event_loop()
        if bots is not None:
            for bot in bots:
                try:
                    bot_init(event_loop, bot[2], bot[4], bot[3], bot[5])
                except:
                    pass
        else:
            bot_init(event_loop, token, char_name, char_id, greeting)

        event_loop.run_forever()

if __name__ == "__main__":
    cur.execute("SELECT * FROM bots")
    bots = cur.fetchall()
    th = Thread(target=create_new_bot, args=(None, None, None, bots, None))
    th.start()
    asyncio.run(main())

Вот полный код ошибки

Traceback (most recent call last):
  File "/root/python_projects/ai_character_311/lib/python3.11/site-packages/aiogram/dispatcher/dispatcher.py", line 507, in start_polling
    loop.add_signal_handler(
  File "/usr/lib/python3.11/asyncio/unix_events.py", line 107, in add_signal_handler
    raise RuntimeError(str(exc))
RuntimeError: set_wakeup_fd only works in main thread of the main interpreter
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<Dispatcher.start_polling() done, defined at /root/python_projects/ai_character_311/lib/python3.11/site-packages/aiogram/dispatcher/dispatcher.py:457> exception=RuntimeError('set_wakeup_fd only works in main thread of the main interpreter')>
Traceback (most recent call last):
  File "/usr/lib/python3.11/asyncio/unix_events.py", line 105, in add_signal_handler
    signal.set_wakeup_fd(self._csock.fileno())
ValueError: set_wakeup_fd only works in main thread of the main interpreter

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/root/python_projects/ai_character_311/lib/python3.11/site-packages/aiogram/dispatcher/dispatcher.py", line 507, in start_polling
    loop.add_signal_handler(
  File "/usr/lib/python3.11/asyncio/unix_events.py", line 107, in add_signal_handler
    raise RuntimeError(str(exc))
RuntimeError: set_wakeup_fd only works in main thread of the main interpreter

Да, знаю что мультибота делать таким образом не самая лучшая идея, но в целом мне пойдет. Самое главное, что ошибка происходит только на линуксе, на винде всё работает нормально.


Ответы (1 шт):

Автор решения: Vlad

Два пути решения:

  1. Запускай бота в отдельном процессе (multiprocessing). Внутри каждого процесса есть свой main поток, таким образом бот будет работать в там где требует т.е. в мейне. Не забывайте про количество ядер на сервере.

  2. Запускать бота как отдельный сервис, через systemd. Этот путь предпочтительнее.

→ Ссылка