如何实现Discord全服务器成员消息统计命令
Discord服务器成员消息统计命令报错修复
你编写的Discord机器人命令意图统计指定成员在全服务器的消息总数,但运行时出现报错,原代码如下:
@bot.tree.command(name="message_count", description = "see members message count in the server") async def message_count(ctx:discord.Interaction, member: discord.Member): counter = 0 for channel in ctx.guild.channels: async for message in channel.history(limit = 100): if message.author == member: counter += 1 await ctx.send(f'{member.mention} has sent **{counter}** messages in this server.')
报错原因
- 遍历了非文本频道:
ctx.guild.channels包含服务器内所有类型的频道(语音、分类、公告等),这些频道没有history()方法,调用时会触发属性错误。 - 消息发送方式错误:
ctx是discord.Interaction对象,不能用ctx.send()发送消息,需使用交互专属的消息发送方法。 - 缺少超时处理:全频道消息统计耗时较长,未做延迟响应会导致Discord判定交互超时。
修正后的代码
import discord from discord.ext import commands @bot.tree.command(name="message_count", description="查看服务器内成员的消息总数") async def message_count(ctx: discord.Interaction, member: discord.Member): # 发送延迟响应,避免超时 await ctx.response.defer(ephemeral=False) counter = 0 # 仅遍历服务器内的文本频道 for channel in ctx.guild.text_channels: try: # 遍历频道历史消息,limit=None表示获取所有可获取的历史消息 async for message in channel.history(limit=None): if message.author == member: counter += 1 except discord.Forbidden: # 跳过机器人无权限访问的频道 continue except discord.HTTPException: # 处理API请求异常 continue # 通过followup发送最终统计结果 await ctx.followup.send(f'{member.mention} 在本服务器共发送了 **{counter}** 条消息。')
关键修正说明
- 筛选文本频道:用
ctx.guild.text_channels替代ctx.guild.channels,只处理有消息历史的文本频道。 - 延迟响应:
ctx.response.defer()告诉Discord机器人正在处理,避免交互超时。 - 异常捕获:跳过无权限或请求失败的频道,保证命令能正常运行完成。
- 正确发送消息:使用
ctx.followup.send()发送统计结果,符合交互命令的消息发送规范。 - 消息范围调整:
limit=None会获取频道内所有可获取的历史消息(受Discord API限制,过旧的消息可能无法获取),如果只需要最近100条,可改回limit=100。
内容的提问来源于stack exchange,提问作者xAGTx47 0047
相关产品推荐
相关产品推荐

