You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py警告系统问题:Embed重复显示警告信息

问题解决:Discord.py警告系统Embed重复显示警告信息

问题原因

  1. 遍历对象错误:你用for w in check遍历的是find_one返回的单个文档(字典结构),这会遍历字典的所有键(比如user_id、reason、moderator_id等),每遍历一个键就重复添加一次相同的字段内容,导致信息重复显示。
  2. 单条记录限制:find_one仅返回匹配的第一条警告记录,若用户有多个警告,无法全部展示。

修复后的代码

@client.hybrid_command(name="warnings", with_app_command=True, description="View the warnings of a member", aliases=["punishments"])
async def warnings(ctx, member: discord.Member = None):
    if member is None:
        await ctx.reply("必须指定一个成员")
        return
    
    # 获取该用户的所有警告记录,而非单条
    warn_records = warndb.warn_logs.find({"user_id": member.id})
    warn_list = list(warn_records)
    
    if not warn_list:
        await ctx.reply("该用户没有警告记录")
        return
    
    embed = discord.Embed(color=embedcolor, title=f"{member.name}的警告记录")
    # 遍历每条警告记录,添加对应字段
    for idx, warn in enumerate(warn_list, start=1):
        reason = warn.get("reason", "无理由")
        moderator_id = warn.get("moderator_id", "未知")
        embed.add_field(
            name=f"警告 {idx}",
            value=f"**理由**: {reason}\n**警告者**: <@{moderator_id}>",
            inline=False
        )
    
    await ctx.send(embed=embed)

关键修改点

  • 替换find_one为find,获取用户所有警告记录
  • 遍历目标改为警告记录列表,而非单个文档的键
  • 给每条警告添加序号,区分不同记录,同时完整展示理由和警告者信息
  • 使用get方法避免因键不存在导致的潜在错误

内容的提问来源于stack exchange,提问作者TheRealKurumi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:40:32