discord.py(pycord) task.loop(time=time) runs function indefinitely

286 views Asked by At

I am making a discord bot with py-cord, that runs a specific function once on every specific time. However, my discord bot starts to run the function infinitely after the set time passes. The bot is running on a cloud server, maybe something happens on reconnecting, but I could not figure it out.

Here is my code

import discord
import datetime
from discord.ext import commands, tasks
import requests

utc = datetime.timezone(datetime.timedelta(hours=9))
send_time = datetime.time(hour=1, minute=0,tzinfo=utc)

class dailyNotice(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.my_task.start()

    def cog_unload(self):
        self.my_task.cancel()

    @tasks.loop(time=send_time)
    async def my_task(self):
         another_function()

    @my_task.before_loop
    async def before_printer(self):
        print('waiting...')
        await self.bot.wait_until_ready()

@bot.event
async def on_ready():
    await bot.change_presence(status=discord.Status.online)
    
    loaded_cogs = bot.cogs.keys()
    if "dailyNotice" in loaded_cogs:
        print('dailyNotice already running')
    elif "dailyNotice" not in loaded_cogs:
        print('dailyNotice')
        bot.add_cog(dailyNotice(bot))

EDITED

To be specific to my code, follow code is to prevent from cog running twice on reconnecting. But, although there are print() functions to print current cog status, there were no message printed on terminal.

    loaded_cogs = bot.cogs.keys()
    if "dailyNotice" in loaded_cogs:
        print('dailyNotice already running')
    elif "dailyNotice" not in loaded_cogs:
        print('dailyNotice')
        bot.add_cog(dailyNotice(bot))
1

There are 1 answers

0
Junah201 On

enter image description here

in pycord official docs, discord.ext.tasks.loop have reconnect option. and default value of reconnect is 'True'.

reconnect (bool) – Whether to handle errors and restart the task using an exponential back-off algorithm similar to the one used in discord.Client.connect().

If the reconnect option is set to True and an error occurred, tasks restart. I think that an error occured in your another_function(). So set your reconnect option as False and your can see an error.