'Discord.py, Is it possible to run a task every 1 hour?
I want to make a bot that counts the number of online members in a guild every 1 hour. Then, it finds the average "activity" of the server. The problem is that I don't know how to run the "counting task" every 1 hour or so. This is what I ve got so far:
@bot.command()
async def d(ctx):
memList = []
for user in ctx.guild.members:
if user.status == discord.Status.offline:
memList.append(user.id)
total = len(memList)
print(total)
This code counts the members^
from discord.ext import tasks
@tasks.loop(seconds=3600)
async def f(ctx):
memList = []
for user in ctx.guild.members:
if user.status == discord.Status.offline:
memList.append(user.id)
total = len(memList)
print(total)
f.start()
This is supposed to count the members every 1 hour, however, I don't have a way to pass the context for this peace of code:
for user in ctx.guild.members:
Solution 1:[1]
Bagle's answer really solved my problem with the ctx thing. With their help, I managed to solve the whole problem. So, I decided to post it here for anyone that's interested. This is the finished product:
#The required intents for this task
intents = discord.Intents.default()
intents.members = True
intents.presences = True
#The function
@tasks.loop(hours=1)
async def f():
guildList = dict() #I want to save the amount of online members in a dictionary for easier access.
onlineMemList = [] #Temporary list
for guild in bot.guilds: #Loop through all the guilds
for user in guild.members: #Loop through every user in the guild
if user.status == discord.Status.online:
onlineMemList.append(user.id) #Append the online members to the list
guildList.update({guild.name: len(onlineMemList)}) #Add the amount of online members to the dictionary with a key of guild.name
onlineMemList = [] #Empty the list
print(guildList)
f.start()
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 | Tony |
