diff --git a/builtin/python/baihu/__init__.py b/builtin/python/baihu/__init__.py new file mode 100644 index 0000000..a3f9776 --- /dev/null +++ b/builtin/python/baihu/__init__.py @@ -0,0 +1,22 @@ +import os +from .notify import notify as _notify + +def notify(title, text): + """ + 发送内建通知。 + 会在调用时校验环境变量:BHPKG_NOTIFY_TOKEN, BHPKG_NOTIFY_CHANNEL + """ + _TOKEN = os.environ.get("BHPKG_NOTIFY_TOKEN") + _CHANNEL = os.environ.get("BHPKG_NOTIFY_CHANNEL") + + if not _TOKEN or not _CHANNEL: + missing = [] + if not _TOKEN: missing.append("BHPKG_NOTIFY_TOKEN") + if not _CHANNEL: missing.append("BHPKG_NOTIFY_CHANNEL") + + error_msg = f"缺少必要的环境变量以使用 baihu 模块: {', '.join(missing)}。请在白虎面板的任务设置中配置指定的 Key。" + raise RuntimeError(error_msg) + + return _notify(title, text) + +__all__ = ['notify'] diff --git a/builtin/python/baihu/notify.py b/builtin/python/baihu/notify.py new file mode 100644 index 0000000..bd96b77 --- /dev/null +++ b/builtin/python/baihu/notify.py @@ -0,0 +1,32 @@ +import os +import json +import urllib.request + +def notify(title, text, channel_id=None): + """ + 发送内建通知。 + """ + token = os.environ.get("BHPKG_NOTIFY_TOKEN") + url = os.environ.get("BHPKG_NOTIFY_URL", "http://localhost:8052/api/v1/notify/send") + default_channel = os.environ.get("BHPKG_NOTIFY_CHANNEL") + + cid = channel_id or default_channel + + if not url or not token or not cid: + return + + payload = { + "channel_id": cid, + "title": title, + "text": text + } + + data = json.dumps(payload).encode('utf-8') + req = urllib.request.Request(url, data=data, method='POST') + req.add_header('Content-Type', 'application/json') + req.add_header('notify-token', token) + + + with urllib.request.urlopen(req) as resp: + return resp.read().decode('utf-8') +