'Python : Best way to do an infinite loop with an async function [closed]

I have a Discord Python script that retrieves data every second via an API. This data is then displayed as a bot status message. But with time, while True + async seems to crash after few hours and doesn't send anything without displaying any error. Here is the code:

@bot.event
async def on_ready():
  while True :
    data=api()
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=data))

I was told that the best way to make a script run continuously was to enter the script in crontab but since discord only works with asyncio the script does not finish and therefore cannot be restarted by cron. Moreover the minimum frequency is 1 minute.

Do you have any solution ?

Thanks



Solution 1:[1]

Use the ext.tasks which is provided by the library. Here is an example

from discord.ext import commands, tasks


@tasks.loop(seconds=60) # will repeat every 60 seconds
async def change_presence():
    data = api()
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=data))


change_presence.start()
bot.run(...)

The above code Will break if you are using master branch of dpy if you are on master branch, start the task in the following manner

import asyncio
from discord.ext import commands, tasks


@tasks.loop(seconds=60) # will repeat every 60 seconds
async def change_presence():
    data = api()
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=data))

async def main():
    async with bot:
        change_presence.start()
        await bot.start(...)

asyncio.run(main())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SELECT stupidity FROM discord