Discord bot issue: 'client.loop.create_task(update_stats())' causing errors

I’m working on a Discord bot and I’m stuck. I want to track server activity and save it to a file. But when I try to run the bot, I get an error with client.loop.create_task(update_stats()).

Here’s a simplified version of what I’m trying to do:

import discord
import asyncio

client = discord.Client(intents=discord.Intents.default())

async def track_activity():
    while True:
        # Do some tracking stuff
        await asyncio.sleep(60)

@client.event
async def on_ready():
    print('Bot is ready!')

client.loop.create_task(track_activity())
client.run('MY_BOT_TOKEN')

The error message says something about ‘loop attribute cannot be accessed in non-async contexts’. I’m not sure what that means or how to fix it.

Can someone explain what I’m doing wrong and how to make this work? I’ve tried reorganizing things, but nothing seems to help.

The issue you’re encountering stems from how Discord.py handles event loops. To resolve this, you should initiate your background task within an asynchronous context. A reliable approach is to create a separate function for bot startup:

async def setup():
await client.wait_until_ready()
client.loop.create_task(track_activity())

client.loop.create_task(setup())
client.run(‘MY_BOT_TOKEN’)

This method ensures your task starts only after the bot is fully operational. It’s also worth noting that for more complex bots, consider using Discord.py’s built-in Cogs system for better organization and task management.

I’ve dealt with similar issues in my Discord bot projects. The problem lies in how you’re initializing the background task. Here’s what worked for me:

Instead of calling create_task() directly, wrap it in a coroutine and use it as a setup function. Like this:

async def setup():
await client.wait_until_ready()
client.loop.create_task(track_activity())

if name == ‘main’:
client.loop.run_until_complete(setup())
client.run(‘MY_BOT_TOKEN’)

This approach ensures the task starts only after the bot is fully initialized. It solved the async context errors for me and might work for you too.

Also, make sure you’re using the latest version of discord.py. Older versions sometimes have quirks with task creation.

hey there SpinningGalaxy! Looks like ur running into an async issue. try moving the create_task call inside the on_ready event. like this:

@client.event
async def on_ready():
print(‘Bot is ready!’)
client.loop.create_task(track_activity())

this should fix the loop error. lemme know if u need more help!