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"]
我不断在“location = data["location"]["name"]["localtime"]"这一行收到类型错误
TypeError: string indices must be integers, not 'str'
在天气 API 中,信息存储在嵌套字典中。我通过使用
location = data["outer_key"]["inner_key"]
访问这些值
我传递的命令是
!weather "city_name"
我做错了什么?
我不确定,但由于你的数据变量不能是列表,如果你想使用位置变量,你必须将其转换为字典:location = data["location"]["name"]["localtime ”]
正确类型: 数据 = {位置: {"name": {"localtime": "2024-04-15 12:00"}}}