T
T
Telmor2021-11-08 20:39:33
Python
Telmor, 2021-11-08 20:39:33

How do I repeat an action every 5 minutes in discord.py so that it doesn't disable other commands?

I am writing a bot now, and I have a need for a time check. Simply put. I enter the time in the database and I need to compare the time now with the one in the database every 5 minutes. And if the time is now more than in the database - do actions. Simply put, if when subtracting from the time which is now the time from the database, a positive number is obtained to do something. But I need this to happen all the time, even after the bot is restarted. And I need to do several such checks almost simultaneously. And the main thing is that these checks go along with the work of the bot, and that the commands work for it. How can I do it?
I did a check at the end of the command and in the event on_ready . But after that, my bot stopped responding to commands. How can I fix this?
The code:

while True:
        for guild in bot.guilds:
            for member in guild.members:

                    test = spons.find_one({'_id': member.id})['r_id']
                    if test != 0:
                        timers = spons.find_one({'_id': member.id})['time_role']
                        print(timers)
                        print('Время с бд')
                        print('============================')
                        rol_i = spons.find_one({'_id': member.id})['r_id']
                        rols = discord.utils.get(member.guild.roles, id=rol_i)
                        time_now = int(time.time())
                        print(time_now)
                        print('Время сейчас')
                        print('============================')
                        delta = time_now - timers
                        print(delta)
                        print('Разница')
                        print('============================')
                        if delta >= 0:

Please help me with this issue.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin, 2021-11-08
@Telmor

You can use the timer, which is included in the asyncio library.
await asyncio.sleep(10) # время в секундах

Z
Zero None, 2021-11-09
@ZERRITO

You can do as Konstantin wrote, or you can use the built-in decorator.
Example:

from discord.ext import tasks
...

@tasks.loop(seconds=1) # Сколько секунд цикл будет "спать" перед повторным выполнением
async def newloop():
    # Код внутри цикла

@newloop.before_loop # Действие перед началом задачи
async def before_newloop():
  await Bot.wait_until_ready() # Подождать, пока бот не будет полностью запущен (У меня Bot - переменная бота. У вас может быть client, bot и тд...)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question