Nextcord机器人天气命令报错:TypeError: string indices must be integers排查
Nextcord机器人天气命令TypeError问题排查与解决
问题场景
开发Nextcord Discord机器人时,编写了查询天气的命令,运行!weather "city_name"时触发TypeError:
string indices must be integers, not 'str'
报错位置在location = data["location"]["name"]["localtime"]这一行。
原代码
import nextcord from nextcord.ext import commands from config import TOKEN, API_KEY import aiohttp bot = commands.Bot(command_prefix = "!", intents = nextcord.Intents.all()) @bot.event async def on_ready(): print("Bot has connected to Discord") @bot.command() async def weather(ctx: commands.Context, *, city): url = "http://api.weatherapi.com/v1/current.json" params = { "key": API_KEY, "q": city } async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as responses: data = await responses.json() print(data) location = data["location"]["name"]["localtime"]
报错信息
string indices must be integers, not 'str'
问题原因
你错误地访问了字典层级:data["location"]["name"]返回的是字符串类型(比如城市名称"Beijing"),字符串仅支持用整数下标访问单个字符(如"Beijing"[0]),但你用字符串键"localtime"去访问,直接触发类型错误。
根据WeatherAPI的返回结构,localtime是location字典下的直接子键,和name同级,并非name的子键。
修正方案
调整字典访问层级,修改报错行代码:
async def weather(ctx: commands.Context, *, city): url = "http://api.weatherapi.com/v1/current.json" params = { "key": API_KEY, "q": city } async with aiohttp.ClientSession() as session: async with session.get(url, params=params) as responses: data = await responses.json() print(data) # 正确获取城市名称与本地时间 city_name = data["location"]["name"] local_time = data["location"]["localtime"] # 可将结果发送至Discord频道 await ctx.send(f"{city_name} 的本地时间:{local_time}")
额外建议
如果不确定API返回的字典结构,可打印data["location"]查看所有子键,避免层级错误:
print(data["location"]) # 输出示例: # {'name': 'Beijing', 'region': 'Beijing', 'country': 'China', 'localtime': '2024-05-20 14:30', ...}
内容的提问来源于stack exchange,提问作者Aashish Koundinya
相关产品推荐
相关产品推荐

