mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
refactor: 重构天气查询插件
使用和风天气作为数据源 功能更完善
This commit is contained in:
parent
0cb373012a
commit
4348ad74f2
2 changed files with 93 additions and 27 deletions
|
|
@ -11,7 +11,7 @@ import websockets
|
||||||
from typing import Dict, Any
|
from typing import Dict, Any
|
||||||
from core.utils.dialogue import Message, Dialogue
|
from core.utils.dialogue import Message, Dialogue
|
||||||
from core.handle.textHandle import handleTextMessage
|
from core.handle.textHandle import handleTextMessage
|
||||||
from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_from_string
|
from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_from_string, get_ip_info
|
||||||
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
from concurrent.futures import ThreadPoolExecutor, TimeoutError
|
||||||
from core.handle.sendAudioHandle import sendAudioMessage
|
from core.handle.sendAudioHandle import sendAudioMessage
|
||||||
from core.handle.receiveAudioHandle import handleAudioMessage
|
from core.handle.receiveAudioHandle import handleAudioMessage
|
||||||
|
|
@ -37,6 +37,8 @@ class ConnectionHandler:
|
||||||
|
|
||||||
self.websocket = None
|
self.websocket = None
|
||||||
self.headers = None
|
self.headers = None
|
||||||
|
self.client_ip = None
|
||||||
|
self.client_ip_info = {}
|
||||||
self.session_id = None
|
self.session_id = None
|
||||||
self.prompt = None
|
self.prompt = None
|
||||||
self.welcome_msg = None
|
self.welcome_msg = None
|
||||||
|
|
@ -103,8 +105,10 @@ class ConnectionHandler:
|
||||||
# 获取并验证headers
|
# 获取并验证headers
|
||||||
self.headers = dict(ws.request.headers)
|
self.headers = dict(ws.request.headers)
|
||||||
# 获取客户端ip地址
|
# 获取客户端ip地址
|
||||||
client_ip = ws.remote_address[0]
|
self.client_ip = ws.remote_address[0]
|
||||||
self.logger.bind(tag=TAG).info(f"{client_ip} conn - Headers: {self.headers}")
|
self.client_ip_info = get_ip_info(self.client_ip)
|
||||||
|
self.logger.bind(tag=TAG).info(f"{self.client_ip} conn - Headers: {self.headers}")
|
||||||
|
self.logger.bind(tag=TAG).info(f"Client ip info: {self.client_ip_info}")
|
||||||
|
|
||||||
# 进行认证
|
# 进行认证
|
||||||
await self.auth.authenticate(self.headers)
|
await self.auth.authenticate(self.headers)
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,104 @@
|
||||||
import requests
|
import requests
|
||||||
from bs4 import BeautifulSoup
|
from bs4 import BeautifulSoup
|
||||||
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
from plugins_func.register import register_function, ToolType, ActionResponse, Action
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
get_weather_function_desc = {
|
GET_WEATHER_FUNCTION_DESC = {
|
||||||
"type": "function",
|
"type": "function",
|
||||||
"function": {
|
"function": {
|
||||||
"name": "get_weather",
|
"name": "get_weather",
|
||||||
"description": "获取某个地点的天气,用户应先提供一个位置,比如用户说杭州天气,参数为:zhejiang/hangzhou,比如用户说北京天气怎么样,参数为:beijing/beijing。如果用户只问天气怎么样,参数是:guangdong/guangzhou",
|
"description": (
|
||||||
|
"获取某个地点的天气,用户应提供一个位置,比如用户说杭州天气,参数为:杭州。"
|
||||||
|
"如果用户说的是省份,默认用省会城市。如果用户说的不是省份或城市而是一个地名,"
|
||||||
|
"默认用该地所在省份的省会城市。"
|
||||||
|
),
|
||||||
"parameters": {
|
"parameters": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"properties": {
|
"properties": {
|
||||||
"city": {
|
"location": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"description": "城市,zhejiang/hangzhou"
|
"description": "地点名,例如杭州。可选参数,如果不提供则不传"
|
||||||
|
},
|
||||||
|
"lang": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "返回用户使用的语言code,例如zh_CN/zh_HK/en_US/ja_JP等,默认zh_CN"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"required": [
|
"required": ["lang"]
|
||||||
"city"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@register_function('get_weather', get_weather_function_desc, ToolType.WAIT)
|
API_KEY = "bdd98ec1d87747f3a2e8b1741a5af796" # TODO: 做成配置项
|
||||||
def get_weather(city: str):
|
DEFAULT_LOCATION = "广州"
|
||||||
"""
|
HEADERS = {
|
||||||
"获取某个地点的天气,用户应先提供一个位置,\n比如用户说杭州天气,参数为:zhejiang/hangzhou,\n\n比如用户说北京天气怎么样,参数为:beijing/beijing",
|
'User-Agent': (
|
||||||
city : 城市,zhejiang/hangzhou
|
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||||
"""
|
'(KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
|
||||||
url = "https://tianqi.moji.com/weather/china/"+city
|
)
|
||||||
headers = {
|
|
||||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
|
|
||||||
}
|
}
|
||||||
response = requests.get(url, headers=headers)
|
|
||||||
if response.status_code!=200:
|
|
||||||
|
def fetch_city_info(location):
|
||||||
|
url = f"https://geoapi.qweather.com/v2/city/lookup?key={API_KEY}&location={location}&lang=zh"
|
||||||
|
response = requests.get(url, headers=HEADERS).json()
|
||||||
|
return response.get('location', [])[0] if response.get('location') else None
|
||||||
|
|
||||||
|
|
||||||
|
def fetch_weather_page(url):
|
||||||
|
response = requests.get(url, headers=HEADERS)
|
||||||
|
return BeautifulSoup(response.text, "html.parser") if response.ok else None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_weather_info(soup):
|
||||||
|
city_name = soup.select_one("h1.c-submenu__location").get_text(strip=True)
|
||||||
|
|
||||||
|
current_abstract = soup.select_one(".c-city-weather-current .current-abstract")
|
||||||
|
current_abstract = current_abstract.get_text(strip=True) if current_abstract else "未知"
|
||||||
|
|
||||||
|
current_basic = {}
|
||||||
|
for item in soup.select(".c-city-weather-current .current-basic .current-basic___item"):
|
||||||
|
parts = item.get_text(strip=True, separator=" ").split(" ")
|
||||||
|
if len(parts) == 2:
|
||||||
|
key, value = parts[1], parts[0]
|
||||||
|
current_basic[key] = value
|
||||||
|
|
||||||
|
temps_list = []
|
||||||
|
for row in soup.select(".city-forecast-tabs__row")[:7]: # 取前7天的数据
|
||||||
|
date = row.select_one(".date-bg .date").get_text(strip=True)
|
||||||
|
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)
|
||||||
|
temps_list.append((date, high_temp, low_temp))
|
||||||
|
|
||||||
|
return city_name, current_abstract, current_basic, temps_list
|
||||||
|
|
||||||
|
|
||||||
|
@register_function('get_weather', GET_WEATHER_FUNCTION_DESC, ToolType.SYSTEM_CTL)
|
||||||
|
def get_weather(conn, location: str = None, lang: str = "zh_CN"):
|
||||||
|
location = location or conn.client_ip_info.get("city") or DEFAULT_LOCATION
|
||||||
|
logger.bind(tag=TAG).debug(f"获取天气: {location}")
|
||||||
|
|
||||||
|
city_info = fetch_city_info(location)
|
||||||
|
if not city_info:
|
||||||
|
return ActionResponse(Action.REQLLM, f"未找到相关的城市: {location},请确认地点是否正确", None)
|
||||||
|
|
||||||
|
soup = fetch_weather_page(city_info['fxLink'])
|
||||||
|
if not soup:
|
||||||
return ActionResponse(Action.REQLLM, None, "请求失败")
|
return ActionResponse(Action.REQLLM, None, "请求失败")
|
||||||
soup = BeautifulSoup(response.text, "html.parser")
|
|
||||||
weather = soup.find('meta', attrs={'name':'description'})["content"]
|
city_name, current_abstract, current_basic, temps_list = parse_weather_info(soup)
|
||||||
weather = weather.replace("墨迹天气", "")
|
weather_report = f"根据下列数据,用{lang}回应用户的查询天气请求:\n{city_name}未来7天天气:\n"
|
||||||
return ActionResponse(Action.REQLLM, weather, None)
|
for i, (date, high, low) in enumerate(temps_list):
|
||||||
|
if high and low:
|
||||||
|
weather_report += f"{date}: {low}到{high}\n"
|
||||||
|
weather_report += (
|
||||||
|
f"当前天气: {current_abstract}\n"
|
||||||
|
f"当前天气参数: {current_basic}\n"
|
||||||
|
f"(确保只报告指定单日的气温范围,除非用户明确要求想要了解多日天气,如果未指定,默认报告今天的温度范围。"
|
||||||
|
"参数为0的值不需要报告给用户,每次都报告体感温度,根据语境选择合适的参数内容告知用户,并对参数给出相应评价)"
|
||||||
|
)
|
||||||
|
|
||||||
|
return ActionResponse(Action.REQLLM, weather_report, None)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue