S
S
Sergey Denisov2020-07-17 19:30:11
Python
Sergey Denisov, 2020-07-17 19:30:11

How to send scheduled messages with aiogram?

Hello, how can I implement the sending of messages on a schedule? I use the aiogram python bot library.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sotanodroid, 2020-07-19
@Belshed

You can use the EventLoop call_at function: https://docs.python.org/3/library/asyncio-eventloo...
For example, you need to send a message at a certain interval.
We get the time from the current event loop, add an interval to it - this will be the time of the function call.
Next, create a task to call at this time.
The call_at function takes a time parameter when to call the function, and the function itself as the second argument. The third and further arguments can be passed arguments for the called function.

loop = asyncio.get_event_loop()
delay = 100.0

async def my_func():
    # твоя логика с отправкой сообщений тут
    when_to_call = loop.time() + delay  # delay -- промежуток времени в секундах.
    loop.call_at(when_to_call, my_callback)

def my_callback():
    asyncio.ensure_future(my_func())

Thus, you will loop your function call by interval.
Don't forget also that your event loop should run indefinitely in this case: https://docs.python.org/3/library/asyncio-eventloo...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question