Skip to content
Advertisement

Using MongoDB on Discord.py for scheduled tasks

Purpose

I have some commands like temp-mute, temp-ban, and other commands that need to be done after commands execution, and I do need to schedule things like giveaways and trigger a function as soon as the subscription ends, from a command.

What do I want?

I want to store all my timings and things in MongoDB and then make it trigger at the time that the function needs to be triggered. I currently use await asyncio.sleep(seconds), but that stops when I restart the bot or if the bot goes offline, I want the function to trigger as soon as it comes online if the time is passed, or I want it to trigger on time even after the bot restarts.

Advertisement

Answer

You can use @tasks.loop().

from pymongo import MongoClient
cluster = MongoClient("mongo_url_here")
collection = cluster["name"]

This might be how you describe the collection. Now , when you temp ban or temp mute someone you need to save the final time. You can do this like this ,

current_time = datetime.datetime.now()
final_time = current_time + datetime.timedelta(seconds=seconds_here)

Save the final_time in the database then.

Now you need to create a @tasks.loop(seconds=x)

x means that “after every x seconds the function inside @tasks.loop() will run

@tasks.loop(seconds=10)
async def checker(self):
    try:
        all = collection.find({}) # return all documents inside the db
        current_time = datetime.datetime.now()
        async for x in all:
            if current >= x["Time"]: # do stuff after this
            else:
                pass
    except Exception:
        pass

x["Time"] -> This can be a variable in document which stores the final_time

{“id” : id , “Time” : final_time} -> Like this

Now , async def checker(self): -> Checker is a function , you need to start it. It depends on whether you are using cog or not

If not -> checker.start() # Anywhere in code to start

If it is cog -> self.checker.start() # Should be placed inside `init

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement