Discord Python - OpenWeatherAPI 解析天气数据
Discord Python - OpenWeatherAPI Parse Weather Data
我正在为我的机器人制作天气命令,但我无法使用请求解析天气部分,(是的,我做到了。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: Command raised an exception: TypeError: list indices must be integers or slices, not str
而且我不知道为什么。但是当我试图格式化它时,天气部分有一个“[]”
而且我不知道如何解析它。
由 @arundeepchohan 回答。
我只需要让它被索引(在第二个之前添加[0])
再次感谢你@arundeepchohan
我正在为我的机器人制作天气命令,但我无法使用请求解析天气部分,(是的,我做到了。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: Command raised an exception: TypeError: list indices must be integers or slices, not str
而且我不知道为什么。但是当我试图格式化它时,天气部分有一个“[]”
而且我不知道如何解析它。
由 @arundeepchohan 回答。 我只需要让它被索引(在第二个之前添加[0]) 再次感谢你@arundeepchohan