Discord.py,是否可以每1小时运行一个任务?

Discord.py, Is it possible to run a task every 1 hour?

我想制作一个机器人,每 1 小时统计一次公会中在线成员的数量。然后,它找到服务器的平均值“activity”。问题是我不知道如何每 1 小时左右 运行“计数任务”。这是我到目前为止得到的:

@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)

此代码统计会员^

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()

这应该每 1 小时计算一次成员,但是,我没有办法为这段代码和平传递上下文: for user in ctx.guild.members:

有时,您需要记住,如果您不通过 f.start() 循环,您的机器人 'smart' 不足以知道 ctx 的来源。无论哪种方式,您都不应该将 ctx 传递到您的循环中,因为您的机器人将连接到多个服务器,那么您的机器人如何知道哪个服务器将成为您的 ctx.guild?

相反,我的建议是通过 bot.get_guild() 创建您自己的公会对象并通过那里迭代成员。请查看下面修改后的代码。

from discord.ext import tasks

@tasks.loop(hours=1) # alternatively, minutes=60, seconds=3600, etc.
async def f():
    memList = []
    guild = bot.get_guild(your_guild_id) # replace this with your server's id
    for user in guild.members:
        if user.status == discord.Status.offline:
            memList.append(user.id)

    total = len(memList)
    print(total)

f.start()

Bagle 的回答确实解决了我的 ctx 问题。在他们的帮助下,我设法解决了整个问题。因此,我决定 post 在这里为所有感兴趣的人提供。这是成品:

#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()