Search code examples
pythondiscorddiscord.py

how to run a command in tasks.loop discord.py bot


so im trying to get a command to run every 5 minutes on my dsicrod.py bot and need ctx to get guild members and certain details like that so I need it in a bot.command, but I cant have that properly do that without tasks.loop(minutes=5) so I tried getting it to send the command with tasks.loop but it wouldn't work so I went to the pythin discord and got help they got me to this point

@bot.command(pass_context=True)
async def update_member_count(ctx): 
    await ctx.send(ctx.guild.member_count)
    channel = discord.utils.get(ctx.guild.channels, id=829355122122424330)
    await channel.edit(name = f'Member Count: {ctx.guild.member_count}')


@tasks.loop(minutes=5)
async def update_member_count2(ctx):
    await update_member_count(ctx)

and It still gives errors saying that ctx arg is missing in update_member_count2. pls help


Solution

  • You can create your loop-function in another way. Your approach is a bit unclear to me.

    Try out the following:

    async def update_member_count(ctx):
        while True:
            await ctx.send(ctx.guild.member_count)
            channel = discord.utils.get(ctx.guild.channels, id=YourID)
            await channel.edit(name=f'Member Count: {ctx.guild.member_count}')
            await asyncio.sleep(TimeInSeconds)
    
    
    @bot.command()
    async def updatem(ctx):
        bot.loop.create_task(update_member_count(ctx))  # Create loop/task
        await ctx.send("Loop started, changed member count.") # Optional
    

    (Or you simply create the task in your on_ready event, depends on you)

    What did we do?

    • Created a loop out of a function (async def update_member_count(ctx):)
    • Exectued updatem one time to activate the loop
    • Changed your actual command to a "function"