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

如何让Discord.py机器人无需引号识别多词城市名?

要实现无需引号就能识别多词城市名,只需修改weather命令的参数接收方式,让它能捕获命令后的所有输入内容:

核心修改说明

discord.py 默认按空格拆分命令参数,单个arg只能取到第一个单词。改用*args可以把命令后所有空格分隔的内容打包成元组,再拼接成完整城市名即可解决问题。同时优化返回结果的展示格式,并增加异常处理避免API报错导致机器人崩溃。

修改后的完整代码

import discord
from discord.ext import commands
import requests
import json

def get_weather(city):
    url = "https://api.openweathermap.org/data/2.5/weather"
    parameters = {
        "q": city,
        "appid": "d9451e04c3b2a30d46a555f28a3c3724",
        "units": "metric",
        "lang": "ro"
    }
    response = requests.get(url=url, params=parameters)
    response.raise_for_status()

    json_data = response.json()
    weather_description = json_data["weather"][0]["description"]
    main_temp = json_data["main"]["temp"]
    return weather_description, main_temp

intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)

@bot.event
async def on_ready():
    print("Bot Ready!")

@bot.command()
async def weather(ctx, *args):
    # 拼接所有参数为完整城市名
    city_name = " ".join(args)
    # 转换为API要求的格式(空格替换为+)
    converted_city = city_name.replace(" ", "+")
    try:
        desc, temp = get_weather(converted_city)
        # 格式化输出天气信息
        await ctx.send(f"{city_name} 的天气:{desc},温度:{temp}°C")
    except requests.exceptions.HTTPError as e:
        # 处理城市不存在等API错误
        await ctx.send(f"获取天气失败:{str(e)}")

@bot.command()
async def test2(ctx, arg):
    await ctx.send(arg)

关键改动点

  • 使用*args替代单个arg,接收命令后的所有输入内容,比如输入$weather New York时,args会捕获('New', 'York'),拼接后得到完整城市名
  • 增加异常捕获逻辑,当API返回错误(如城市名称无效)时,能给用户明确的错误提示
  • 优化消息展示格式,让天气结果更直观易读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:05:54