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:
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.