统计一周内的留言并保存



我有一个问题,但是找不到答案。我想计数消息,但只从星期一到星期日的消息,并在德国时间上午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")

我知道如何计数频道消息,但我不知道如何计数所有消息,从一周开始,保存计数消息,并使bot感到舒适,因此他不需要太多时间来计数。

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

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

可以使用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代码中,只需在之前使用后和在对channel.history的呼叫中告诉Discord在哪里查找这些消息的时间范围。使用我上面发布的函数,你的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")

最新更新