chore: clean up code

This commit is contained in:
acgnhik 2022-05-02 12:55:24 +08:00
parent e44614fe4a
commit cc44f20c2f
4 changed files with 24 additions and 9 deletions

View File

@ -201,6 +201,7 @@ class PushplusNotifier(MessageNotifier):
super()._do_disable() super()._do_disable()
logger.debug('Disabled Pushplus notifier') logger.debug('Disabled Pushplus notifier')
class TelegramNotifier(MessageNotifier): class TelegramNotifier(MessageNotifier):
provider = Telegram.get_instance() provider = Telegram.get_instance()

View File

@ -12,7 +12,9 @@ import aiohttp
from ..utils.patterns import Singleton from ..utils.patterns import Singleton
__all__ = 'MessagingProvider', 'EmailService', 'Serverchan', 'Pushplus', 'Telegram' __all__ = (
'MessagingProvider', 'EmailService', 'Serverchan', 'Pushplus', 'Telegram'
)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -144,10 +146,12 @@ class Pushplus(MessagingProvider):
if response['code'] != 200: if response['code'] != 200:
raise HTTPException(response['code'], response['msg']) raise HTTPException(response['code'], response['msg'])
class TelegramResponse(TypedDict): class TelegramResponse(TypedDict):
ok: bool ok: bool
result: dict result: dict
class Telegram(MessagingProvider): class Telegram(MessagingProvider):
def __init__(self, token: str = '', chatid: str = '') -> None: def __init__(self, token: str = '', chatid: str = '') -> None:
super().__init__() super().__init__()
@ -175,6 +179,8 @@ class Telegram(MessagingProvider):
async with aiohttp.ClientSession(raise_for_status=True) as session: async with aiohttp.ClientSession(raise_for_status=True) as session:
async with session.post(url, json=payload) as res: async with session.post(url, json=payload) as res:
response = cast(TelegramResponse, await res.json()) response = cast(TelegramResponse, await res.json())
print(response)
if not response['ok']: if not response['ok']:
raise HTTPException(response['result']['error_code'], response['result']['description']) raise HTTPException(
response['result']['error_code'],
response['result']['description'],
)

View File

@ -14,7 +14,6 @@ from typing import (
import toml import toml
from blrec.notification.providers import Telegram
from pydantic import BaseModel as PydanticBaseModel from pydantic import BaseModel as PydanticBaseModel
from pydantic import Field, BaseSettings, validator, PrivateAttr from pydantic import Field, BaseSettings, validator, PrivateAttr
from pydantic.networks import HttpUrl, EmailStr from pydantic.networks import HttpUrl, EmailStr
@ -356,21 +355,26 @@ class PushplusSettings(BaseModel):
raise ValueError('token is invalid') raise ValueError('token is invalid')
return value return value
class TelegramSettings(BaseModel): class TelegramSettings(BaseModel):
token: str = '' token: str = ''
chatid: str = '' chatid: str = ''
@validator('token') @validator('token')
def _validate_token(cls, value: str) -> str: def _validate_token(cls, value: str) -> str:
if value != '' and not re.fullmatch(r'[0-9]{8,10}:[a-zA-Z0-9_-]{35}', value): if value != '' and not re.fullmatch(
r'[0-9]{8,10}:[a-zA-Z0-9_-]{35}', value
):
raise ValueError('token is invalid') raise ValueError('token is invalid')
return value return value
@validator('chatid') @validator('chatid')
def _validate_chatid(cls, value: str) -> str: def _validate_chatid(cls, value: str) -> str:
if value != '' and not re.fullmatch(r'(-|[0-9]){0,}', value): if value != '' and not re.fullmatch(r'(-|[0-9]){0,}', value):
raise ValueError('chatid is invalid') raise ValueError('chatid is invalid')
return value return value
class NotifierSettings(BaseModel): class NotifierSettings(BaseModel):
enabled: bool = False enabled: bool = False
@ -399,11 +403,13 @@ class PushplusNotificationSettings(
): ):
pass pass
class TelegramNotificationSettings( class TelegramNotificationSettings(
TelegramSettings, NotifierSettings, NotificationSettings TelegramSettings, NotifierSettings, NotificationSettings
): ):
pass pass
class WebHookEventSettings(BaseModel): class WebHookEventSettings(BaseModel):
live_began: bool = True live_began: bool = True
live_ended: bool = True live_ended: bool = True

View File

@ -21,7 +21,9 @@ from .models import (
) )
from .typing import KeySetOfSettings from .typing import KeySetOfSettings
from ..webhook import WebHook from ..webhook import WebHook
from ..notification import Notifier, EmailService, Serverchan, Pushplus, Telegram from ..notification import (
Notifier, EmailService, Serverchan, Pushplus, Telegram
)
from ..logging import configure_logger from ..logging import configure_logger
from ..exception import NotFoundError from ..exception import NotFoundError
if TYPE_CHECKING: if TYPE_CHECKING: