使用requests和json获取Discord消息失效的问题求助
问题:Discord API请求返回数据异常引发TypeError错误
我有一个运行近一年的Bot,用来读取Discord服务器频道消息,原本用以下代码以JSON格式获取最新消息:
r = requests.get(f'https://discord.com/api/v9/channels/{channelid}/messages?limit=1', headers=headers) jsonn = json.loads(r.text) for value in jsonn: print(value) current = str(value['embeds'])[1:500] if current != last: # 后续逻辑
现在这段代码突然抛出错误:
current = str(value['embeds'])[1:500] TypeError: string indices must be integers
原因分析与解决方法
错误根源
这个错误说明你遍历的value是字符串类型,而非预期的消息字典对象。大概率是Discord API返回的内容结构发生了变化:
- 原本API返回的是消息对象数组(
list类型),现在可能返回了错误信息字符串或错误字典(比如API版本过期、权限失效、请求被限流)。
排查与修复步骤
先确认API返回的实际内容
在json.loads之前添加打印语句,查看返回的原始文本和状态码:print(f"请求状态码: {r.status_code}") print(f"API返回内容: {r.text}")- 状态码
429:请求被限流,需添加重试机制或降低请求频率 - 状态码
401/403:token无效或Bot失去频道访问权限,需重新验证权限或更新token - 返回类似
{"message": "Unknown Route", "code": 10003}的内容:API路由或版本过时
- 状态码
更新API版本
当前使用的v9版本已被Discord API废弃,建议切换到最新稳定版(比如v10):r = requests.get(f'https://discord.com/api/v10/channels/{channelid}/messages?limit=1', headers=headers)添加类型校验,增强代码健壮性
不要默认API一定返回消息数组,添加类型判断和异常处理:r = requests.get(f'https://discord.com/api/v10/channels/{channelid}/messages?limit=1', headers=headers) print(f"请求状态码: {r.status_code}") print(f"API返回内容: {r.text}") try: jsonn = json.loads(r.text) except json.JSONDecodeError: print("无法解析API返回的JSON内容") exit() # 判断返回的是消息列表还是错误对象 if isinstance(jsonn, list): for value in jsonn: # 先确保消息里有embeds字段且是列表类型 if 'embeds' in value and isinstance(value['embeds'], list): current = str(value['embeds'])[1:500] if current != last: # 你的后续业务逻辑 pass else: print("当前消息中没有embeds或embeds格式异常") else: # 处理API错误 error_msg = jsonn.get('message', '未知错误') error_code = jsonn.get('code', '无错误码') print(f"API请求失败: {error_msg} (错误码: {error_code})")
内容的提问来源于stack exchange,提问作者Pauli Walnuts
相关产品推荐
相关产品推荐

