You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为discord.py命令添加参数,实现动态指定天气预报索引

给discord.py天气命令添加自定义日期索引参数的实现方法

嘿,这事儿其实很简单,我一步步带你搞定:

1. 先修改命令定义,新增参数

你原来的weather命令没有接收参数的功能,我们先给它加一个整数类型的参数,用来指定要查询的天气预报索引。修改后的命令定义长这样:

@bot.command(pass_context=True)
async def weather(ctx, day_index: int):

这里的day_index: int是类型提示,discord.py会自动把用户输入的内容转换成整数,避免后续出现类型错误。

2. 把固定索引换成参数变量

你原来代码里的forecasts[0]是固定取第一天的天气,现在直接换成forecasts[day_index - 1]就行——为啥要减1?因为用户习惯输入1代表今天,而列表是从0开始索引的,所以输入1对应索引0,输入2对应索引1,这样更符合用户的使用直觉~

3. 加个异常处理更友好(推荐)

天气预报的forecasts列表一般只有5天左右的数据,如果用户输入的数字超出范围,程序会直接报错。我们加个异常处理,给用户友好的提示:

try:
    selected_forecast = forecasts[day_index - 1]
except IndexError:
    await ctx.send(f"抱歉,输入的日期索引超出范围啦!目前支持查询1到{len(forecasts)}天的天气~")
    return

把选中的天气预报存到selected_forecast变量里,后面的字段直接用这个变量,不用重复写索引,代码更简洁。

4. 完整的修改后代码

整合所有部分,完整代码如下:

import discord
from discord.ext import commands
from discord.ext.commands import Bot
import asyncio
import random
from weather import Weather, Unit  # 优化了原来重复的导入语句

# 记得替换成你的命令前缀和Bot令牌
bot = commands.Bot(command_prefix='!')

@bot.command(pass_context=True)
async def weather(ctx, day_index: int):
    weather = Weather(unit=Unit.CELSIUS)
    location = weather.lookup_by_location('toronto')
    forecasts = location.forecast
    
    # 处理索引越界的情况
    try:
        selected_forecast = forecasts[day_index - 1]
    except IndexError:
        await ctx.send(f"抱歉,输入的日期索引超出范围啦!目前支持查询1到{len(forecasts)}天的天气~")
        return
    
    # 构建天气Embed消息
    embed = discord.Embed(title="-=-__THE WEATHER__-=-", color=0x15dbc7)
    embed.add_field(name="Clouds", value=selected_forecast.text, inline=False)
    embed.add_field(name="Date", value=selected_forecast.date, inline=False)
    embed.add_field(name="High", value=selected_forecast.high, inline=False)
    embed.add_field(name="Low", value=selected_forecast.low, inline=False)
    await ctx.send(embed=embed)

# 启动机器人
bot.run('你的Bot令牌')

5. 使用方法

现在用户在Discord里输入类似!weather 1就能查今天的天气,输入!weather 3就能查后天的,是不是很方便~

内容的提问来源于stack exchange,提问作者Web Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:33:17