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

discord.py中Unban命令报错TypeError,如何修正?

问题解决:discord.py /unban命令 TypeError 错误

错误原因

你遍历infractions字典时,直接用for i in infractions得到的是字典的键(caseid字符串),而非对应的违规记录字典。所以尝试用i["user"]访问字符串的索引会触发TypeError。

另外还有两个潜在问题:

  1. 违规记录中"user"存储的是字符串类型的用户ID,而user.id是整数,直接对比会不匹配
  2. await user.unban()需要指定服务器(Guild),否则无法完成解封操作

修复后的完整代码

async def openinf():
    with open("infractions.json", "r") as f:
        users = json.load(f)
    return users

async def createinfraction(user, type, mod, date, caseid, reason, expireson = None):
        infractions = await openinf()
        
        infractions[str(caseid)] = {}
        infractions[str(caseid)]["type"] = str(type)
        infractions[str(caseid)]["mod"] = str(mod.id)
        infractions[str(caseid)]["date"] = str(date)
        infractions[str(caseid)]["user"] = str(user.id)
        infractions[str(caseid)]["reason"] = str(reason)
        infractions[str(caseid)]["avatar"] = str(user.avatar)
        infractions[str(caseid)]["expireson"] = str(expireson)
        infractions[str(caseid)]["status"] = "Active"


        with open("infractions.json", "w") as f:
            json.dump(infractions, f)
        return True

@client.tree.command()
@commands.has_role(modrole)
@app_commands.describe(user = "Provide an ID of the user to unban.")
async def unban(interaction : discord.Interaction, user : str):
        user = await client.fetch_user(int(user))

        infractions = await openinf()

        # 遍历字典的键值对,case_id是案件ID,infraction是对应的违规记录
        for case_id, infraction in infractions.items():
            # 转换类型后对比用户ID
            if infraction["user"] == str(user.id):
                if infraction["type"] == "Ban" and infraction["status"] == "Active":
                    # 指定服务器解封用户
                    await interaction.guild.unban(user)
                    await interaction.response.send_message(content=f"{user} has been unbanned!", ephemeral=True)
                    # 更新违规记录状态
                    infraction["status"] = "Revoked"
                    with open("infractions.json", "w") as f:
                        json.dump(infractions, f)
                    return
        
        # 如果没找到对应记录,返回提示
        await interaction.response.send_message(content="No active ban record found for this user.", ephemeral=True)

修改要点说明

  1. 遍历方式修正:使用infractions.items()同时获取案件ID和对应的违规记录字典,避免直接操作字符串键
  2. ID类型匹配:将user.id转为字符串,和违规记录中存储的字符串类型ID对比
  3. 指定服务器解封:使用interaction.guild.unban(user)明确指定当前交互所在的服务器执行解封
  4. 添加无记录提示:遍历结束后如果未找到有效记录,给用户反馈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:12:45