Skip to content

Commit

Permalink
change qweather_apitype type & use nonebot_plugin_alconna
Browse files Browse the repository at this point in the history
  • Loading branch information
MeetWq committed Mar 4, 2024
1 parent f0ef0e1 commit 60f6d3c
Show file tree
Hide file tree
Showing 9 changed files with 744 additions and 2,505 deletions.
37 changes: 15 additions & 22 deletions nonebot_plugin_heweather/__init__.py
Original file line number Diff line number Diff line change
@@ -1,54 +1,47 @@
from nonebot import on_keyword, require
from nonebot import require
from nonebot.log import logger
from nonebot.matcher import Matcher
from nonebot.params import EventPlainText
from nonebot.plugin import PluginMetadata, inherit_supported_adapters

require("nonebot_plugin_saa")
require("nonebot_plugin_alconna")
require("nonebot_plugin_htmlrender")

from nonebot_plugin_saa import Image, MessageFactory # noqa: E402
from nonebot_plugin_alconna import Alconna, Args, UniMessage, on_alconna

from .config import DEBUG, QWEATHER_APIKEY, QWEATHER_APITYPE, Config # noqa: E402
from .render_pic import render # noqa: E402
from .weather_data import CityNotFoundError, ConfigError, Weather # noqa: E402
from .config import DEBUG, QWEATHER_APIKEY, QWEATHER_APITYPE, Config
from .render_pic import render
from .weather_data import CityNotFoundError, ConfigError, Weather

__plugin_meta__ = PluginMetadata(
name="nonebot-plugin-heweather",
name="和风天气",
description="和风天气图片显示插件",
usage="天气地名 / 地名天气",
type="application",
homepage="https://github.com/kexue-z/nonebot-plugin-heweather",
config=Config,
supported_adapters=inherit_supported_adapters("nonebot_plugin_saa"),
supported_adapters=inherit_supported_adapters("nonebot_plugin_alconna"),
)


if DEBUG:
logger.debug("将会保存图片到 weather.png")


weather = on_keyword({"天气"}, priority=1)
weather = on_alconna(Alconna("天气", Args["city", str]), block=True, priority=1)
weather.shortcut(r"^(?P<city>.+)天气$", {"args": ["{city}"], "fuzzy": False})
weather.shortcut(r"^天气(?P<city>.+)$", {"args": ["{city}"], "fuzzy": False})


@weather.handle()
async def _(matcher: Matcher, arg: str = EventPlainText()):
if not (QWEATHER_APIKEY and QWEATHER_APITYPE):
async def _(matcher: Matcher, city: str):
if QWEATHER_APIKEY is None or QWEATHER_APITYPE is None:
raise ConfigError("请设置 qweather_apikey 和 qweather_apitype")

city = ""
if args := arg.split("天气"):
city = args[0].strip() or args[1].strip()
if not city:
await matcher.finish("地点是...空气吗?? >_<")

# 判断指令前后是否都有内容,如果是则结束,否则跳过。
if (args[0].strip() == "") == (args[1].strip() == ""):
await matcher.finish()
w_data = Weather(city_name=city, api_key=QWEATHER_APIKEY, api_type=QWEATHER_APITYPE)
try:
await w_data.load_data()
except CityNotFoundError:
logger.warning(f"找不到城市: {city}")
matcher.block = False
await matcher.finish()

Expand All @@ -57,7 +50,7 @@ async def _(matcher: Matcher, arg: str = EventPlainText()):
if DEBUG:
debug_save_img(img)

await MessageFactory([Image(img)]).send()
await UniMessage.image(raw=img).send()


def debug_save_img(img: bytes) -> None:
Expand Down
2 changes: 1 addition & 1 deletion nonebot_plugin_heweather/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

class Config(BaseModel):
qweather_apikey: Optional[str] = Field(default=None)
qweather_apitype: Optional[str] = Field(default=None)
qweather_apitype: Optional[int] = Field(default=None)
qweather_hourlytype: Optional[HourlyType] = Field(default=HourlyType.current_12h)
qweather_forecase_days: Optional[int] = Field(default=3)
debug: Optional[bool] = Field(default=False)
Expand Down
83 changes: 72 additions & 11 deletions nonebot_plugin_heweather/model.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
from enum import IntEnum
from typing import List, Optional

from pydantic import BaseModel, ConfigDict, Extra
from nonebot.compat import PYDANTIC_V2, ConfigDict
from pydantic import BaseModel


class Now(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

obsTime: str
temp: str
icon: str
Expand All @@ -18,13 +25,25 @@ class Now(BaseModel):


class NowApi(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

code: str
now: Now


class Daily(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

fxDate: str
week: Optional[str]
date: Optional[str]
Expand All @@ -37,13 +56,25 @@ class Daily(BaseModel):


class DailyApi(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

code: str
daily: List[Daily]


class Air(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

category: str
aqi: str
pm2p5: str
Expand All @@ -56,27 +87,51 @@ class Air(BaseModel):


class AirApi(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

code: str
now: Optional[Air]


class Warning(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

title: str
type: str
pubTime: str
text: str


class WarningApi(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

code: str
warning: Optional[List[Warning]]


class Hourly(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

fxTime: str
hour: Optional[str]
temp: str
Expand All @@ -86,7 +141,13 @@ class Hourly(BaseModel):


class HourlyApi(BaseModel):
model_config = ConfigDict(extra=Extra.allow)
if PYDANTIC_V2:
model_config = ConfigDict(extra="allow")
else:

class Config:
extra = "allow"

code: str
hourly: List[Hourly]

Expand Down
18 changes: 8 additions & 10 deletions nonebot_plugin_heweather/weather_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import asyncio
from typing import Optional, Union
from typing import Optional

from httpx import AsyncClient, Response
from nonebot.log import logger
Expand All @@ -8,16 +8,13 @@
from .model import AirApi, DailyApi, HourlyApi, NowApi, WarningApi


class APIError(Exception):
...
class APIError(Exception): ...


class ConfigError(Exception):
...
class ConfigError(Exception): ...


class CityNotFoundError(Exception):
...
class CityNotFoundError(Exception): ...


class Weather:
Expand All @@ -40,7 +37,8 @@ def __url__(self):
logger.info("使用免费订阅API")
else:
raise ConfigError(
"api_type 必须是为 (int)0 -> 免费订阅, (int)1 -> 标准订阅, (int)2 -> 商业版"
"api_type 必须是为 (int)0 -> 免费订阅, "
"(int)1 -> 标准订阅, (int)2 -> 商业版"
f"\n当前为: ({type(self.api_type)}){self.api_type}"
)

Expand All @@ -50,10 +48,10 @@ def _forecast_days(self):
if self.api_type == 0 and not (3 <= self.forecast_days <= 7):
raise ConfigError("api_type = 0 免费订阅 预报天数必须 3<= x <=7")

def __init__(self, city_name: str, api_key: str, api_type: Union[int, str] = 0):
def __init__(self, city_name: str, api_key: str, api_type: int = 0):
self.city_name = city_name
self.apikey = api_key
self.api_type = int(api_type)
self.api_type = api_type
self.__url__()

self._forecast_days()
Expand Down
Loading

0 comments on commit 60f6d3c

Please sign in to comment.