首页 > 解决方案 > discord python - 计算一周的消息并保存它们

问题描述

我有一个问题,但找不到答案。我想计算消息,但只计算周一到周日的消息,并在德国时间凌晨 12 点将计数器重置为零。

我知道这适用于计数消息:

channel = bot.get_channel(721833279711477941)
count = 0
async for _ in channel.history(limit=None):
   count += 1
await channel.send(f"{count} messages in this channel")

我知道如何计算频道消息,但我不知道如何计算所有消息,从一周开始,保存计数的消息,并让机器人感到舒适,所以他不需要太多时间来计算它.

显然,机器人不应该花一段时间来计算消息。我不想要那个。所以我想到了将所有计数的消息保存在数据库中,并在每条消息处向前计数。但是机器人仍然应该计算一周中特定频道中的每条消息(也许他只做一次,将其存储在数据库中)。

我需要这个功能来学习它如何在 python 中工作,并希望使用 {count} 占位符作为不和谐通道。我希望我解释得很好,并且对你来说可以理解。

标签: pythonpython-3.xdiscord.pymysql-pythondiscord.py-rewrite

解决方案


您可以使用datetime库制作一些简单的函数来计算上周一和下周日的时间,因为您想计算该时间内的消息量,一些可以工作的代码如下:

def last_monday():
    today = datetime.datetime.today()
    monday = today - datetime.timedelta(days=today.weekday())
    return monday


def next_sunday():
    today = datetime.datetime.today()
    sunday = today + datetime.timedelta((6-today.weekday()) % 7)
    return sunday

这些函数计算上周一或下周日以今天为参考并添加或减去必要的天数。返回值采用日期时间接受的格式。

然后在您的discord.py代码中,您可以简单地在调用中使用beforeafterchannel.history来告诉 Discord 查找这些消息的时间范围。使用我在上面发布的函数,您的不和谐函数应该具有以下方面的内容:

channel = bot.get_channel(721833279711477941)
messages = channel.history(limit=None, before=next_sunday(), after=last_monday()).flatten()
count = len(messages)
await channel.send(f"{count} messages in this channel")

推荐阅读