Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a weather command using discord.py v1.4.1

In case you would like to make a weather command using discord.py and have a cool addition to your bot, I got you covered, I have answered below on how to create a weather command in discord.py.

like image 743
Videro Avatar asked Mar 02 '23 03:03

Videro


1 Answers

We will be making a command which will work like this -

example


Starting off, we are going to be using openweahtermap API, which requires an API key, you can get one for free by simple logging in to their website.

Once you have got the API key, you are all good to go.

The second step will be to start coding, we will import 1 module apart from discord.py which is requests. We can simply import it -

import requests

After importing we can define the following things so that it's easier to use them.

api_key = "your_api_key"
base_url = "http://api.openweathermap.org/data/2.5/weather?"

The next step will be to create a command which takes city as an argument.

@client.command()
async def weather(ctx, *, city: str):

Afterwards, we can get the response of the website using requests and then read the response by using json. WE also define the channel in which the command is being used.

    city_name = city
    complete_url = base_url + "appid=" + api_key + "&q=" + city_name
    response = requests.get(complete_url)
    x = response.json()
    channel = ctx.message.channel

Now, we check if the city_name is a valid city by using a simple if statement. We also use async with channel.typing() which shows that the bot is typing till the time that it fetches the contents from the website.

    if x["cod"] != "404":
        async with channel.typing():

Now we get the info about the weather.

            y = x["main"]
            current_temperature = y["temp"]
            current_temperature_celsiuis = str(round(current_temperature - 273.15))
            current_pressure = y["pressure"]
            current_humidity = y["humidity"]
            z = x["weather"]
            weather_description = z[0]["description"]

Now, once we have the info, we put the info inside a discord.Embed like so -

            weather_description = z[0]["description"]
            embed = discord.Embed(title=f"Weather in {city_name}",
                              color=ctx.guild.me.top_role.color,
                              timestamp=ctx.message.created_at,)
            embed.add_field(name="Descripition", value=f"**{weather_description}**", inline=False)
            embed.add_field(name="Temperature(C)", value=f"**{current_temperature_celsiuis}°C**", inline=False)
            embed.add_field(name="Humidity(%)", value=f"**{current_humidity}%**", inline=False)
            embed.add_field(name="Atmospheric Pressure(hPa)", value=f"**{current_pressure}hPa**", inline=False)
            embed.set_thumbnail(url="https://i.ibb.co/CMrsxdX/weather.png")
            embed.set_footer(text=f"Requested by {ctx.author.name}")

After constructing the embed, we send it.

        await channel.send(embed=embed)
    else:
        await channel.send("City not found.")

We also use an else statement which sends that the city is not found if the API is unable to fetch the weather of the city mentioned.


And with that you have successfully made a weather command!

If you do run into any errors or have any doubts, make sure to comment them below. I will try to help as much as I can.

Thanks!

like image 145
Videro Avatar answered Mar 05 '23 15:03

Videro