88 lines
3.0 KiB
Python
88 lines
3.0 KiB
Python
from typing import Optional
|
|
|
|
import requests
|
|
from pydantic import BaseModel, model_validator
|
|
|
|
from notify.delivery.base import DeliveryProvider, render_notification_template
|
|
from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError
|
|
from notify.models import DeliveryChannel, DeliveryTokenConfig, NotificationRecipient
|
|
|
|
__all__ = [
|
|
'MAX_API_TIMEOUT',
|
|
'MaxTargetSchema',
|
|
'MaxDeliveryProvider',
|
|
]
|
|
|
|
MAX_API_TIMEOUT = 10
|
|
|
|
|
|
class MaxTargetSchema(BaseModel):
|
|
chat_id: int
|
|
user_id: Optional[int] = None
|
|
|
|
@model_validator(mode="after")
|
|
def validate_ids(self):
|
|
if self.user_id is None:
|
|
if self.chat_id >= 0:
|
|
raise ValueError("chat_id must be negative when user_id is not specified")
|
|
elif self.chat_id <= 0 or self.user_id <= 0:
|
|
raise ValueError("chat_id and user_id must be positive when both are specified")
|
|
return self
|
|
|
|
|
|
class MaxDeliveryProvider(DeliveryProvider):
|
|
channel = DeliveryChannel.MAX
|
|
target_schema = MaxTargetSchema
|
|
supports_codes = True
|
|
|
|
def target_key(self, target: MaxTargetSchema) -> str:
|
|
if target.user_id:
|
|
return f"user:{target.user_id}"
|
|
return f"chat:{target.chat_id}"
|
|
|
|
def send(self, recipient: NotificationRecipient) -> None:
|
|
_, body = render_notification_template(DeliveryChannel.MAX, recipient)
|
|
self.send_message(self.parse_target(recipient.delivery_target), "", body)
|
|
self.mark_sent(recipient)
|
|
|
|
def send_message(
|
|
self,
|
|
target: Optional[MaxTargetSchema],
|
|
subject: str,
|
|
body: str,
|
|
attachments=(),
|
|
) -> None:
|
|
delivery_config = DeliveryTokenConfig.get_default(DeliveryChannel.MAX)
|
|
if delivery_config is None:
|
|
raise DeliveryError("No default MAX delivery config")
|
|
if target is None:
|
|
raise PermanentDeliveryError("MAX recipient has no chat_id")
|
|
|
|
request_params = {}
|
|
if target.user_id:
|
|
request_params["user_id"] = target.user_id
|
|
else:
|
|
request_params["chat_id"] = target.chat_id
|
|
|
|
try:
|
|
response = requests.post(
|
|
"https://platform-api.max.ru/messages",
|
|
params=request_params,
|
|
headers={"Authorization": delivery_config.token},
|
|
json={
|
|
"chat_id": target.chat_id,
|
|
"text": body,
|
|
},
|
|
timeout=MAX_API_TIMEOUT,
|
|
)
|
|
response.raise_for_status()
|
|
except requests.Timeout as exc:
|
|
raise DeliveryError("MAX request timed out") from exc
|
|
except requests.HTTPError as exc:
|
|
status = exc.response.status_code if exc.response is not None else 0
|
|
if status == 429 or status >= 500:
|
|
raise DeliveryError(f"MAX API temporary error: {status}") from exc
|
|
raise PermanentDeliveryError(f"MAX API rejected the message: {status}") from exc
|
|
except requests.RequestException as exc:
|
|
raise DeliveryError("MAX request failed") from exc
|