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

Discord机器人id命令报错TypeError,如何实现字符串与整数显示?

问题解决与代码修改

报错原因

discord.app_commands.errors.CommandInvokeError 触发的 TypeError: 字符串索引必须为整数,本质是你错误地将字符串当作字典来访问。调用request.json(content_type='text/html')解析后,fakeid['name']是字符串类型,而非你预期的嵌套字典,所以用['address']这种字符串键去索引自然会报错。

代码修改方案

实际调用https://api.namefake.com/返回的JSON里,address是和name同级的顶级字段,并非嵌套在name下。同时要完善异常处理和分支逻辑,确保整数、字符串类型数据都能正常显示(f-string会自动处理类型转换)。

修改后的完整代码:

@commands.hybrid_command(
    name="id",
    description="生成虚假用户信息",
)
async def id(self, context: Context) -> None:
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.namefake.com/") as request:
            if request.status == 200:
                try:
                    # 解析API返回的JSON数据
                    fakeid = await request.json(content_type='text/html')
                    # 构建Embed,同时展示字符串和整数类型数据
                    embed = discord.Embed(
                        title="虚假身份信息",
                        color=0x9C84EF
                    )
                    # 添加字符串类型字段
                    embed.add_field(name="姓名", value=fakeid['name'], inline=False)
                    embed.add_field(name="地址", value=fakeid['address'], inline=False)
                    # 添加整数类型字段(示例:以API返回的zip字段为例,实际可根据需求调整)
                    embed.add_field(name="邮编", value=fakeid['zip'], inline=False)
                    await context.send(embed=embed)
                except KeyError as e:
                    await context.send(f"数据解析错误:缺失字段 {e}")
                except Exception as e:
                    await context.send(f"处理失败:{str(e)}")
            else:
                await context.send(f"请求失败,状态码:{request.status}")

关键说明

  • 修正字段访问路径:address是顶级字段,直接用fakeid['address']访问即可
  • 异常捕获机制:处理解析失败、字段缺失等情况,避免机器人崩溃
  • 类型适配:Discord的Embed会自动适配整数和字符串类型,无需额外转换,直接传入数据即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:27:36