diff --git a/plugins/weather/config_default.py b/plugins/weather/config_default.py deleted file mode 100644 index 5536780b8f1f15fc04940de87847b974331e5840..0000000000000000000000000000000000000000 --- a/plugins/weather/config_default.py +++ /dev/null @@ -1,3 +0,0 @@ -# 和风天气 https://www.heweather.com - -KEY = "" diff --git a/plugins/weather/weather.py b/plugins/weather/weather.py deleted file mode 100644 index e601cdbfda3648148ea147112bbf91adca3544c3..0000000000000000000000000000000000000000 --- a/plugins/weather/weather.py +++ /dev/null @@ -1,84 +0,0 @@ -from register import command -from global_vars import CONFIG -import threading -import urllib -config = CONFIG[__name__] - -def plugin(): - return { - "author": "Antares", - "version": 1.0, - "description": "天气查询" - } - -def get_now_weather(local, key): - url = "https://free-api.heweather.net/s6/weather/now?location=%s&key=%s" % (str(urllib.parse.quote(local)), key) - import json - data = None - with urllib.request.urlopen(url) as f: - data = json.JSONDecoder().decode(f.read().decode("utf-8")) - return data['HeWeather6'][0] - -def get_air(local, key): - url = "https://free-api.heweather.net/s6/air/now?location=%s&key=%s" % (str(urllib.parse.quote(local)), key) - import json - data = None - with urllib.request.urlopen(url) as f: - data = json.JSONDecoder().decode(f.read().decode("utf-8")) - return data['HeWeather6'][0] - -def get_forecast_weather(local, key): - url = "https://free-api.heweather.net/s6/weather/forecast?location=%s&key=%s" % (str(urllib.parse.quote(local)), key) - import json - data = None - with urllib.request.urlopen(url) as f: - data = json.JSONDecoder().decode(f.read().decode("utf-8")) - return data['HeWeather6'][0] - -@command(name="天气", help="查询天气") -def weather(bot, context, args): - - while args[-1] == "": - del args[-1] - - def handle(): - now_weather = get_now_weather(args[1], config.KEY) - forecast_weather = get_forecast_weather(args[1], config.KEY) - - if not now_weather['status'] == "ok": - bot.send(context,"Now Weather Error: %s"% now_weather['status']) - return - - if not forecast_weather['status'] == "ok": - bot.send(context,"Forecast Weather Error: %s"% forecast_weather['status']) - return - - now_air = get_air(now_weather['basic'][ - 'parent_city' if 'parent_city' in now_weather['basic'] else 'location'], config.KEY) - - if not now_air['status'] == "ok": - now_air['air_now_city'] = {'qlty':"未知",'aqi':'未知'} - - location_data = "查询位置:%s,%s,%s,%s\n时区:%s\n更新时间:%s\n" % ( - now_weather['basic']['location'], now_weather['basic'][ - 'parent_city' if 'parent_city' in now_weather['basic'] else 'location'], - now_weather['basic'][ - 'admin_area' if 'admin_area' in now_weather['basic'] else 'location'], - now_weather['basic']['cnty'], now_weather['basic']['tz'], now_weather['update']['loc']) - - now_data = "当前天气:%s\n当前温度:%s摄氏度\n风向风力:%s %s级\n空气质量:%s\n空气质量指数(AQI):%s\n" % ( - now_weather['now']['cond_txt'], now_weather['now']['tmp'], - now_weather['now']['wind_dir'], now_weather['now']['wind_sc'], - now_air['air_now_city']['qlty'], now_air['air_now_city']['aqi']) - - more_days = [] - for item in forecast_weather['daily_forecast']: - more_days.append("天(%s):\n白天天气:%s\n夜间天气:%s\n最高温度:%s摄氏度\n最低温度:%s摄氏度" %( - item['date'],item['cond_txt_d'],item['cond_txt_n'],item['tmp_max'],item['tmp_min'] - )) - - message="%s\n%s\n最近三天:\n今%s\n明%s\n后%s" % ( - location_data, now_data, more_days[0], more_days[1], more_days[2]) - bot.send(context,message) - - threading.Thread(target=handle).start() diff --git a/plugins_new/weather/plugins.py b/plugins_new/weather/plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..f33957972d9fafeb3c90edc6ba6ffa4d0fafd63e --- /dev/null +++ b/plugins_new/weather/plugins.py @@ -0,0 +1,100 @@ +from common.plugin import Plugin +from common.config_loader import ConfigBase +from common.datatypes import PluginMeta +from common.countdown_bot import CountdownBot +from common.loop import TimeTuple +from common.command import ChatType +from common.event import GroupMessageEvent +import aiohttp +import urllib +from typing import Dict +from io import StringIO + + +class WeatherConfig(ConfigBase): + # 和风天气 https://www.heweather.com + APP_KEY = "" + + +class WeatherPlugin(Plugin): + async def get_data(self, local: str, type1: str, type2: str) -> dict: + async with self.aioclient.get(f"https://free-api.heweather.net/s6/{type1}/{type2}", params={ + "location": urllib.parse.quote(local), + "key": self.config.APP_KEY, + "lang": "zh" + }) as resp: + data = await resp.json() + return data['HeWeather6'][0] + + def generate_location(self, data: Dict[str, str]) -> str: + return f"""查询位置: {data["location"]},{data["parent_city"]},{data["admin_area"]},{data["cnty"]} +时区: {data["tz"]} +经度: {data["lon"]} +纬度: {data["lat"]} +""" + + def generate_weather(self, weather: Dict[str, str], air: Dict[str, str]) -> str: + return f"""当前天气: {weather["cond_txt"]} +当前温度: {weather["tmp"]}摄氏度 +风向风力: {weather["wind_dir"]} {weather["wind_sc"]}级 +空气质量: {air["qlty"]} +空气质量指数(AQI): {air["aqi"]} +""" + + def generate_forecast(self, index: int, data: Dict[str, str]) -> str: + return f"""{"今明后"[index]}天({data['date']}): +白天天气: {data['cond_txt_d']} +夜间天气: {data['cond_txt_n']} +最高温度: {data['tmp_max']}摄氏度 +最低温度: {data['tmp_min']}摄氏度""" + + def command_weather(self, plugin, args: List[str], raw_string: str, context, evt: GroupMessageEvent): + async def wrapper(): + weather_now = await self.get_data(args[0], "weather", "now") + weather_forecast = await self.get_data(args[0], "weather", "forecast") + if not weather_now['status'] == "ok": + self.bot.send(context, f"Error: {weather_now['status']}") + return + if not weather_forecast['status'] == 'ok': + self.bot.send(context, f"Error: {weather_forecast['status']}") + return + air_now = await self.get_data(weather_now['basic']['parent_city'], "air", "now") + message = StringIO() + message.write(self.generate_location(weather_now['basic'])) + message.write(f"更新时间:{weather_now['update']['loc']}\n\n") + message.write(self.generate_weather(weather_now['now'], + air_now['air_now_city'] if air_now['status'] == "ok" else {'qlty': "未知", 'aqi': '未知'})) + message.write("\n最近三天:\n") + for index, data in enumerate(weather_forecast['daily_forecast']): + message.write(self.generate_forecast(index, data)) + if index >= 2: + break + message.write('\n') + self.bot.send(context, message.getvalue()) + self.bot.submit_async_task(wrapper()) + + def on_enable(self): + self.aioclient = aiohttp.ClientSession() + self.bot: CountdownBot + self.config: WeatherConfig + self.register_command_wrapped( + command_name="weather", + command_handler=self.command_weather, + help_string="查询天气 | weather [地名/城市代码/IP地址/经度,纬度] (单个地名半角逗号分割小到大的行政区排列)", + chats={ChatType.discuss, ChatType.group, ChatType.private}, + alias=["天气"] + ) + + +def get_plugin_class(): + return WeatherPlugin + + +def get_config_class(): + return WeatherConfig + + +def get_plugin_meta(): + return PluginMeta( + "weather", 2.0, "天气查询" + )