Q
Q
qwwwwwty2021-10-25 01:08:49
Python
qwwwwwty, 2021-10-25 01:08:49

How to make bot send message every 30 seconds, Python Aiogram?

it is necessary that the bot send a message (a random bunch of words from the list) once every 30 seconds to the conversation, so that the cycle is endless and does not break. I already have the code, but the problem is that the bot works properly (posts a message to the conversation as it should), BUT because of my function, the bot began to ignore commands (for example, !help). here is my function itself:

loop = asyncio.get_event_loop()
bot = Bot("3213213131", loop)

a = ["привет", "мир", ]
print(random.choice(a))

b = ["как", "дела?", ]
print(random.choice(b))

local_time = "30"
from aiogram import Bot
import asyncio
import time
import random

async def helloworld():
    while True:
        bot_info = await bot.get_me()
        print(bot_info.username)
        time.sleep(int(local_time))
        await dp.bot.send_message(config.GROUP_ID, text = (random.choice(a) +" "+ random.choice(b)))
        print(random.choice(a))
        print(random.choice(b))
    
    

if __name__ == '__main__':
    try:
        loop.run_until_complete(helloworld())
    except KeyboardInterrupt:
        loop.stop()



#run long-polling
if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)


by the way, the console does not give errors and in fact everything works as it should, except for ignoring commands (for example !help)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-10-25
@qwwwwwty

Well, firstly, why do you need 2 main blocks?
At the same time, note that the first main block will not finish running until your helloworld() coroutine finishes running, since you are using the run_until_complete() method. And your coroutine will never finish its work.
Use loop.create_task() to schedule a coroutine to run "in the free time" of the system and continue working.

if __name__ == '__main__':
  loop.create_task(helloworld())
  executor.start_polling(dp, skip_updates=True)

Secondly, long-running synchronous operations in a coroutine block its work, and the work of other coroutines. This is the basics of asynchronous programming, damn it!
Therefore, your time.sleep() hangs the entire bot. Use await asyncio.sleep() , it will give control to other coroutines of the bot while the current coroutine sleeps.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question