如何使用Discord.py统计指定角色过去28天内的消息发送总量
Discord角色消息统计命令修正
你原有代码存在以下几处错误:
- 判断逻辑错误:
message.author == role是将用户对象和角色对象直接对比,永远返回False,正确逻辑是判断指定角色是否在消息发送者的角色列表中 - 缺少时间筛选:
channel.history()未指定时间范围,默认只会拉取最近100条消息,也无法匹配你要统计过去28天数据的需求 - 消息发送位置错误:
await ctx.send写在遍历循环内部,会导致每扫一条消息就发一次统计结果,造成频道刷屏 - 仅统计当前频道:原有代码只会统计命令触发的当前频道的消息,如需统计整个服务器所有可访问频道的消息需要额外遍历服务器频道列表
修正后的单频道统计代码
import datetime import discord from discord.ext import commands @commands.command() async def messagesrole(ctx, role: discord.Role): counter = 0 # 计算28天前的UTC时间,适配Discord时间标准 time_limit = datetime.datetime.utcnow() - datetime.timedelta(days=28) # 遍历当前频道28天内的所有消息 async for message in ctx.channel.history(after=time_limit, limit=None): # 排除机器人发送的消息,不需要可以删掉下面这行 if message.author.bot: continue if role in message.author.roles: counter += 1 # 遍历完成后再发送统计结果 await ctx.send(f'拥有{role.name}角色的成员过去28天在本频道共发送了{counter}条消息')
全服务器统计版本(可选)
如果需要统计整个服务器所有机器人可访问的文字频道的消息,改用以下代码:
import datetime import discord from discord.ext import commands @commands.command() async def messagesrole(ctx, role: discord.Role): counter = 0 time_limit = datetime.datetime.utcnow() - datetime.timedelta(days=28) # 遍历服务器所有文字频道 for channel in ctx.guild.text_channels: # 跳过机器人没有读消息权限的频道 if not channel.permissions_for(ctx.guild.me).read_message_history: continue async for message in channel.history(after=time_limit, limit=None): if message.author.bot: continue if role in message.author.roles: counter += 1 await ctx.send(f'拥有{role.name}角色的成员过去28天在本服务器共发送了{counter}条消息')
注意事项
- 使用前需要确保你的机器人开启了
Message Content Intent权限,否则无法读取消息内容,在Discord开发者后台的机器人设置页即可开启 - 服务器消息量较大时统计会有明显延迟,属于正常情况
内容的提问来源于stack exchange,提问作者Clasher
相关产品推荐
相关产品推荐

