Discord Bot出现Python TypeError: string indices must be integers问题,现已解决
解决Discord Bot开发中的TypeError: string indices must be integers报错
这个报错的核心问题是你试图用字符串作为索引去访问一个字符串类型的变量——只有整数才能用来索引字符串(比如my_str[0]取第一个字符),而你大概率是把本应是字典/列表的对象当成了字符串来操作。
常见错误场景与修复方案
场景1:错误操作Discord消息对象
比如你想获取消息作者的ID,错误地直接操作消息内容字符串:
@bot.event async def on_message(message): # 错误:message.content是字符串,不能用['author']索引 author_id = message.content['author'] await message.channel.send(f"Author ID: {author_id}")
修复:直接调用消息对象的属性,而不是操作内容字符串:
@bot.event async def on_message(message): author_id = message.author.id await message.channel.send(f"Author ID: {author_id}")
场景2:未解析API返回的JSON数据
如果你的Bot调用了外部API,没把返回的文本解析成字典就直接索引:
import requests async def fetch_user_data(user_id): resp = requests.get(f"https://api.example.com/users/{user_id}") # 错误:resp.text是字符串,无法用['username']索引 username = resp.text['username']
修复:先用json()方法把响应文本解析为字典:
import requests async def fetch_user_data(user_id): resp = requests.get(f"https://api.example.com/users/{user_id}") user_data = resp.json() # 转换为字典 username = user_data['username']
通用排查步骤
- 定位报错代码行,用
print(type(your_variable))确认要索引的变量类型 - 如果变量本应是字典/列表,回溯数据来源:是不是Discord对象被误转成了字符串?是不是API响应没解析?
- 针对变量的真实类型调整操作方式——字符串用整数索引,字典用键名,列表用整数索引
内容的提问来源于stack exchange,提问作者AriV
相关产品推荐
相关产品推荐

