如何使用discord.py v1.4.1实现Discord机器人天气命令?
Got it, let's walk through exactly how to build a working weather command for your discord.py bot step by step. I'll use OpenWeatherMap's API since it's free and easy to set up—here's what you need to do:
1. Prerequisites & Setup
- First, install the required packages: you'll need
discord.pyfor the bot framework andrequeststo call the weather API. Run this in your terminal:pip install discord.py requests - Next, grab an API key from OpenWeatherMap: head to their official site, sign up for a free account, and you'll get a key to access their weather data endpoints.
2. Core Bot Code with Weather Command
Here's the full implementation, broken down into manageable parts:
First, import the necessary modules:
import discord from discord.ext import commands import requests import os
Initialize your bot (make sure you have your Discord bot token handy too):
intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents)
Now the weather command itself. We'll make it accept a city name, fetch the data, and format a clean embed to send back to users:
@bot.command(name='weather', help='Get current weather for a city (usage: !weather London)') async def weather(ctx, *, city: str): # Use environment variables to keep your API key secure (never hardcode it!) api_key = os.getenv('OPENWEATHER_API_KEY') base_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric" try: response = requests.get(base_url) response.raise_for_status() # Trigger error for HTTP status codes >=400 data = response.json() # Extract key weather details from the API response main_data = data['main'] weather_desc = data['weather'][0]['description'] temp = main_data['temp'] feels_like = main_data['feels_like'] humidity = main_data['humidity'] wind_speed = data['wind']['speed'] weather_icon = data['weather'][0]['icon'] # Create a formatted embed for readable output embed = discord.Embed(title=f"Weather in {city.capitalize()}", color=discord.Color.blue()) embed.add_field(name="Condition", value=f"*{weather_desc.capitalize()}*", inline=False) embed.add_field(name="Temperature", value=f"{temp}°C", inline=True) embed.add_field(name="Feels Like", value=f"{feels_like}°C", inline=True) embed.add_field(name="Humidity", value=f"{humidity}%", inline=True) embed.add_field(name="Wind Speed", value=f"{wind_speed} m/s", inline=True) embed.set_thumbnail(url=f"http://openweathermap.org/img/wn/{weather_icon}@2x.png") await ctx.send(embed=embed) except requests.exceptions.HTTPError as err: if response.status_code == 404: await ctx.send("Sorry, that city wasn't found. Double-check the spelling!") else: await ctx.send(f"Failed to fetch weather data: {str(err)}") except Exception as e: await ctx.send(f"Oops, something went wrong: {str(e)}") # Start the bot (use environment variable for your token too!) bot.run(os.getenv('DISCORD_BOT_TOKEN'))
3. Key Best Practices
- Secure your credentials: Use environment variables instead of hardcoding your API key or bot token. On Windows, set them via Command Prompt with
set OPENWEATHER_API_KEY=your_key_here; on macOS/Linux useexport OPENWEATHER_API_KEY=your_key_here. - Handle errors gracefully: The code checks for invalid cities, HTTP errors, and general exceptions to prevent your bot from crashing unexpectedly.
- Customize units: Swap
units=metricforunits=imperialif you want Fahrenheit instead of Celsius. - Embed formatting: Embeds make the output far cleaner than plain text—users will appreciate the organized info and weather icon.
4. Test the Command
Once your bot is running, type this in any server where it has "Send Messages" and "Embed Links" permissions:
!weather Tokyo
You should get a blue embed with all the current weather details for Tokyo, including the condition, temperature, humidity, and a matching weather icon.
内容的提问来源于stack exchange,提问作者Harjot

