F
F
Flaca Strexy2021-02-08 15:11:57
Python
Flaca Strexy, 2021-02-08 15:11:57

How to run a parallel loop in aiogram bot?

There is a bot in which you need 2 processes in parallel, the bot pulling itself and another cycle.
The 2 processes themselves work, but the problem is that messages are not sent in the cycle due to async functions, I can’t figure out how to do it, here is the code:
The function itself:

def is_enabled():
  while True:
    for user_id in users:
      send_message(user_id)
    time.sleep(15)

Send message function:
async def send_message(user_id=None):
  if user_id:
    await bot.send_message(chat_id=user_id, text='123')

The pulling itself and the loop:
if __name__ == '__main__':
  Process(target=is_enabled).start()
  Process(target=executor.start_polling(dp, skip_updates=True)).start()


The error is:
RuntimeWarning: coroutine 'send_message' was never awaited send_message (
user_id)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Flaca Strexy, 2021-02-09
@flacastrexy

made such a code, but the bot itself does not work, but the loop works...
UPD: the working version is below in the comment

async def is_enabled():
  print('запускаю цикл')
  while True:
    print('отправляю сообщения')
    for user_id in users:
      await bot.send_message(chat_id=user_id, text='123')
      print('отправил')
    print('жду')
    time.sleep(10)


async def on_startup(x):
  asyncio.create_task(is_enabled())


if __name__ == '__main__':

  executor.start_polling(dp, skip_updates=True, on_startup=on_startup)

D
Dr. Bacon, 2021-02-08
@bacon

Because this is async and Process is not needed here, create_task or the like is needed within the current event loop, and aiogram even has an on_startup parameter for start_polling or something like that.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question