'Discord bot going offline after a loop

I wanted to give my bot a presence that changes after a certain amount of time. (In this case 5 minutes)

@client.event
async def on_ready():
    while True:
        presence = randint(1, 5)
        if presence == 1:
            await client.change_presence(game=discord.Game(name='with commands', type=1))
        elif presence == 2:
            await client.change_presence(game=discord.Game(name='you', type=3))
        elif presence == 3:
            await client.change_presence(game=discord.Game(name='and watching', type=2))
        elif presence == 4:
            await client.change_presence(game=discord.Game(name='Youtube Videos', type=3))
        elif presence == 5:
            await client.change_presence(game=discord.Game(name='like a boss', type=1))
        time.sleep(300)

problem is that after the 300 seconds my bot goes offline on discord, while the python file is still running, and doesn't show any errors. Anyone who knows what's causing this? Thanks.



Solution 1:[1]

time.sleep(300) block your programm and the connection time out.
Use await asyncio.sleep(300) insead.

Solution 2:[2]

dont make loops like that in discord.py use the built in loop function from discord.ext import tasks, commands can be used like this:

from discord.ext import tasks, commands
@client.event
async def on_ready():
    loop.start()
@tasks.loop(seconds=0.3)
async def loop():
    presence = randint(1, 5)
    if presence == 1:
        await client.change_presence(game=discord.Game(name='with commands', type=1))
    elif presence == 2:
        await client.change_presence(game=discord.Game(name='you', type=3))
    elif presence == 3:
        await client.change_presence(game=discord.Game(name='and watching', type=2))
    elif presence == 4:
        await client.change_presence(game=discord.Game(name='Youtube Videos', type=3))
    elif presence == 5:
        await client.change_presence(game=discord.Game(name='like a boss', type=1))

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 iElden
Solution 2