python - Discord Python - OpenWeatherAPI 解析天气数据
问题描述
我正在为我的机器人制作天气命令,但我无法使用请求解析天气部分,(是的,我做了 .json() 它),代码:
import requests
import discord
import random
from discord import Embed
from discord.ext import commands
colour = random.randint(0x000000, 0xffffff)
class Weather(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def weather(self, ctx, *, location: str=None):
if location:
result = requests.get(f"http://api.openweathermap.org/data/2.5/weather?q={location}&APPID=APP ID").json()
embed = (discord.Embed(title=f"{location} Weather",
description=result,
colour=colour))
location = result["name"]
temp = result["main"]["temp"]
wind_speed = result["wind"]["speed"]
visibility = result["visibility"]
weather = result["weather"]["main"]
description = result["weather"]["description"]
feels_like = result["main"]["feels_like"]
await ctx.send(f"{location}\n{temp}\n{wind_speed}\n{visibility}\n{weather}\n{description}\n{feels_like}\n")
else:
await ctx.send("Please provide me with a location.")
def setup(client):
client.add_cog(Weather(client))
当我尝试解析天气时,它引发了一个错误。
discord.ext.commands.errors.CommandInvokeError:命令引发异常:TypeError:列表索引必须是整数或切片,而不是 str
我不知道为什么。但是当我尝试格式化它时,天气部分有一个“[]”
而且我不知道如何解析它。
解决方案
由@arundeepchohan 提供。我只需要将其编入索引(在第二个之前添加 [0])再次感谢@arundeepchohan
推荐阅读
- web-services - 寻找示例或指南或链接以了解 JAX-WS 1.2 项目
- listview - 小部件进入列表视图或颤动中的数据
- reactjs - 包括 id 的 ReactJs 路由路径返回不正确的组件
- c++ - 如何防止 CMAKE 在构建时为共享库创建符号链接(不在安装时)
- github - 仅在阻止拉取请求时手动运行 GitHub Actions
- sql - 在 MS Access 中查询分组数据
- gitlab - 更改 gitlab markdown 美人鱼图大小
- javascript - React Native“TypeError:Object(...)不是函数”反应导航堆栈错误
- javascript - 如何在组标题中添加可点击按钮?
- python - 代码正在执行应该在初始语句中被拒绝的过程,我不知道为什么