|
| 1 | +"""OneBot v11 notification provider. |
| 2 | +
|
| 3 | +OneBot v11 is a standard for QQ bot APIs. This provider sends |
| 4 | +notifications via the OneBot v11 HTTP API. |
| 5 | +
|
| 6 | +Documentation: https://github.com/botuniverse/onebot-11 |
| 7 | +""" |
| 8 | + |
| 9 | +import json |
| 10 | +import logging |
| 11 | +from typing import TYPE_CHECKING |
| 12 | + |
| 13 | +from module.models.bangumi import Notification |
| 14 | +from module.notification.base import NotificationProvider |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from module.models.config import NotificationProvider as ProviderConfig |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class OneBotProvider(NotificationProvider): |
| 23 | + """OneBot v11 HTTP API notification provider. |
| 24 | +
|
| 25 | + Sends anime update notifications through a OneBot v11-compatible |
| 26 | + QQ bot using the HTTP API. |
| 27 | +
|
| 28 | + Config fields used: |
| 29 | + - url: Base URL of the OneBot HTTP API (e.g. http://localhost:5700) |
| 30 | + - token: Optional Authorization access_token |
| 31 | + - chat_id: Target user_id (private) or group_id (group) |
| 32 | + - message_type: "private" for private messages, "group" for group messages |
| 33 | + """ |
| 34 | + |
| 35 | + def __init__(self, config: "ProviderConfig"): |
| 36 | + super().__init__() |
| 37 | + self.base_url = config.url.rstrip("/") |
| 38 | + self.token = config.token or "" |
| 39 | + self.chat_id = config.chat_id or "" |
| 40 | + self.message_type = config.message_type or "private" |
| 41 | + |
| 42 | + # Build API endpoints |
| 43 | + self.private_msg_url = f"{self.base_url}/send_private_msg" |
| 44 | + self.group_msg_url = f"{self.base_url}/send_group_msg" |
| 45 | + |
| 46 | + # Build JSON headers (OneBot API expects application/json) |
| 47 | + self.json_headers = { |
| 48 | + "Content-Type": "application/json", |
| 49 | + "Accept": "application/json", |
| 50 | + } |
| 51 | + if self.token: |
| 52 | + self.json_headers["Authorization"] = f"Bearer {self.token}" |
| 53 | + |
| 54 | + async def _post_json(self, url: str, data: dict) -> object: |
| 55 | + """Send a JSON POST request using the shared httpx client. |
| 56 | +
|
| 57 | + OneBot API requires proper application/json content type, |
| 58 | + which the inherited post_data() does not provide (it sends |
| 59 | + form-encoded data). This method uses the underlying httpx |
| 60 | + client directly with json= parameter. |
| 61 | +
|
| 62 | + Args: |
| 63 | + url: The URL to send the request to. |
| 64 | + data: The JSON-serializable data to send. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + The httpx response object, or None on failure. |
| 68 | + """ |
| 69 | + try: |
| 70 | + req = await self._client.post( |
| 71 | + url=url, |
| 72 | + json=data, |
| 73 | + headers=self.json_headers, |
| 74 | + ) |
| 75 | + req.raise_for_status() |
| 76 | + return req |
| 77 | + except Exception as e: |
| 78 | + logger.warning(f"[OneBot] Request failed: {e}") |
| 79 | + return None |
| 80 | + |
| 81 | + def _build_payload( |
| 82 | + self, text: str, poster_path: str = None |
| 83 | + ) -> str | list: |
| 84 | + """Build the message payload for OneBot API. |
| 85 | +
|
| 86 | + For plain text (no poster), sends a simple string. |
| 87 | + When a poster image is available, sends a message segment array |
| 88 | + with both image and text. |
| 89 | +
|
| 90 | + Args: |
| 91 | + text: The text message content. |
| 92 | + poster_path: Optional URL to a poster image. |
| 93 | +
|
| 94 | + Returns: |
| 95 | + A string (plain text) or list (message segments). |
| 96 | + """ |
| 97 | + if poster_path and poster_path not in ("", "https://mikanani.me"): |
| 98 | + return [ |
| 99 | + {"type": "image", "data": {"file": poster_path}}, |
| 100 | + {"type": "text", "data": {"text": text}}, |
| 101 | + ] |
| 102 | + return text |
| 103 | + |
| 104 | + async def send(self, notification: Notification) -> bool: |
| 105 | + """Send notification via OneBot v11. |
| 106 | +
|
| 107 | + Args: |
| 108 | + notification: The notification data. |
| 109 | +
|
| 110 | + Returns: |
| 111 | + True if the message was sent successfully. |
| 112 | + """ |
| 113 | + text = self._format_message(notification) |
| 114 | + message = self._build_payload(text, notification.poster_path) |
| 115 | + |
| 116 | + if self.message_type == "group": |
| 117 | + payload = { |
| 118 | + "group_id": int(self.chat_id), |
| 119 | + "message": message, |
| 120 | + } |
| 121 | + url = self.group_msg_url |
| 122 | + else: |
| 123 | + payload = { |
| 124 | + "user_id": int(self.chat_id), |
| 125 | + "message": message, |
| 126 | + } |
| 127 | + url = self.private_msg_url |
| 128 | + |
| 129 | + resp = await self._post_json(url, payload) |
| 130 | + logger.debug("OneBot notification: %s", resp.status_code if resp else None) |
| 131 | + |
| 132 | + if resp and resp.status_code == 200: |
| 133 | + try: |
| 134 | + result = resp.json() |
| 135 | + if result.get("status") == "ok" or result.get("retcode") == 0: |
| 136 | + return True |
| 137 | + else: |
| 138 | + logger.warning("OneBot API returned error: %s", result) |
| 139 | + return False |
| 140 | + except (json.JSONDecodeError, AttributeError): |
| 141 | + return True |
| 142 | + |
| 143 | + return resp is not None and resp.status_code == 200 |
| 144 | + |
| 145 | + async def test(self) -> tuple[bool, str]: |
| 146 | + """Test the OneBot configuration by sending a test message. |
| 147 | +
|
| 148 | + Returns: |
| 149 | + A tuple of (success, message). |
| 150 | + """ |
| 151 | + text = "AutoBangumi 通知测试成功!\nNotification test successful!" |
| 152 | + |
| 153 | + if self.message_type == "group": |
| 154 | + payload = { |
| 155 | + "group_id": int(self.chat_id), |
| 156 | + "message": text, |
| 157 | + } |
| 158 | + url = self.group_msg_url |
| 159 | + else: |
| 160 | + payload = { |
| 161 | + "user_id": int(self.chat_id), |
| 162 | + "message": text, |
| 163 | + } |
| 164 | + url = self.private_msg_url |
| 165 | + |
| 166 | + try: |
| 167 | + resp = await self._post_json(url, payload) |
| 168 | + if resp and resp.status_code == 200: |
| 169 | + try: |
| 170 | + result = resp.json() |
| 171 | + if result.get("status") == "ok" or result.get("retcode") == 0: |
| 172 | + return True, "OneBot test message sent successfully" |
| 173 | + else: |
| 174 | + error_msg = ( |
| 175 | + result.get("msg") |
| 176 | + or result.get("wording") |
| 177 | + or "unknown error" |
| 178 | + ) |
| 179 | + return False, f"OneBot API error: {error_msg}" |
| 180 | + except (json.JSONDecodeError, AttributeError): |
| 181 | + return True, "OneBot test message sent successfully" |
| 182 | + else: |
| 183 | + status = resp.status_code if resp else "No response" |
| 184 | + return False, f"OneBot API returned status {status}" |
| 185 | + except Exception as e: |
| 186 | + return False, f"OneBot test failed: {e}" |
0 commit comments