mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
天气插件不再内置和风天气凭据
仓库里那个和风天气的密钥不再预置,配置文件和代码里的默认值都清空了,没配凭据时直接提示用户自己去申请。 顺带修了几处:网页结构变了取不到内容时给中性提示,不再把Python的报错原文念给用户;接口和网页两条路的日期、单位统一成一种写法;报告加上观测时间;网页兜底只等5秒,失败结果记5分钟,不用每次都等二十几秒。 文档补了申请流程和要勾的三项权限。
This commit is contained in:
parent
63f3860f29
commit
65e18712e6
4 changed files with 602 additions and 45 deletions
|
|
@ -4,6 +4,20 @@
|
||||||
|
|
||||||
天气插件 `get_weather` 是小智ESP32语音助手的核心功能之一,支持通过语音查询全国各地的天气信息。插件基于和风天气API,提供实时天气和7天天气预报功能。
|
天气插件 `get_weather` 是小智ESP32语音助手的核心功能之一,支持通过语音查询全国各地的天气信息。插件基于和风天气API,提供实时天气和7天天气预报功能。
|
||||||
|
|
||||||
|
## 仓库不再预置凭据
|
||||||
|
|
||||||
|
本仓库不再内置任何和风天气的账号和密钥。插件读不到 `api_key` 或 `api_host` 的时候会直接提示还没配置,不会拿公共账号去请求。自己部署的话,照着下面的步骤申请一套自己的,填进配置里就能用。
|
||||||
|
|
||||||
|
创建凭据时要勾选三项权限,少勾哪一项都取不到对应的数据:
|
||||||
|
|
||||||
|
| 权限 | 用来做什么 |
|
||||||
|
| --- | --- |
|
||||||
|
| GeoAPI 城市查询 | 把地名换成城市编号 |
|
||||||
|
| 实时天气 | 当前的温度、风力、湿度这些 |
|
||||||
|
| 7 天天气预报 | 未来几天的预报 |
|
||||||
|
|
||||||
|
三项里少勾一两个,JSON 接口就取不到完整的数据,天气只能退到网页上抓,显示的内容比接口给的少。
|
||||||
|
|
||||||
## API Key 申请指南
|
## API Key 申请指南
|
||||||
|
|
||||||
### 1. 注册和风天气账号
|
### 1. 注册和风天气账号
|
||||||
|
|
|
||||||
|
|
@ -130,14 +130,15 @@ context_providers:
|
||||||
|
|
||||||
# 插件的基础配置
|
# 插件的基础配置
|
||||||
plugins:
|
plugins:
|
||||||
# 获取天气插件的配置,这里填写你的api_key
|
# 获取天气插件的配置,这里填写你自己的api_key和apihost
|
||||||
# 这个密钥是项目共用的key,用多了可能会被限制
|
# 仓库里不再预置凭据,申请流程写在 docs/weather-integration.md
|
||||||
# 想稳定一点就自行申请替换,每天有1000次免费调用
|
|
||||||
# 申请地址:https://console.qweather.com/#/apps/create-key/over
|
# 申请地址:https://console.qweather.com/#/apps/create-key/over
|
||||||
# 申请后通过这个链接可以找到自己的apihost:https://console.qweather.com/setting?lang=zh
|
# 申请后通过这个链接可以找到自己的apihost:https://console.qweather.com/setting?lang=zh
|
||||||
|
# 建key时要勾选三项权限:GeoAPI城市查询、实时天气、7天天气预报
|
||||||
|
# 只勾一两个的话JSON接口取不到数据,天气只能退到网页上抓
|
||||||
get_weather:
|
get_weather:
|
||||||
api_host: "mj7p3y7naa.re.qweatherapi.com"
|
api_host: ""
|
||||||
api_key: "a861d0d5e7bf4ee1a83d9a9e4f96d4da"
|
api_key: ""
|
||||||
default_location: "广州"
|
default_location: "广州"
|
||||||
# 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻
|
# 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻
|
||||||
# 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/
|
# 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
import httpx
|
import httpx
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
|
|
@ -45,6 +47,36 @@ HEADERS = {
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# 仓库里不再预置和风天气的凭据,自己部署的人得自己去申请一个
|
||||||
|
WEATHER_CREDENTIAL_HINT = (
|
||||||
|
"尚未配置和风天气 api_key,请参考 docs/weather-integration.md 申请后填入"
|
||||||
|
)
|
||||||
|
WEATHER_HOST_HINT = (
|
||||||
|
"尚未配置和风天气 api_host,请参考 docs/weather-integration.md 申请后填入"
|
||||||
|
)
|
||||||
|
|
||||||
|
# 上游挂着的时候每次提问都要把整条链路重走一遍,用户要等二十几秒。
|
||||||
|
# 失败结果短时间内不会变,先记下来直接回
|
||||||
|
WEATHER_FAILURE_TTL = 300
|
||||||
|
|
||||||
|
WEEKDAY_NAMES = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
|
||||||
|
|
||||||
|
# 网页上写的是符号单位,报告里统一用中文,两条路径读出来的东西才对得上
|
||||||
|
UNIT_NAMES = {
|
||||||
|
"km/h": "公里/小时",
|
||||||
|
"km": "公里",
|
||||||
|
"mm": "毫米",
|
||||||
|
"hpa": "百帕",
|
||||||
|
"°": "℃",
|
||||||
|
"°c": "℃",
|
||||||
|
}
|
||||||
|
|
||||||
|
# 网页上的参数名和接口返回的不一样,报告里用接口那套
|
||||||
|
ITEM_NAMES = {
|
||||||
|
"大气压": "气压",
|
||||||
|
"相对湿度": "湿度",
|
||||||
|
}
|
||||||
|
|
||||||
# 天气代码 https://dev.qweather.com/docs/resource/icons/#weather-icons
|
# 天气代码 https://dev.qweather.com/docs/resource/icons/#weather-icons
|
||||||
WEATHER_CODE_MAP = {
|
WEATHER_CODE_MAP = {
|
||||||
"100": "晴",
|
"100": "晴",
|
||||||
|
|
@ -112,6 +144,90 @@ WEATHER_CODE_MAP = {
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def format_observation_time(raw_time):
|
||||||
|
"""观测时间接口给的是带 T 的写法,报告里换成空格好看点"""
|
||||||
|
if not raw_time:
|
||||||
|
return None
|
||||||
|
return str(raw_time).replace("T", " ", 1)
|
||||||
|
|
||||||
|
|
||||||
|
def format_forecast_date(raw_date, today=None):
|
||||||
|
"""
|
||||||
|
预报日期统一成 今天/明天/后天 或者 星期加月日
|
||||||
|
|
||||||
|
<p>
|
||||||
|
接口给的是 2026-10-24 这种写法,网页上写的是 今天10月24日,
|
||||||
|
两条路径各写各的,用户听不出来是同一份数据。统一成一种写法。
|
||||||
|
"""
|
||||||
|
if not raw_date:
|
||||||
|
return raw_date
|
||||||
|
text = str(raw_date).strip()
|
||||||
|
today = today or datetime.date.today()
|
||||||
|
|
||||||
|
iso = re.fullmatch(r"(\d{4})-(\d{1,2})-(\d{1,2})", text)
|
||||||
|
if iso:
|
||||||
|
year = int(iso.group(1))
|
||||||
|
month = int(iso.group(2))
|
||||||
|
day = int(iso.group(3))
|
||||||
|
else:
|
||||||
|
found = re.search(r"(\d{1,2})月(\d{1,2})日", text)
|
||||||
|
if not found:
|
||||||
|
return text
|
||||||
|
year = today.year
|
||||||
|
month = int(found.group(1))
|
||||||
|
day = int(found.group(2))
|
||||||
|
|
||||||
|
try:
|
||||||
|
date_value = datetime.date(year, month, day)
|
||||||
|
except ValueError:
|
||||||
|
return text
|
||||||
|
|
||||||
|
delta = (date_value - today).days
|
||||||
|
if delta == 0:
|
||||||
|
prefix = "今天"
|
||||||
|
elif delta == 1:
|
||||||
|
prefix = "明天"
|
||||||
|
elif delta == 2:
|
||||||
|
prefix = "后天"
|
||||||
|
else:
|
||||||
|
prefix = WEEKDAY_NAMES[date_value.weekday()]
|
||||||
|
return f"{prefix}{month}月{day}日"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_unit(value):
|
||||||
|
"""把单位符号换成中文写法,换不动就原样留着"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text:
|
||||||
|
return text
|
||||||
|
matched = re.fullmatch(r"(.+?)([a-zA-Z°℃/]+)", text)
|
||||||
|
if not matched:
|
||||||
|
return text
|
||||||
|
unit = matched.group(2).lower()
|
||||||
|
if unit not in UNIT_NAMES:
|
||||||
|
return text
|
||||||
|
return f"{matched.group(1)}{UNIT_NAMES[unit]}"
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_temperature(value):
|
||||||
|
"""温度只留数值,单位在报告里统一写一次"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
matched = re.match(r"-?\d+(?:\.\d+)?", str(value).strip())
|
||||||
|
return matched.group(0) if matched else None
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_wind_scale(value):
|
||||||
|
"""风力统一成 3级 这种带单位的写法"""
|
||||||
|
if value is None:
|
||||||
|
return None
|
||||||
|
text = str(value).strip()
|
||||||
|
if not text or text.endswith("级"):
|
||||||
|
return text
|
||||||
|
return f"{text}级"
|
||||||
|
|
||||||
|
|
||||||
async def fetch_city_info(location, api_key, api_host):
|
async def fetch_city_info(location, api_key, api_host):
|
||||||
url = f"https://{api_host}/geo/v2/city/lookup"
|
url = f"https://{api_host}/geo/v2/city/lookup"
|
||||||
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0, connect=3.0)) as client:
|
async with httpx.AsyncClient(timeout=httpx.Timeout(5.0, connect=3.0)) as client:
|
||||||
|
|
@ -165,7 +281,7 @@ async def fetch_weather_data(city_info, api_key, api_host):
|
||||||
return data
|
return data
|
||||||
|
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, connect=3.0)) as client:
|
async with httpx.AsyncClient(timeout=httpx.Timeout(8.0, connect=3.0)) as client:
|
||||||
now, daily = await asyncio.gather(
|
now, daily = await asyncio.gather(
|
||||||
request(client, "now"), request(client, "7d")
|
request(client, "now"), request(client, "7d")
|
||||||
)
|
)
|
||||||
|
|
@ -177,48 +293,87 @@ async def fetch_weather_data(city_info, api_key, api_host):
|
||||||
return now, daily
|
return now, daily
|
||||||
|
|
||||||
|
|
||||||
|
def format_weather_report(
|
||||||
|
city_name, current_text, current_basic, temps_list, observed_at=None
|
||||||
|
):
|
||||||
|
"""两条路径的报告走同一个模板,日期和单位的写法才对得上"""
|
||||||
|
weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_text}\n"
|
||||||
|
if observed_at:
|
||||||
|
weather_report += f"观测时间:{observed_at}\n"
|
||||||
|
|
||||||
|
if current_basic:
|
||||||
|
weather_report += "详细参数:\n"
|
||||||
|
weather_report += "".join(
|
||||||
|
f" · {key}: {value}\n" for key, value in current_basic.items()
|
||||||
|
)
|
||||||
|
|
||||||
|
weather_report += "\n未来7天预报:\n"
|
||||||
|
weather_report += "".join(
|
||||||
|
f"{date}: {weather},气温 {low}~{high}℃\n"
|
||||||
|
for date, weather, high, low in temps_list
|
||||||
|
)
|
||||||
|
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
||||||
|
return weather_report
|
||||||
|
|
||||||
|
|
||||||
def build_weather_report(city_info, now_data, daily_data):
|
def build_weather_report(city_info, now_data, daily_data):
|
||||||
city_name = city_info.get("name") or city_info.get("adm2") or "未知位置"
|
city_name = city_info.get("name") or city_info.get("adm2") or "未知位置"
|
||||||
now = now_data.get("now", {})
|
now = now_data.get("now", {})
|
||||||
weather_report = f"您查询的位置是:{city_name}\n\n"
|
|
||||||
weather_report += f"当前天气: {now.get('text', '未知')}\n"
|
|
||||||
|
|
||||||
current_basic = {
|
current_basic = {
|
||||||
"温度": f"{now['temp']}℃" if now.get("temp") is not None else None,
|
"温度": f"{now['temp']}℃" if now.get("temp") is not None else None,
|
||||||
"体感温度": f"{now['feelsLike']}℃" if now.get("feelsLike") is not None else None,
|
"体感温度": f"{now['feelsLike']}℃" if now.get("feelsLike") is not None else None,
|
||||||
"湿度": f"{now['humidity']}%" if now.get("humidity") is not None else None,
|
"湿度": f"{now['humidity']}%" if now.get("humidity") is not None else None,
|
||||||
"风向": now.get("windDir"),
|
"风向": now.get("windDir"),
|
||||||
"风力": now.get("windScale"),
|
"风力": normalize_wind_scale(now.get("windScale")),
|
||||||
"能见度": f"{now['vis']}公里" if now.get("vis") is not None else None,
|
"能见度": f"{now['vis']}公里" if now.get("vis") is not None else None,
|
||||||
"气压": f"{now['pressure']}百帕" if now.get("pressure") is not None else None,
|
"气压": f"{now['pressure']}百帕" if now.get("pressure") is not None else None,
|
||||||
"降水量": f"{now['precip']}毫米" if now.get("precip") is not None else None,
|
"降水量": f"{now['precip']}毫米" if now.get("precip") is not None else None,
|
||||||
}
|
}
|
||||||
current_basic = {key: value for key, value in current_basic.items() if value}
|
current_basic = {key: value for key, value in current_basic.items() if value}
|
||||||
if current_basic:
|
|
||||||
weather_report += "详细参数:\n"
|
|
||||||
weather_report += "".join(f" · {key}: {value}\n" for key, value in current_basic.items())
|
|
||||||
|
|
||||||
weather_report += "\n未来7天预报:\n"
|
temps_list = []
|
||||||
for item in daily_data.get("daily", [])[:7]:
|
for item in daily_data.get("daily", [])[:7]:
|
||||||
date = item.get("fxDate", "未知日期")
|
date = format_forecast_date(item.get("fxDate") or "未知日期")
|
||||||
weather = item.get("textDay") or WEATHER_CODE_MAP.get(item.get("iconDay"), "未知")
|
weather = item.get("textDay") or WEATHER_CODE_MAP.get(item.get("iconDay"), "未知")
|
||||||
high = item.get("tempMax", "未知")
|
high = normalize_temperature(item.get("tempMax")) or "未知"
|
||||||
low = item.get("tempMin", "未知")
|
low = normalize_temperature(item.get("tempMin")) or "未知"
|
||||||
weather_report += f"{date}: {weather},气温 {low}~{high}℃\n"
|
temps_list.append((date, weather, high, low))
|
||||||
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
|
||||||
return weather_report
|
# 观测时间在 now.obsTime 里,now.updateTime 是空的,兜底才用响应顶层那个
|
||||||
|
observed_at = format_observation_time(
|
||||||
|
now.get("obsTime") or now_data.get("updateTime")
|
||||||
|
)
|
||||||
|
return format_weather_report(
|
||||||
|
city_name, now.get("text", "未知"), current_basic, temps_list, observed_at
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
async def fetch_weather_page(url):
|
async def fetch_weather_page(url):
|
||||||
|
# 网页只是兜底,等太久不值得,接口那边不通的话很快就该告诉用户
|
||||||
async with httpx.AsyncClient(
|
async with httpx.AsyncClient(
|
||||||
timeout=httpx.Timeout(10.0, connect=3.0), follow_redirects=True
|
timeout=httpx.Timeout(5.0, connect=3.0), follow_redirects=True
|
||||||
) as client:
|
) as client:
|
||||||
response = await client.get(url, headers=HEADERS)
|
response = await client.get(url, headers=HEADERS)
|
||||||
return BeautifulSoup(response.text, "html.parser") if response.status_code == 200 else None
|
return BeautifulSoup(response.text, "html.parser") if response.status_code == 200 else None
|
||||||
|
|
||||||
|
|
||||||
def parse_weather_info(soup):
|
def parse_weather_info(soup):
|
||||||
city_name = soup.select_one("h1.c-submenu__location").get_text(strip=True)
|
"""
|
||||||
|
解析和风天气网页上的天气
|
||||||
|
|
||||||
|
<p>
|
||||||
|
页面的结构一变,取不到元素就返回 None。抛异常的话 Python 的原文
|
||||||
|
会被当成回复内容念给用户,听着像系统在报错。
|
||||||
|
"""
|
||||||
|
if soup is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
city_element = soup.select_one("h1.c-submenu__location")
|
||||||
|
if city_element is None:
|
||||||
|
logger.bind(tag=TAG).warning("网页天气解析失败:取不到城市名")
|
||||||
|
return None
|
||||||
|
city_name = city_element.get_text(strip=True)
|
||||||
|
|
||||||
current_abstract = soup.select_one(".c-city-weather-current .current-abstract")
|
current_abstract = soup.select_one(".c-city-weather-current .current-abstract")
|
||||||
current_abstract = (
|
current_abstract = (
|
||||||
|
|
@ -232,18 +387,40 @@ def parse_weather_info(soup):
|
||||||
parts = item.get_text(strip=True, separator=" ").split(" ")
|
parts = item.get_text(strip=True, separator=" ").split(" ")
|
||||||
if len(parts) == 2:
|
if len(parts) == 2:
|
||||||
key, value = parts[1], parts[0]
|
key, value = parts[1], parts[0]
|
||||||
|
# 风向和风力挤在一项里,拆成两项跟接口那套对上
|
||||||
|
if key.endswith("风") and value.endswith("级"):
|
||||||
|
current_basic["风向"] = key
|
||||||
|
current_basic["风力"] = value
|
||||||
|
continue
|
||||||
|
key = ITEM_NAMES.get(key, key)
|
||||||
|
value = normalize_unit(value)
|
||||||
|
if not value or value == "0":
|
||||||
|
continue
|
||||||
current_basic[key] = value
|
current_basic[key] = value
|
||||||
|
|
||||||
temps_list = []
|
temps_list = []
|
||||||
for row in soup.select(".city-forecast-tabs__row")[:7]: # 取前7天的数据
|
for row in soup.select(".city-forecast-tabs__row")[:7]: # 取前7天的数据
|
||||||
date = row.select_one(".date-bg .date").get_text(strip=True)
|
date_element = row.select_one(".date-bg .date")
|
||||||
weather_code = (
|
icon_element = row.select_one(".date-bg .icon")
|
||||||
row.select_one(".date-bg .icon")["src"].split("/")[-1].split(".")[0]
|
if date_element is None or icon_element is None:
|
||||||
)
|
logger.bind(tag=TAG).warning("网页天气解析失败:预报行缺日期或图标")
|
||||||
|
return None
|
||||||
|
icon_src = icon_element.get("src")
|
||||||
|
if not icon_src:
|
||||||
|
logger.bind(tag=TAG).warning("网页天气解析失败:预报行图标没有地址")
|
||||||
|
return None
|
||||||
|
weather_code = icon_src.split("/")[-1].split(".")[0]
|
||||||
weather = WEATHER_CODE_MAP.get(weather_code, "未知")
|
weather = WEATHER_CODE_MAP.get(weather_code, "未知")
|
||||||
temps = [span.get_text(strip=True) for span in row.select(".tmp-cont .temp")]
|
temps = [span.get_text(strip=True) for span in row.select(".tmp-cont .temp")]
|
||||||
high_temp, low_temp = (temps[0], temps[-1]) if len(temps) >= 2 else (None, None)
|
high_temp, low_temp = (temps[0], temps[-1]) if len(temps) >= 2 else (None, None)
|
||||||
temps_list.append((date, weather, high_temp, low_temp))
|
temps_list.append(
|
||||||
|
(
|
||||||
|
format_forecast_date(date_element.get_text(strip=True)),
|
||||||
|
weather,
|
||||||
|
normalize_temperature(high_temp) or "未知",
|
||||||
|
normalize_temperature(low_temp) or "未知",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return city_name, current_abstract, current_basic, temps_list
|
return city_name, current_abstract, current_basic, temps_list
|
||||||
|
|
||||||
|
|
@ -253,11 +430,17 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str
|
||||||
from core.utils.cache.manager import cache_manager, CacheType
|
from core.utils.cache.manager import cache_manager, CacheType
|
||||||
|
|
||||||
weather_config = conn.config.get("plugins", {}).get("get_weather", {})
|
weather_config = conn.config.get("plugins", {}).get("get_weather", {})
|
||||||
api_host = weather_config.get("api_host", "mj7p3y7naa.re.qweatherapi.com")
|
api_key = str(weather_config.get("api_key") or "").strip()
|
||||||
api_key = weather_config.get("api_key", "a861d0d5e7bf4ee1a83d9a9e4f96d4da")
|
api_host = str(weather_config.get("api_host") or "").strip()
|
||||||
default_location = weather_config.get("default_location", "广州")
|
default_location = weather_config.get("default_location", "广州")
|
||||||
client_ip = conn.client_ip
|
client_ip = conn.client_ip
|
||||||
|
|
||||||
|
# 凭据没配就没法取数据,直接告诉用户去申请,别拿空 key 去撞接口
|
||||||
|
if not api_key:
|
||||||
|
return ActionResponse(Action.REQLLM, WEATHER_CREDENTIAL_HINT, None)
|
||||||
|
if not api_host:
|
||||||
|
return ActionResponse(Action.REQLLM, WEATHER_HOST_HINT, None)
|
||||||
|
|
||||||
# 优先使用用户提供的location参数
|
# 优先使用用户提供的location参数
|
||||||
if not location:
|
if not location:
|
||||||
# 通过客户端IP解析城市
|
# 通过客户端IP解析城市
|
||||||
|
|
@ -280,39 +463,40 @@ async def get_weather(conn: "ConnectionHandler", location: str = None, lang: str
|
||||||
location = default_location
|
location = default_location
|
||||||
# 尝试从缓存获取完整天气报告
|
# 尝试从缓存获取完整天气报告
|
||||||
weather_cache_key = f"full_weather_{location}_{lang}"
|
weather_cache_key = f"full_weather_{location}_{lang}"
|
||||||
|
failure_cache_key = f"failed_weather_{location}_{lang}"
|
||||||
cached_weather_report = cache_manager.get(CacheType.WEATHER, weather_cache_key)
|
cached_weather_report = cache_manager.get(CacheType.WEATHER, weather_cache_key)
|
||||||
if cached_weather_report:
|
if cached_weather_report:
|
||||||
return ActionResponse(Action.REQLLM, cached_weather_report, None)
|
return ActionResponse(Action.REQLLM, cached_weather_report, None)
|
||||||
|
# 刚失败过就不要再走一遍链路,用户等不起
|
||||||
|
cached_failure = cache_manager.get(CacheType.WEATHER, failure_cache_key)
|
||||||
|
if cached_failure:
|
||||||
|
return ActionResponse(Action.REQLLM, cached_failure, None)
|
||||||
|
|
||||||
# 缓存未命中,获取实时天气数据
|
# 缓存未命中,获取实时天气数据
|
||||||
city_info = await fetch_city_info(location, api_key, api_host)
|
city_info = await fetch_city_info(location, api_key, api_host)
|
||||||
if not city_info:
|
if not city_info:
|
||||||
return ActionResponse(
|
message = f"暂时查不到 {location} 的天气(城市未找到或天气服务不可用),请稍后再试"
|
||||||
Action.REQLLM,
|
cache_manager.set(
|
||||||
f"暂时查不到 {location} 的天气(城市未找到或天气服务不可用),请稍后再试",
|
CacheType.WEATHER, failure_cache_key, message, ttl=WEATHER_FAILURE_TTL
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
|
return ActionResponse(Action.REQLLM, message, None)
|
||||||
weather_data = await fetch_weather_data(city_info, api_key, api_host)
|
weather_data = await fetch_weather_data(city_info, api_key, api_host)
|
||||||
if weather_data:
|
if weather_data:
|
||||||
weather_report = build_weather_report(city_info, *weather_data)
|
weather_report = build_weather_report(city_info, *weather_data)
|
||||||
else:
|
else:
|
||||||
fx_link = city_info.get("fxLink")
|
fx_link = city_info.get("fxLink")
|
||||||
soup = await fetch_weather_page(fx_link) if fx_link else None
|
soup = await fetch_weather_page(fx_link) if fx_link else None
|
||||||
if not soup:
|
parsed = parse_weather_info(soup)
|
||||||
return ActionResponse(Action.REQLLM, None, "请求天气数据失败")
|
if not parsed:
|
||||||
city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
|
message = "暂时查不到天气数据,请稍后再试"
|
||||||
weather_report = f"您查询的位置是:{city_name}\n\n当前天气: {current_abstract}\n"
|
cache_manager.set(
|
||||||
if current_basic:
|
CacheType.WEATHER, failure_cache_key, message, ttl=WEATHER_FAILURE_TTL
|
||||||
weather_report += "详细参数:\n"
|
|
||||||
weather_report += "".join(
|
|
||||||
f" · {key}: {value}\n" for key, value in current_basic.items() if value != "0"
|
|
||||||
)
|
)
|
||||||
weather_report += "\n未来7天预报:\n"
|
return ActionResponse(Action.REQLLM, message, "请求天气数据失败")
|
||||||
weather_report += "".join(
|
city_name, current_abstract, current_basic, temps_list = parsed
|
||||||
f"{date}: {weather},气温 {low}~{high}\n"
|
weather_report = format_weather_report(
|
||||||
for date, weather, high, low in temps_list
|
city_name, current_abstract, current_basic, temps_list
|
||||||
)
|
)
|
||||||
weather_report += "\n(如需某一天的具体天气,请告诉我日期)"
|
|
||||||
|
|
||||||
# 缓存完整的天气报告
|
# 缓存完整的天气报告
|
||||||
cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report)
|
cache_manager.set(CacheType.WEATHER, weather_cache_key, weather_report)
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,358 @@
|
||||||
|
"""天气插件的凭据、健壮性和报告格式测试。
|
||||||
|
|
||||||
|
接口一律换成假客户端,不碰网络。
|
||||||
|
"""
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from bs4 import BeautifulSoup
|
||||||
|
|
||||||
|
from plugins_func.functions import get_weather as weather_module
|
||||||
|
|
||||||
|
|
||||||
|
class FakeResponse:
|
||||||
|
def __init__(self, status_code=200, payload=None, text=""):
|
||||||
|
self.status_code = status_code
|
||||||
|
self.payload = payload
|
||||||
|
self.text = text
|
||||||
|
|
||||||
|
def json(self):
|
||||||
|
return self.payload
|
||||||
|
|
||||||
|
|
||||||
|
class FakeAsyncClient:
|
||||||
|
"""顶替 httpx.AsyncClient,把建客户端时的参数记下来"""
|
||||||
|
|
||||||
|
requests = []
|
||||||
|
responder = None
|
||||||
|
init_kwargs = {}
|
||||||
|
|
||||||
|
def __init__(self, *args, **kwargs):
|
||||||
|
FakeAsyncClient.init_kwargs = kwargs
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, *exc_info):
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def get(self, url, params=None, headers=None):
|
||||||
|
FakeAsyncClient.requests.append({"url": url, "params": params})
|
||||||
|
return FakeAsyncClient.responder(url, params)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def fake_http(monkeypatch):
|
||||||
|
FakeAsyncClient.requests = []
|
||||||
|
FakeAsyncClient.responder = lambda url, params: FakeResponse(payload={"code": "200"})
|
||||||
|
FakeAsyncClient.init_kwargs = {}
|
||||||
|
monkeypatch.setattr(httpx, "AsyncClient", FakeAsyncClient)
|
||||||
|
return FakeAsyncClient
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def clear_weather_cache():
|
||||||
|
"""天气缓存是全局的,清一下免得上一条用例的结果串到下一条"""
|
||||||
|
from core.utils.cache.manager import cache_manager, CacheType
|
||||||
|
|
||||||
|
cache_manager.clear(CacheType.WEATHER)
|
||||||
|
yield
|
||||||
|
cache_manager.clear(CacheType.WEATHER)
|
||||||
|
|
||||||
|
|
||||||
|
class FakeConn:
|
||||||
|
def __init__(self, plugins=None):
|
||||||
|
self.config = {"plugins": plugins or {}}
|
||||||
|
self.client_ip = None
|
||||||
|
|
||||||
|
|
||||||
|
def _today():
|
||||||
|
return datetime.date.today()
|
||||||
|
|
||||||
|
|
||||||
|
def _web_page(date_text, temp_high="13°", temp_low="9°"):
|
||||||
|
"""照着和风天气网页的样子拼一段,解析要的就是这些结构和写法"""
|
||||||
|
return f"""
|
||||||
|
<html>
|
||||||
|
<h1 class="c-submenu__location">杭州市</h1>
|
||||||
|
<div class="c-city-weather-current">
|
||||||
|
<div class="current-abstract">多云</div>
|
||||||
|
<div class="current-basic">
|
||||||
|
<div class="current-basic___item">4级 西北风</div>
|
||||||
|
<div class="current-basic___item">97% 相对湿度</div>
|
||||||
|
<div class="current-basic___item">13° 体感温度</div>
|
||||||
|
<div class="current-basic___item">9km 能见度</div>
|
||||||
|
<div class="current-basic___item">0.0mm 降水量</div>
|
||||||
|
<div class="current-basic___item">1009hPa 大气压</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="city-forecast-tabs">
|
||||||
|
<div class="city-forecast-tabs__row">
|
||||||
|
<div class="date-bg">
|
||||||
|
<span class="date">{date_text}</span>
|
||||||
|
<img class="icon" src="https://static.qweather.com/img/common/icon/202106d/306.png">
|
||||||
|
</div>
|
||||||
|
<div class="tmp-cont">
|
||||||
|
<span class="temp">{temp_high}</span>
|
||||||
|
<span class="temp">{temp_low}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 凭据
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
async def test_missing_api_key_points_at_the_application_doc():
|
||||||
|
response = await weather_module.get_weather(
|
||||||
|
FakeConn({"get_weather": {"api_host": "h"}}), location="没配密钥市"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.result == (
|
||||||
|
"尚未配置和风天气 api_key,请参考 docs/weather-integration.md 申请后填入"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_missing_api_host_points_at_the_application_doc():
|
||||||
|
response = await weather_module.get_weather(
|
||||||
|
FakeConn({"get_weather": {"api_key": "k"}}), location="没配主机市"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.result == (
|
||||||
|
"尚未配置和风天气 api_host,请参考 docs/weather-integration.md 申请后填入"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_blank_api_key_counts_as_missing():
|
||||||
|
response = await weather_module.get_weather(
|
||||||
|
FakeConn({"get_weather": {"api_key": " ", "api_host": "h"}}), location="空密钥市"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "尚未配置和风天气 api_key" in response.result
|
||||||
|
|
||||||
|
|
||||||
|
async def test_no_credential_leaves_the_request_out(monkeypatch):
|
||||||
|
"""没配凭据就别去撞接口,调用次数得是零"""
|
||||||
|
called = []
|
||||||
|
|
||||||
|
async def fake_city_info(*args, **kwargs):
|
||||||
|
called.append(1)
|
||||||
|
return None
|
||||||
|
|
||||||
|
monkeypatch.setattr(weather_module, "fetch_city_info", fake_city_info)
|
||||||
|
|
||||||
|
await weather_module.get_weather(FakeConn(), location="无凭据市")
|
||||||
|
|
||||||
|
assert called == []
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 网页解析
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_weather_info_returns_none_when_city_name_missing():
|
||||||
|
"""页面结构变了要返回 None,抛异常的话 Python 原文会被念给用户"""
|
||||||
|
soup = BeautifulSoup("<html><div>没有城市名</div></html>", "html.parser")
|
||||||
|
|
||||||
|
assert weather_module.parse_weather_info(soup) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_weather_info_returns_none_when_forecast_icon_missing():
|
||||||
|
html = """
|
||||||
|
<h1 class="c-submenu__location">杭州市</h1>
|
||||||
|
<div class="city-forecast-tabs__row">
|
||||||
|
<div class="date-bg"><span class="date">今天10月24日</span></div>
|
||||||
|
</div>
|
||||||
|
"""
|
||||||
|
soup = BeautifulSoup(html, "html.parser")
|
||||||
|
|
||||||
|
assert weather_module.parse_weather_info(soup) is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_weather_info_returns_none_when_soup_is_missing():
|
||||||
|
assert weather_module.parse_weather_info(None) is None
|
||||||
|
|
||||||
|
|
||||||
|
async def test_broken_web_page_gives_a_neutral_message(monkeypatch):
|
||||||
|
async def fake_city_info(*args, **kwargs):
|
||||||
|
return {"id": "1", "name": "杭州", "fxLink": "https://example.com/x.html"}
|
||||||
|
|
||||||
|
async def fake_weather_data(*args, **kwargs):
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def fake_page(url):
|
||||||
|
return BeautifulSoup("<html></html>", "html.parser")
|
||||||
|
|
||||||
|
monkeypatch.setattr(weather_module, "fetch_city_info", fake_city_info)
|
||||||
|
monkeypatch.setattr(weather_module, "fetch_weather_data", fake_weather_data)
|
||||||
|
monkeypatch.setattr(weather_module, "fetch_weather_page", fake_page)
|
||||||
|
|
||||||
|
response = await weather_module.get_weather(
|
||||||
|
FakeConn({"get_weather": {"api_key": "k", "api_host": "h"}}), location="页面变了市"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.result == "暂时查不到天气数据,请稍后再试"
|
||||||
|
assert "AttributeError" not in str(response.result)
|
||||||
|
assert "NoneType" not in str(response.result)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 报告内容
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_carries_the_observation_time():
|
||||||
|
report = weather_module.build_weather_report(
|
||||||
|
{"name": "杭州"},
|
||||||
|
{"now": {"text": "多云", "obsTime": "2026-10-24T09:52+08:00"}},
|
||||||
|
{"daily": []},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "观测时间:2026-10-24 09:52+08:00" in report
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_falls_back_to_the_top_level_update_time():
|
||||||
|
"""now.updateTime 是空的,顶层那个才有用"""
|
||||||
|
report = weather_module.build_weather_report(
|
||||||
|
{"name": "杭州"},
|
||||||
|
{"updateTime": "2026-10-24T10:00+08:00", "now": {"text": "多云"}},
|
||||||
|
{"daily": []},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "观测时间:2026-10-24 10:00+08:00" in report
|
||||||
|
|
||||||
|
|
||||||
|
def test_report_without_any_observation_time_has_no_empty_line():
|
||||||
|
report = weather_module.build_weather_report(
|
||||||
|
{"name": "杭州"}, {"now": {"text": "多云"}}, {"daily": []}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "观测时间" not in report
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 两条路径的写法
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
def test_forecast_date_writing_is_the_same_on_both_paths():
|
||||||
|
today = datetime.date(2026, 10, 24)
|
||||||
|
|
||||||
|
assert weather_module.format_forecast_date("2026-10-24", today) == "今天10月24日"
|
||||||
|
assert weather_module.format_forecast_date("今天10月24日", today) == "今天10月24日"
|
||||||
|
assert weather_module.format_forecast_date("2026-10-25", today) == "明天10月25日"
|
||||||
|
assert weather_module.format_forecast_date("周日10月25日", today) == "明天10月25日"
|
||||||
|
assert weather_module.format_forecast_date("2026-10-27", today) == "周二10月27日"
|
||||||
|
assert weather_module.format_forecast_date("周二10月27日", today) == "周二10月27日"
|
||||||
|
|
||||||
|
|
||||||
|
def test_both_paths_write_the_same_date_and_units():
|
||||||
|
today = _today()
|
||||||
|
iso_date = today.isoformat()
|
||||||
|
web_date = f"今天{today.month}月{today.day}日"
|
||||||
|
|
||||||
|
json_report = weather_module.build_weather_report(
|
||||||
|
{"name": "杭州市"},
|
||||||
|
{
|
||||||
|
"now": {
|
||||||
|
"text": "多云",
|
||||||
|
"temp": "13",
|
||||||
|
"feelsLike": "13",
|
||||||
|
"humidity": "97",
|
||||||
|
"windDir": "西北风",
|
||||||
|
"windScale": "4",
|
||||||
|
"vis": "9",
|
||||||
|
"pressure": "1009",
|
||||||
|
"precip": "0.0",
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"daily": [
|
||||||
|
{
|
||||||
|
"fxDate": iso_date,
|
||||||
|
"textDay": "中雨",
|
||||||
|
"iconDay": "306",
|
||||||
|
"tempMax": "13",
|
||||||
|
"tempMin": "9",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
parsed = weather_module.parse_weather_info(
|
||||||
|
BeautifulSoup(_web_page(web_date), "html.parser")
|
||||||
|
)
|
||||||
|
web_report = weather_module.format_weather_report(*parsed)
|
||||||
|
|
||||||
|
for report in (json_report, web_report):
|
||||||
|
assert f"{web_date}" in report
|
||||||
|
assert "气温 9~13℃" in report
|
||||||
|
assert "能见度: 9公里" in report
|
||||||
|
assert "气压: 1009百帕" in report
|
||||||
|
assert "降水量: 0.0毫米" in report
|
||||||
|
assert "湿度: 97%" in report
|
||||||
|
assert "体感温度: 13℃" in report
|
||||||
|
assert "风力: 4级" in report
|
||||||
|
|
||||||
|
|
||||||
|
def test_web_page_units_are_written_in_chinese():
|
||||||
|
parsed = weather_module.parse_weather_info(
|
||||||
|
BeautifulSoup(_web_page("今天10月24日"), "html.parser")
|
||||||
|
)
|
||||||
|
|
||||||
|
_, _, current_basic, _ = parsed
|
||||||
|
assert current_basic["能见度"] == "9公里"
|
||||||
|
assert current_basic["气压"] == "1009百帕"
|
||||||
|
assert current_basic["降水量"] == "0.0毫米"
|
||||||
|
assert current_basic["湿度"] == "97%"
|
||||||
|
assert current_basic["体感温度"] == "13℃"
|
||||||
|
assert current_basic["风向"] == "西北风"
|
||||||
|
assert current_basic["风力"] == "4级"
|
||||||
|
|
||||||
|
|
||||||
|
def test_web_page_temperature_uses_the_same_unit_as_the_api_path():
|
||||||
|
parsed = weather_module.parse_weather_info(
|
||||||
|
BeautifulSoup(_web_page("今天10月24日"), "html.parser")
|
||||||
|
)
|
||||||
|
|
||||||
|
_, _, _, temps_list = parsed
|
||||||
|
assert temps_list[0][2] == "13"
|
||||||
|
assert temps_list[0][3] == "9"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 等待时间
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
async def test_web_fallback_does_not_wait_long(fake_http):
|
||||||
|
"""网页只是兜底,等太久不值得"""
|
||||||
|
fake_http.responder = lambda url, params: FakeResponse(text="<html></html>")
|
||||||
|
|
||||||
|
await weather_module.fetch_weather_page("https://example.com/x.html")
|
||||||
|
|
||||||
|
assert fake_http.init_kwargs["timeout"].read == 5.0
|
||||||
|
|
||||||
|
|
||||||
|
async def test_failure_is_remembered_so_the_next_ask_does_not_wait(monkeypatch):
|
||||||
|
"""上游挂着的时候别每次都把整条链路重走一遍"""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
async def fake_city_info(*args, **kwargs):
|
||||||
|
calls.append(1)
|
||||||
|
return None
|
||||||
|
|
||||||
|
monkeypatch.setattr(weather_module, "fetch_city_info", fake_city_info)
|
||||||
|
conn = FakeConn({"get_weather": {"api_key": "k", "api_host": "h"}})
|
||||||
|
|
||||||
|
first = await weather_module.get_weather(conn, location="失败标记市")
|
||||||
|
second = await weather_module.get_weather(conn, location="失败标记市")
|
||||||
|
|
||||||
|
assert calls == [1]
|
||||||
|
assert first.result == second.result
|
||||||
Loading…
Reference in a new issue