gotify-client 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gotify_client/__init__.py +44 -0
- gotify_client/__main__.py +6 -0
- gotify_client/cli.py +343 -0
- gotify_client/client.py +260 -0
- gotify_client-0.1.0.dist-info/METADATA +294 -0
- gotify_client-0.1.0.dist-info/RECORD +8 -0
- gotify_client-0.1.0.dist-info/WHEEL +4 -0
- gotify_client-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Gotify 消息推送 Python 客户端工具包。"""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Dict, Optional
|
|
4
|
+
|
|
5
|
+
from .client import GotifyNotifier
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = ["GotifyNotifier", "init", "send"]
|
|
9
|
+
|
|
10
|
+
_default_notifier: Optional[GotifyNotifier] = None
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def init(
|
|
14
|
+
server_url: Optional[str] = None,
|
|
15
|
+
app_token: Optional[str] = None,
|
|
16
|
+
**kwargs: Any,
|
|
17
|
+
) -> GotifyNotifier:
|
|
18
|
+
"""初始化全局默认推送实例。"""
|
|
19
|
+
global _default_notifier
|
|
20
|
+
_default_notifier = GotifyNotifier(server_url=server_url, app_token=app_token, **kwargs)
|
|
21
|
+
return _default_notifier
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def send(
|
|
25
|
+
message: str,
|
|
26
|
+
title: Optional[str] = None,
|
|
27
|
+
priority: Optional[int] = None,
|
|
28
|
+
markdown: bool = False,
|
|
29
|
+
click_url: Optional[str] = None,
|
|
30
|
+
ignore_errors: Optional[bool] = None,
|
|
31
|
+
) -> Optional[Dict[str, Any]]:
|
|
32
|
+
"""使用全局默认实例发送消息(若未手动调用 init,则自动尝试从环境变量读取配置)。"""
|
|
33
|
+
global _default_notifier
|
|
34
|
+
if _default_notifier is None:
|
|
35
|
+
_default_notifier = GotifyNotifier()
|
|
36
|
+
|
|
37
|
+
return _default_notifier.send(
|
|
38
|
+
message=message,
|
|
39
|
+
title=title,
|
|
40
|
+
priority=priority,
|
|
41
|
+
markdown=markdown,
|
|
42
|
+
click_url=click_url,
|
|
43
|
+
ignore_errors=ignore_errors,
|
|
44
|
+
)
|
gotify_client/cli.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from rich.console import Console
|
|
8
|
+
from rich.markup import escape
|
|
9
|
+
from rich.panel import Panel
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
|
|
12
|
+
from . import __version__
|
|
13
|
+
from .client import (
|
|
14
|
+
CONFIG_FILE_PATH,
|
|
15
|
+
GotifyNotifier,
|
|
16
|
+
check_server_health,
|
|
17
|
+
load_local_config,
|
|
18
|
+
resolve_base_url,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
app = typer.Typer(
|
|
22
|
+
name="gotify-client",
|
|
23
|
+
help="🚀 轻量级 Gotify 消息推送命令行工具",
|
|
24
|
+
no_args_is_help=True,
|
|
25
|
+
rich_markup_mode="rich",
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _make_console(*, stderr: bool = False) -> Console:
|
|
30
|
+
"""构造 Console,并保证在 GBK 等非 UTF-8 终端下不会因为 emoji 直接崩溃。"""
|
|
31
|
+
stream = sys.stderr if stderr else sys.stdout
|
|
32
|
+
# Python 3.7+ 的 TextIOWrapper 支持 reconfigure;不可编码的字符替换掉而不是抛异常
|
|
33
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
34
|
+
if reconfigure is not None:
|
|
35
|
+
try:
|
|
36
|
+
reconfigure(errors="replace")
|
|
37
|
+
except (ValueError, OSError):
|
|
38
|
+
pass
|
|
39
|
+
return Console(stderr=stderr)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
console = _make_console()
|
|
43
|
+
err_console = _make_console(stderr=True)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _read_stdin() -> str:
|
|
47
|
+
"""从管道读取消息正文。
|
|
48
|
+
|
|
49
|
+
终端 locale 不一定是 UTF-8(例如 Windows 中文环境是 GBK),
|
|
50
|
+
直接 sys.stdin.read() 会抛 UnicodeDecodeError,因此按字节读取后显式解码。
|
|
51
|
+
"""
|
|
52
|
+
raw = sys.stdin.buffer.read()
|
|
53
|
+
for encoding in ("utf-8", sys.stdin.encoding or "utf-8"):
|
|
54
|
+
try:
|
|
55
|
+
text = raw.decode(encoding)
|
|
56
|
+
break
|
|
57
|
+
except (UnicodeDecodeError, LookupError):
|
|
58
|
+
continue
|
|
59
|
+
else:
|
|
60
|
+
text = raw.decode("utf-8", errors="replace")
|
|
61
|
+
# 去掉管道末尾的换行:`echo hi | gotify-client send` 应该推送 "hi" 而不是 "hi\n"
|
|
62
|
+
return text.rstrip("\r\n")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _get_message_icon(message: str, priority: int) -> str:
|
|
66
|
+
msg_lower = message.lower()
|
|
67
|
+
if priority >= 8 or any(
|
|
68
|
+
k in msg_lower for k in ["error", "fail", "异常", "警告", "告警", "超时", "失败"]
|
|
69
|
+
):
|
|
70
|
+
return "🚨"
|
|
71
|
+
if any(k in msg_lower for k in ["success", "done", "完成", "成功", "部署", "备份"]):
|
|
72
|
+
return "🎉"
|
|
73
|
+
if any(k in msg_lower for k in ["disk", "cpu", "内存", "磁盘", "负载"]):
|
|
74
|
+
return "📊"
|
|
75
|
+
return "💬"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _format_priority(priority: int, rich_mode: bool = True) -> str:
|
|
79
|
+
if rich_mode:
|
|
80
|
+
if priority >= 8:
|
|
81
|
+
return f"🔴 [bold red]{priority} (紧急/强提醒)[/bold red]"
|
|
82
|
+
if priority >= 4:
|
|
83
|
+
return f"🟡 [yellow]{priority} (普通)[/yellow]"
|
|
84
|
+
if priority >= 1:
|
|
85
|
+
return f"🔵 [blue]{priority} (低)[/blue]"
|
|
86
|
+
return f"⚪ [dim]{priority} (静默)[/dim]"
|
|
87
|
+
else:
|
|
88
|
+
if priority >= 8:
|
|
89
|
+
return f"🔴 \033[91m{priority} (紧急)\033[0m"
|
|
90
|
+
if priority >= 4:
|
|
91
|
+
return f"🟡 \033[93m{priority} (普通)\033[0m"
|
|
92
|
+
if priority >= 1:
|
|
93
|
+
return f"🔵 \033[94m{priority} (低)\033[0m"
|
|
94
|
+
return f"⚪ \033[2m{priority} (静默)\033[0m"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _render_success(
|
|
98
|
+
style: str,
|
|
99
|
+
title: str,
|
|
100
|
+
message: str,
|
|
101
|
+
priority: int,
|
|
102
|
+
markdown: bool,
|
|
103
|
+
url: Optional[str],
|
|
104
|
+
result: Dict[str, Any],
|
|
105
|
+
) -> None:
|
|
106
|
+
msg_icon = _get_message_icon(message, priority)
|
|
107
|
+
preview = message.strip() if len(message.strip()) <= 200 else f"{message.strip()[:200]}..."
|
|
108
|
+
|
|
109
|
+
if style == "rich":
|
|
110
|
+
grid = Table.grid(padding=(0, 2))
|
|
111
|
+
grid.add_column(style="bold dim", justify="right")
|
|
112
|
+
grid.add_column()
|
|
113
|
+
grid.add_row("🆔 消息 ID:", f"[bold green]#{result.get('id')}[/bold green]")
|
|
114
|
+
grid.add_row("📌 标题:", f"[bold white]{escape(title)}[/bold white]")
|
|
115
|
+
grid.add_row("⚡ 优先级:", _format_priority(priority, True))
|
|
116
|
+
grid.add_row("🎨 格式:", "📝 [cyan]Markdown[/cyan]" if markdown else "📄 纯文本")
|
|
117
|
+
if url:
|
|
118
|
+
grid.add_row("🔗 跳转链接:", f"[underline blue]{escape(url)}[/underline blue]")
|
|
119
|
+
grid.add_row(f"{msg_icon} 正文内容:", escape(preview))
|
|
120
|
+
|
|
121
|
+
console.print(
|
|
122
|
+
Panel(
|
|
123
|
+
grid,
|
|
124
|
+
title="[bold green]🚀 Gotify 推送成功[/bold green]",
|
|
125
|
+
border_style="green",
|
|
126
|
+
expand=False,
|
|
127
|
+
)
|
|
128
|
+
)
|
|
129
|
+
else:
|
|
130
|
+
GREEN, CYAN, DIM, BOLD, RESET = (
|
|
131
|
+
"\033[92m",
|
|
132
|
+
"\033[96m",
|
|
133
|
+
"\033[2m",
|
|
134
|
+
"\033[1m",
|
|
135
|
+
"\033[0m",
|
|
136
|
+
)
|
|
137
|
+
print(f"\n🚀 {GREEN}{BOLD}推送成功{RESET} {DIM}(🆔 #{result.get('id')}){RESET}")
|
|
138
|
+
print(f"{DIM}{'─' * 42}{RESET}")
|
|
139
|
+
print(f" 📌 {CYAN}标题{RESET} : {title}")
|
|
140
|
+
print(f" ⚡ {CYAN}等级{RESET} : {_format_priority(priority, False)}")
|
|
141
|
+
print(f" 🎨 {CYAN}格式{RESET} : {'📝 Markdown' if markdown else '📄 纯文本'}")
|
|
142
|
+
if url:
|
|
143
|
+
print(f" 🔗 {CYAN}链接{RESET} : {url}")
|
|
144
|
+
print(f" {msg_icon} {CYAN}内容{RESET} : {preview}")
|
|
145
|
+
print(f"{DIM}{'─' * 42}{RESET}\n")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _render_error(style: str, error: Exception) -> None:
|
|
149
|
+
if style == "rich":
|
|
150
|
+
err_console.print(
|
|
151
|
+
Panel(
|
|
152
|
+
f"❌ [red]{escape(str(error))}[/red]",
|
|
153
|
+
title="[bold red]💥 Gotify 推送失败[/bold red]",
|
|
154
|
+
border_style="red",
|
|
155
|
+
expand=False,
|
|
156
|
+
)
|
|
157
|
+
)
|
|
158
|
+
else:
|
|
159
|
+
RED, BOLD, RESET = "\033[91m", "\033[1m", "\033[0m"
|
|
160
|
+
print(f"\n💥 {RED}{BOLD}推送失败:{RESET} ❌ {error}\n", file=sys.stderr)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@app.command("send")
|
|
164
|
+
def cmd_send(
|
|
165
|
+
message: Optional[str] = typer.Argument(None, help="消息正文(不传则自动从管道 stdin 读取)"),
|
|
166
|
+
title: Optional[str] = typer.Option(
|
|
167
|
+
None, "--title", "-t", help="消息标题(默认取本地配置或「系统通知」)"
|
|
168
|
+
),
|
|
169
|
+
priority: Optional[int] = typer.Option(
|
|
170
|
+
None,
|
|
171
|
+
"--priority",
|
|
172
|
+
"-p",
|
|
173
|
+
min=0,
|
|
174
|
+
max=10,
|
|
175
|
+
help="消息优先级 (0-10),默认取本地配置或 5",
|
|
176
|
+
),
|
|
177
|
+
markdown: bool = typer.Option(False, "--markdown", "-m", help="启用 Markdown 格式渲染"),
|
|
178
|
+
url: Optional[str] = typer.Option(None, "--url", "-u", help="点击通知后打开的链接"),
|
|
179
|
+
style: str = typer.Option(
|
|
180
|
+
os.getenv("GOTIFY_STYLE", "rich"),
|
|
181
|
+
"--style",
|
|
182
|
+
"-s",
|
|
183
|
+
help="输出风格: rich 或 plain",
|
|
184
|
+
),
|
|
185
|
+
quiet: bool = typer.Option(False, "--quiet", "-q", help="静默模式:成功时不输出信息"),
|
|
186
|
+
server: Optional[str] = typer.Option(None, "--server", help="临时覆盖 Gotify 服务器地址"),
|
|
187
|
+
token: Optional[str] = typer.Option(None, "--token", help="临时覆盖 App Token"),
|
|
188
|
+
) -> None:
|
|
189
|
+
"""📤 发送一条推送消息到 Gotify 服务器。"""
|
|
190
|
+
if message is None and not sys.stdin.isatty():
|
|
191
|
+
message = _read_stdin()
|
|
192
|
+
|
|
193
|
+
if not message or not message.strip():
|
|
194
|
+
err_console.print(
|
|
195
|
+
"[bold red]❌ 错误:[/bold red] 必须提供消息内容,或通过管道传入(例如: [cyan]echo 'hi' | gotify-client send[/cyan])"
|
|
196
|
+
)
|
|
197
|
+
raise typer.Exit(code=1)
|
|
198
|
+
|
|
199
|
+
try:
|
|
200
|
+
notifier = GotifyNotifier(server_url=server, app_token=token)
|
|
201
|
+
effective_title = title if title is not None else notifier.default_title
|
|
202
|
+
effective_priority = priority if priority is not None else notifier.default_priority
|
|
203
|
+
if not quiet and style == "rich":
|
|
204
|
+
with console.status(
|
|
205
|
+
"[bold cyan]📡 正在向 Gotify 服务器发送推送...[/bold cyan]",
|
|
206
|
+
spinner="dots",
|
|
207
|
+
):
|
|
208
|
+
result = notifier.send(
|
|
209
|
+
message=message,
|
|
210
|
+
title=effective_title,
|
|
211
|
+
priority=effective_priority,
|
|
212
|
+
markdown=markdown,
|
|
213
|
+
click_url=url,
|
|
214
|
+
)
|
|
215
|
+
else:
|
|
216
|
+
result = notifier.send(
|
|
217
|
+
message=message,
|
|
218
|
+
title=effective_title,
|
|
219
|
+
priority=effective_priority,
|
|
220
|
+
markdown=markdown,
|
|
221
|
+
click_url=url,
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
if result and not quiet:
|
|
225
|
+
_render_success(
|
|
226
|
+
style,
|
|
227
|
+
effective_title,
|
|
228
|
+
message,
|
|
229
|
+
effective_priority,
|
|
230
|
+
markdown,
|
|
231
|
+
url,
|
|
232
|
+
result,
|
|
233
|
+
)
|
|
234
|
+
except Exception as e:
|
|
235
|
+
_render_error(style, e)
|
|
236
|
+
raise typer.Exit(code=1) from e
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
@app.command("config")
|
|
240
|
+
def cmd_config(
|
|
241
|
+
server_url: str = typer.Option(
|
|
242
|
+
..., "--server", prompt="🌐 请输入 Gotify 服务器地址", help="服务器地址"
|
|
243
|
+
),
|
|
244
|
+
app_token: str = typer.Option(
|
|
245
|
+
...,
|
|
246
|
+
"--token",
|
|
247
|
+
prompt="🔑 请输入 App Token",
|
|
248
|
+
hide_input=True,
|
|
249
|
+
help="应用 Token",
|
|
250
|
+
),
|
|
251
|
+
default_title: str = typer.Option(
|
|
252
|
+
"系统通知", "--title", prompt="📌 默认消息标题", help="默认标题"
|
|
253
|
+
),
|
|
254
|
+
) -> None:
|
|
255
|
+
"""⚙️ 交互式配置并保存默认服务器地址与 Token 到本地。"""
|
|
256
|
+
cfg = dict(load_local_config()) # 保留用户手写的 default_priority 等字段
|
|
257
|
+
cfg.update(
|
|
258
|
+
{
|
|
259
|
+
"server_url": server_url.strip(),
|
|
260
|
+
"app_token": app_token.strip(),
|
|
261
|
+
"default_title": default_title.strip(),
|
|
262
|
+
}
|
|
263
|
+
)
|
|
264
|
+
CONFIG_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
265
|
+
# 先以 600 建临时文件再原子替换,避免 token 在写入过程中被同组用户读到
|
|
266
|
+
tmp_path = CONFIG_FILE_PATH.with_suffix(".json.tmp")
|
|
267
|
+
tmp_path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False), encoding="utf-8")
|
|
268
|
+
os.chmod(tmp_path, 0o600)
|
|
269
|
+
tmp_path.replace(CONFIG_FILE_PATH)
|
|
270
|
+
console.print(
|
|
271
|
+
Panel(
|
|
272
|
+
f"✅ 配置已保存至: [cyan]{CONFIG_FILE_PATH}[/cyan]\n"
|
|
273
|
+
f"🌐 服务器: [green]{cfg['server_url']}[/green]\n"
|
|
274
|
+
f"📌 默认标题: [yellow]{cfg['default_title']}[/yellow]",
|
|
275
|
+
title="[bold green]⚙️ 配置更新成功[/bold green]",
|
|
276
|
+
border_style="green",
|
|
277
|
+
expand=False,
|
|
278
|
+
)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
@app.command("health")
|
|
283
|
+
def cmd_health(
|
|
284
|
+
server: Optional[str] = typer.Option(None, "--server", help="指定 Gotify 服务器地址"),
|
|
285
|
+
token: Optional[str] = typer.Option(None, "--token", help="指定 App Token"),
|
|
286
|
+
) -> None:
|
|
287
|
+
"""🩺 检查 Gotify 服务器连通性与健康状态(/health 不需要 App Token)。"""
|
|
288
|
+
del token # 保留参数只为兼容,健康检查本身不需要鉴权
|
|
289
|
+
try:
|
|
290
|
+
base_url = resolve_base_url(server)
|
|
291
|
+
if not base_url:
|
|
292
|
+
err_console.print(
|
|
293
|
+
"[bold red]❌ 错误:[/bold red] 未配置服务器地址,请传 --server、"
|
|
294
|
+
"设置 GOTIFY_URL 或运行 [cyan]gotify-client config[/cyan]"
|
|
295
|
+
)
|
|
296
|
+
raise typer.Exit(code=1)
|
|
297
|
+
|
|
298
|
+
with console.status(f"[cyan]🔍 正在检测 {base_url} ...[/cyan]", spinner="dots"):
|
|
299
|
+
ok = check_server_health(base_url)
|
|
300
|
+
|
|
301
|
+
if ok:
|
|
302
|
+
console.print(f"🟢 [bold green]服务器在线正常![/bold green] ({base_url})")
|
|
303
|
+
else:
|
|
304
|
+
err_console.print(f"🔴 [bold red]服务器无响应或状态异常![/bold red] ({base_url})")
|
|
305
|
+
raise typer.Exit(code=1)
|
|
306
|
+
except typer.Exit:
|
|
307
|
+
raise
|
|
308
|
+
except Exception as e:
|
|
309
|
+
_render_error("rich", e)
|
|
310
|
+
raise typer.Exit(code=1) from e
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
@app.command("test")
|
|
314
|
+
def cmd_test(
|
|
315
|
+
style: str = typer.Option("rich", "--style", "-s", help="输出风格: rich 或 plain"),
|
|
316
|
+
) -> None:
|
|
317
|
+
"""🧪 发送一条测试推送消息以验证配置是否生效。"""
|
|
318
|
+
cmd_send(
|
|
319
|
+
message="🎉 恭喜!如果你收到这条消息,说明 **gotify-client** CLI 工具已配置成功!",
|
|
320
|
+
title="🧪 测试通知",
|
|
321
|
+
priority=5,
|
|
322
|
+
markdown=True,
|
|
323
|
+
url=None,
|
|
324
|
+
style=style,
|
|
325
|
+
quiet=False,
|
|
326
|
+
server=None,
|
|
327
|
+
token=None,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
@app.callback(invoke_without_command=True)
|
|
332
|
+
def main_callback(
|
|
333
|
+
version: bool = typer.Option(False, "--version", "-v", help="显示当前版本号"),
|
|
334
|
+
) -> None:
|
|
335
|
+
if version:
|
|
336
|
+
console.print(
|
|
337
|
+
f"🚀 [bold cyan]gotify-client[/bold cyan] 版本: [green]v{__version__}[/green]"
|
|
338
|
+
)
|
|
339
|
+
raise typer.Exit()
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
if __name__ == "__main__":
|
|
343
|
+
app()
|
gotify_client/client.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, Optional
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
# 本地持久化配置文件路径(默认存放在用户主目录下)
|
|
10
|
+
CONFIG_FILE_PATH = Path.home() / ".gotify-client.json"
|
|
11
|
+
|
|
12
|
+
# Gotify 官方对 priority 的取值范围约束
|
|
13
|
+
MIN_PRIORITY = 0
|
|
14
|
+
MAX_PRIORITY = 10
|
|
15
|
+
DEFAULT_PRIORITY = 5
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _coerce_priority(value: Any, field: str = "priority") -> int:
|
|
19
|
+
"""把 priority 归一化为 0~10 的整数,非法值抛 ValueError。
|
|
20
|
+
|
|
21
|
+
bool 和浮点一律拒绝(True 会被当成 1、3.7 会被静默截断成 3,都是隐藏 bug);
|
|
22
|
+
数字字符串(配置文件里手写成 "9")则接受。
|
|
23
|
+
"""
|
|
24
|
+
invalid = ValueError(
|
|
25
|
+
f"{field} 必须是 {MIN_PRIORITY}~{MAX_PRIORITY} 之间的整数,收到: {value!r}"
|
|
26
|
+
)
|
|
27
|
+
if isinstance(value, bool) or isinstance(value, float):
|
|
28
|
+
raise invalid
|
|
29
|
+
if isinstance(value, int):
|
|
30
|
+
number = value
|
|
31
|
+
elif isinstance(value, str) and value.strip().lstrip("+-").isdigit():
|
|
32
|
+
number = int(value.strip())
|
|
33
|
+
else:
|
|
34
|
+
raise invalid
|
|
35
|
+
if not MIN_PRIORITY <= number <= MAX_PRIORITY:
|
|
36
|
+
raise invalid
|
|
37
|
+
return number
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def load_local_config() -> Dict[str, Any]:
|
|
41
|
+
"""读取本地持久化配置文件。
|
|
42
|
+
|
|
43
|
+
返回值:
|
|
44
|
+
dict: 配置字典;如果文件不存在、格式解析失败或内容不是 JSON 对象,返回空字典。
|
|
45
|
+
"""
|
|
46
|
+
try:
|
|
47
|
+
data = json.loads(CONFIG_FILE_PATH.read_text(encoding="utf-8"))
|
|
48
|
+
except (OSError, ValueError):
|
|
49
|
+
return {}
|
|
50
|
+
return data if isinstance(data, dict) else {}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class GotifyError(RuntimeError):
|
|
54
|
+
"""Gotify 客户端自身抛出的可预期错误(响应格式异常、重定向等)。"""
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def normalize_base_url(raw_url: str) -> str:
|
|
58
|
+
"""把用户填的地址规范化为 Gotify 根地址(去掉末尾斜杠和误填的 /message)。"""
|
|
59
|
+
clean_url = raw_url.strip().rstrip("/")
|
|
60
|
+
if clean_url.endswith("/message"):
|
|
61
|
+
clean_url = clean_url[: -len("/message")]
|
|
62
|
+
return clean_url
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def resolve_base_url(server_url: Optional[str] = None) -> Optional[str]:
|
|
66
|
+
"""按 显式传参 > 环境变量 > 本地配置文件 的顺序解析服务器地址。"""
|
|
67
|
+
raw_url = server_url or os.getenv("GOTIFY_URL") or load_local_config().get("server_url", "")
|
|
68
|
+
return normalize_base_url(raw_url) if raw_url else None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def check_server_health(base_url: str, timeout: int = 10) -> bool:
|
|
72
|
+
"""检查 Gotify 服务器是否在线。
|
|
73
|
+
|
|
74
|
+
/health 不需要鉴权,因此这里不构造带 token 的客户端。
|
|
75
|
+
只有返回 200 且响应体是 Gotify 的 JSON(含 health 字段)才算健康,
|
|
76
|
+
避免把任意一个返回 200 的 Web 服务器误判为 Gotify。
|
|
77
|
+
"""
|
|
78
|
+
try:
|
|
79
|
+
resp = requests.get(f"{base_url.rstrip('/')}/health", timeout=timeout)
|
|
80
|
+
except requests.exceptions.RequestException:
|
|
81
|
+
return False
|
|
82
|
+
if resp.status_code != 200:
|
|
83
|
+
return False
|
|
84
|
+
try:
|
|
85
|
+
body = resp.json()
|
|
86
|
+
except ValueError:
|
|
87
|
+
return False
|
|
88
|
+
return isinstance(body, dict) and "health" in body
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class GotifyNotifier:
|
|
92
|
+
"""Gotify 消息推送客户端类。
|
|
93
|
+
|
|
94
|
+
配置加载优先级:
|
|
95
|
+
1. 初始化时显式传入的参数 (server_url / app_token)
|
|
96
|
+
2. 系统环境变量 (GOTIFY_URL / GOTIFY_TOKEN)
|
|
97
|
+
3. 本地配置文件 (~/.gotify-client.json)
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
def __init__(
|
|
101
|
+
self,
|
|
102
|
+
server_url: Optional[str] = None,
|
|
103
|
+
app_token: Optional[str] = None,
|
|
104
|
+
default_title: Optional[str] = None,
|
|
105
|
+
default_priority: Optional[int] = None,
|
|
106
|
+
timeout: int = 10,
|
|
107
|
+
ignore_errors: bool = False,
|
|
108
|
+
) -> None:
|
|
109
|
+
"""初始化 Gotify 推送客户端。
|
|
110
|
+
|
|
111
|
+
参数说明:
|
|
112
|
+
server_url (str, optional): Gotify 服务器地址(如 "https://example.com")。
|
|
113
|
+
app_token (str, optional): Gotify 应用的 App Token。
|
|
114
|
+
default_title (str, optional): 默认消息标题,默认为 "系统通知"。
|
|
115
|
+
default_priority (int, optional): 默认消息优先级(0~10),默认为 5。
|
|
116
|
+
timeout (int): HTTP 请求超时时间(秒),默认为 10 秒。
|
|
117
|
+
ignore_errors (bool): 是否默认忽略推送异常,默认为 False。
|
|
118
|
+
设为 True 时,网络异常或推送失败仅打印错误提示,不会抛出异常中断主程序。
|
|
119
|
+
|
|
120
|
+
异常说明:
|
|
121
|
+
ValueError: 当服务器地址或 App Token 均未提供且环境变量与本地配置也未设置时抛出。
|
|
122
|
+
"""
|
|
123
|
+
local_cfg = load_local_config()
|
|
124
|
+
|
|
125
|
+
raw_url = server_url or os.getenv("GOTIFY_URL") or local_cfg.get("server_url", "")
|
|
126
|
+
token = app_token or os.getenv("GOTIFY_TOKEN") or local_cfg.get("app_token", "")
|
|
127
|
+
|
|
128
|
+
if not raw_url:
|
|
129
|
+
raise ValueError(
|
|
130
|
+
"未找到服务器地址:请传参、设置环境变量 GOTIFY_URL 或运行 `gotify-client config` 配置"
|
|
131
|
+
)
|
|
132
|
+
if not token:
|
|
133
|
+
raise ValueError(
|
|
134
|
+
"未找到 App Token:请传参、设置环境变量 GOTIFY_TOKEN 或运行 `gotify-client config` 配置"
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
# 规范化 URL:去除末尾斜杠,提取基础域名并拼接 /message 接口
|
|
138
|
+
self.base_url = normalize_base_url(raw_url)
|
|
139
|
+
self.api_url = f"{self.base_url}/message"
|
|
140
|
+
|
|
141
|
+
self.app_token = token
|
|
142
|
+
self.default_title = default_title or local_cfg.get("default_title") or "系统通知"
|
|
143
|
+
raw_priority = (
|
|
144
|
+
default_priority
|
|
145
|
+
if default_priority is not None
|
|
146
|
+
else local_cfg.get("default_priority", DEFAULT_PRIORITY)
|
|
147
|
+
)
|
|
148
|
+
# 配置文件的优先级不可信,非法时静默回落到默认值而不是直接崩溃
|
|
149
|
+
try:
|
|
150
|
+
self.default_priority = _coerce_priority(raw_priority, "default_priority")
|
|
151
|
+
except ValueError:
|
|
152
|
+
self.default_priority = DEFAULT_PRIORITY
|
|
153
|
+
self.timeout = timeout
|
|
154
|
+
self.ignore_errors = ignore_errors
|
|
155
|
+
|
|
156
|
+
# 初始化持久化 Session,复用底层 TCP 连接并预置鉴权请求头
|
|
157
|
+
self.session = requests.Session()
|
|
158
|
+
self.session.headers.update(
|
|
159
|
+
{
|
|
160
|
+
"X-Gotify-Key": self.app_token,
|
|
161
|
+
"Content-Type": "application/json",
|
|
162
|
+
}
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def send(
|
|
166
|
+
self,
|
|
167
|
+
message: str,
|
|
168
|
+
title: Optional[str] = None,
|
|
169
|
+
priority: Optional[int] = None,
|
|
170
|
+
markdown: bool = False,
|
|
171
|
+
click_url: Optional[str] = None,
|
|
172
|
+
ignore_errors: Optional[bool] = None,
|
|
173
|
+
) -> Optional[Dict[str, Any]]:
|
|
174
|
+
"""向 Gotify 服务器发送一条推送消息。
|
|
175
|
+
|
|
176
|
+
参数说明:
|
|
177
|
+
message (str): 【必填】推送的消息正文内容。
|
|
178
|
+
title (str, optional): 消息标题,未传则使用初始化时的 default_title。
|
|
179
|
+
priority (int, optional): 消息优先级(0~10),未传则使用 default_priority。
|
|
180
|
+
markdown (bool): 是否开启 Markdown 格式渲染,默认为 False。
|
|
181
|
+
click_url (str, optional): 点击通知卡片后在浏览器中打开的跳转链接。
|
|
182
|
+
ignore_errors (bool, optional): 临时覆盖初始化时的 ignore_errors 设置。
|
|
183
|
+
|
|
184
|
+
返回值:
|
|
185
|
+
dict | None: 推送成功返回服务器响应的 JSON 字典;
|
|
186
|
+
若开启 ignore_errors 且推送失败,则返回 None。
|
|
187
|
+
"""
|
|
188
|
+
should_ignore = self.ignore_errors if ignore_errors is None else ignore_errors
|
|
189
|
+
|
|
190
|
+
if not message or not message.strip():
|
|
191
|
+
if should_ignore:
|
|
192
|
+
print("[Gotify 警告] 推送内容为空,已跳过发送。", file=sys.stderr)
|
|
193
|
+
return None
|
|
194
|
+
raise ValueError("推送内容 (message) 不能为空")
|
|
195
|
+
|
|
196
|
+
effective_priority = _coerce_priority(
|
|
197
|
+
priority if priority is not None else self.default_priority
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
payload: Dict[str, Any] = {
|
|
201
|
+
"title": title if title is not None else self.default_title,
|
|
202
|
+
"message": message,
|
|
203
|
+
"priority": effective_priority,
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
# 组装客户端扩展字段
|
|
207
|
+
extras: Dict[str, Any] = {}
|
|
208
|
+
if markdown:
|
|
209
|
+
extras["client::display"] = {"contentType": "text/markdown"}
|
|
210
|
+
if click_url:
|
|
211
|
+
extras["client::notification"] = {"click": {"url": click_url}}
|
|
212
|
+
|
|
213
|
+
if extras:
|
|
214
|
+
payload["extras"] = extras
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
response = self.session.post(
|
|
218
|
+
url=self.api_url,
|
|
219
|
+
json=payload,
|
|
220
|
+
timeout=self.timeout,
|
|
221
|
+
# 禁止跟随重定向:requests 会把 X-Gotify-Key 一并带到新的 Host
|
|
222
|
+
allow_redirects=False,
|
|
223
|
+
)
|
|
224
|
+
if response.is_redirect:
|
|
225
|
+
raise GotifyError(
|
|
226
|
+
f"服务器返回了重定向(HTTP {response.status_code} -> "
|
|
227
|
+
f"{response.headers.get('Location')!r});请把 GOTIFY_URL 直接指向 "
|
|
228
|
+
"Gotify 的真实地址,例如 https://gotify.example.com"
|
|
229
|
+
)
|
|
230
|
+
response.raise_for_status()
|
|
231
|
+
try:
|
|
232
|
+
return response.json()
|
|
233
|
+
except ValueError:
|
|
234
|
+
raise GotifyError(
|
|
235
|
+
f"服务器返回了非 JSON 响应(HTTP {response.status_code}): "
|
|
236
|
+
f"{response.text[:200]!r};请确认 {self.base_url} 是 Gotify 服务地址"
|
|
237
|
+
) from None
|
|
238
|
+
except (requests.exceptions.RequestException, GotifyError) as e:
|
|
239
|
+
if should_ignore:
|
|
240
|
+
print(f"[Gotify 推送失败] {e}", file=sys.stderr)
|
|
241
|
+
return None
|
|
242
|
+
raise
|
|
243
|
+
|
|
244
|
+
def check_health(self) -> bool:
|
|
245
|
+
"""检查 Gotify 服务器连通性与健康状态。
|
|
246
|
+
|
|
247
|
+
返回值:
|
|
248
|
+
bool: 服务器返回 200 且响应体是 Gotify 的 health JSON 时为 True。
|
|
249
|
+
"""
|
|
250
|
+
return check_server_health(self.base_url, self.timeout)
|
|
251
|
+
|
|
252
|
+
def close(self) -> None:
|
|
253
|
+
"""释放底层连接池。"""
|
|
254
|
+
self.session.close()
|
|
255
|
+
|
|
256
|
+
def __enter__(self) -> "GotifyNotifier":
|
|
257
|
+
return self
|
|
258
|
+
|
|
259
|
+
def __exit__(self, *exc_info: Any) -> None:
|
|
260
|
+
self.close()
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: gotify-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: 轻量级 Gotify 消息推送 Python 客户端与命令行工具
|
|
5
|
+
Keywords: gotify,push,notification,cli,webhook
|
|
6
|
+
Author: EzraX21
|
|
7
|
+
Author-email: EzraX21 <xjr119911@gmail.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Intended Audience :: System Administrators
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: System :: Monitoring
|
|
21
|
+
Classifier: Topic :: Utilities
|
|
22
|
+
Classifier: Typing :: Typed
|
|
23
|
+
Requires-Dist: requests>=2.25.0
|
|
24
|
+
Requires-Dist: rich>=13.0.0
|
|
25
|
+
Requires-Dist: typer>=0.12.0
|
|
26
|
+
Requires-Dist: pytest>=8.0.0 ; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest-cov>=5.0.0 ; extra == 'dev'
|
|
28
|
+
Requires-Dist: ruff>=0.6.0 ; extra == 'dev'
|
|
29
|
+
Requires-Dist: pre-commit>=3.7.0 ; extra == 'dev'
|
|
30
|
+
Requires-Python: >=3.10
|
|
31
|
+
Project-URL: Homepage, https://github.com/EzraX21/gotify-client
|
|
32
|
+
Project-URL: Repository, https://github.com/EzraX21/gotify-client
|
|
33
|
+
Project-URL: Issues, https://github.com/EzraX21/gotify-client/issues
|
|
34
|
+
Project-URL: Changelog, https://github.com/EzraX21/gotify-client/blob/main/CHANGELOG.md
|
|
35
|
+
Provides-Extra: dev
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
# 🚀 gotify-client
|
|
39
|
+
|
|
40
|
+
轻量级 **Gotify** 消息推送 Python 客户端与多子命令 CLI 工具。支持全局快捷推送、多实例面向对象调用、交互式本地配置、环境变量读取、Markdown 格式渲染、点击跳转链接、管道输入(`stdin`)、静默模式以及双终端输出风格(`rich` 精美卡片 / `plain` 原生彩色)。
|
|
41
|
+
|
|
42
|
+
## 📁 项目结构
|
|
43
|
+
|
|
44
|
+
```text
|
|
45
|
+
gotify-client/
|
|
46
|
+
├── pyproject.toml # uv 项目与构建配置
|
|
47
|
+
├── uv.lock # 锁定的依赖版本
|
|
48
|
+
├── README.md # 说明文档
|
|
49
|
+
├── CHANGELOG.md # 版本变更记录
|
|
50
|
+
├── LICENSE # MIT
|
|
51
|
+
├── .pre-commit-config.yaml # 提交前自动 lint/格式化
|
|
52
|
+
├── .github/workflows/ci.yml # GitHub Actions:多版本测试 + ruff + 构建
|
|
53
|
+
├── tests/ # pytest 测试(91 个用例,覆盖率 ~91%)
|
|
54
|
+
└── src/
|
|
55
|
+
└── gotify_client/ # 核心包目录
|
|
56
|
+
├── __init__.py # 包初始化与快捷方法
|
|
57
|
+
├── __main__.py # 支持 python -m gotify_client
|
|
58
|
+
├── client.py # GotifyNotifier 核心实现与本地配置加载
|
|
59
|
+
└── cli.py # 基于 Typer 的多子命令 CLI 入口
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
---
|
|
63
|
+
|
|
64
|
+
## 📦 安装方式
|
|
65
|
+
|
|
66
|
+
### 1. 使用 `uv` 安装(推荐)
|
|
67
|
+
```bash
|
|
68
|
+
# 同步虚拟环境(自动安装 requests、rich、typer)
|
|
69
|
+
uv sync
|
|
70
|
+
|
|
71
|
+
# 或作为全局命令行工具安装到系统任意位置
|
|
72
|
+
uv tool install .
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 2. 使用 `pip` 安装
|
|
76
|
+
```bash
|
|
77
|
+
# 本地开发模式安装
|
|
78
|
+
pip install -e .
|
|
79
|
+
|
|
80
|
+
# 或打包后安装生成的 wheel 文件
|
|
81
|
+
uv build
|
|
82
|
+
pip install dist/gotify_client-0.1.0-py3-none-any.whl
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
### 3. 开发与测试
|
|
86
|
+
```bash
|
|
87
|
+
uv sync --all-extras # 安装含 pytest / ruff 的开发依赖
|
|
88
|
+
uv run pytest -q # 跑测试
|
|
89
|
+
uv run ruff check src tests # 静态检查
|
|
90
|
+
uv run ruff format src tests # 格式化
|
|
91
|
+
|
|
92
|
+
# 可选:装上 pre-commit 钩子,提交前自动检查
|
|
93
|
+
uv run pre-commit install
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
> 安装后也可以 `python -m gotify_client` 代替 `gotify-client`,适合在受限环境里调用。
|
|
97
|
+
|
|
98
|
+
---
|
|
99
|
+
|
|
100
|
+
## ⚙️ 配置方式
|
|
101
|
+
|
|
102
|
+
配置加载优先级:**代码显式传参 > 系统环境变量 > 本地配置文件 (`~/.gotify-client.json`)**。
|
|
103
|
+
|
|
104
|
+
### 方式一:CLI 交互式配置(最省心,推荐)
|
|
105
|
+
运行一次初始化命令,按提示输入服务器地址和 App Token(输入时自动隐藏),配置将持久化保存在 `~/.gotify-client.json`:
|
|
106
|
+
```bash
|
|
107
|
+
gotify-client config
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
### 方式二:环境变量配置
|
|
111
|
+
```bash
|
|
112
|
+
export GOTIFY_URL="https://example.com"
|
|
113
|
+
export GOTIFY_TOKEN="A1b2C3d4E5f6G7h"
|
|
114
|
+
export GOTIFY_STYLE="rich" # 可选:rich(默认卡片风格)或 plain(紧凑原生彩色)
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
> **提示**:传入 `server_url` 时只需填写基础域名(如 `https://example.com`),程序会自动补全 `/message` 接口路径。
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 🖥️ 命令行工具 (`gotify-client`)
|
|
122
|
+
|
|
123
|
+
### 1. 常用子命令一览
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
# 查看彩色帮助菜单与版本
|
|
127
|
+
gotify-client --help
|
|
128
|
+
gotify-client --version
|
|
129
|
+
|
|
130
|
+
# ⚙️ 交互式保存服务器地址与 Token 到本地
|
|
131
|
+
gotify-client config
|
|
132
|
+
|
|
133
|
+
# 🧪 发送一条测试通知,验证手机/客户端是否正常接收
|
|
134
|
+
gotify-client test
|
|
135
|
+
|
|
136
|
+
# 🩺 检查 Gotify 服务器在线健康状态(不需要 App Token)
|
|
137
|
+
gotify-client health
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
> `health` 只请求 `/health`,该接口本身不需要鉴权,因此没配 token 也能用。
|
|
141
|
+
> 判定标准是「HTTP 200 且响应体是 Gotify 的 health JSON」,不会把任意 Web 服务器误判为在线。
|
|
142
|
+
|
|
143
|
+
### 2. 发送推送 (`gotify-client send`)
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
# 最简调用(自动读取本地配置或环境变量)
|
|
147
|
+
gotify-client send "备份任务已顺利完成"
|
|
148
|
+
|
|
149
|
+
# 完整参数调用(标题、高优先级、Markdown、点击跳转链接)
|
|
150
|
+
gotify-client send "**警告**:磁盘剩余空间不足 10%" \
|
|
151
|
+
-t "服务器监控" \
|
|
152
|
+
-p 9 \
|
|
153
|
+
-m \
|
|
154
|
+
-u "https://example.com"
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### 3. 双输出风格切换与效果预览
|
|
158
|
+
|
|
159
|
+
* **`--style rich`(默认圆角卡片风格)**:
|
|
160
|
+
```text
|
|
161
|
+
╭──────────── 🚀 Gotify 推送成功 ────────────╮
|
|
162
|
+
│ 🆔 消息 ID: #42 │
|
|
163
|
+
│ 📌 标题: 服务器监控 │
|
|
164
|
+
│ ⚡ 优先级: 🔴 9 (紧急/强提醒) │
|
|
165
|
+
│ 🎨 格式: 📝 Markdown │
|
|
166
|
+
│ 🚨 正文内容: **警告**:磁盘剩余不足 10% │
|
|
167
|
+
╰────────────────────────────────────────────╯
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
* **`--style plain`(紧凑原生彩色风格)**:
|
|
171
|
+
```text
|
|
172
|
+
🚀 推送成功 (🆔 #42)
|
|
173
|
+
──────────────────────────────────────────
|
|
174
|
+
📌 标题 : 服务器监控
|
|
175
|
+
⚡ 等级 : 🔴 9 (紧急)
|
|
176
|
+
🎨 格式 : 📝 Markdown
|
|
177
|
+
🚨 内容 : **警告**:磁盘剩余不足 10%
|
|
178
|
+
──────────────────────────────────────────
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
### 4. 管道输入 (`stdin`) 与静默模式 (`-q`)
|
|
182
|
+
|
|
183
|
+
```bash
|
|
184
|
+
# 管道输入:直接推送系统命令输出或日志内容
|
|
185
|
+
df -h | gotify-client send -t "磁盘空间报告" -p 4
|
|
186
|
+
tail -n 20 /var/log/nginx/error.log | gotify-client send -t "Nginx 异常日志" -p 8
|
|
187
|
+
|
|
188
|
+
# 静默模式(适合 Crontab 定时任务):成功时零输出,仅失败时输出错误到 stderr
|
|
189
|
+
0 2 * * * /usr/local/bin/backup.sh && gotify-client send "每日备份完成" -q
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## 🐍 Python 代码调用
|
|
195
|
+
|
|
196
|
+
### 1. 全局快捷模式(推荐在多文件项目中使用)
|
|
197
|
+
|
|
198
|
+
```python
|
|
199
|
+
import gotify_client
|
|
200
|
+
|
|
201
|
+
# 1. 初始化全局配置(若已配置本地文件 ~/.gotify-client.json 或环境变量,可跳过此步)
|
|
202
|
+
gotify_client.init(
|
|
203
|
+
server_url="https://example.com",
|
|
204
|
+
app_token="A1b2C3d4E5f6G7h",
|
|
205
|
+
default_title="业务系统",
|
|
206
|
+
ignore_errors=True, # 开启安静模式:网络异常仅打印提示,不抛出异常中断主程序
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
# 2. 发送普通文本消息
|
|
210
|
+
gotify_client.send("每日数据同步任务已完成!")
|
|
211
|
+
|
|
212
|
+
# 3. 发送 Markdown 格式与高优先级告警
|
|
213
|
+
gotify_client.send(
|
|
214
|
+
message="### 服务器负载告警\n- **CPU**: `96%`\n- **状态**: 持续 5 分钟超载",
|
|
215
|
+
title="紧急告警",
|
|
216
|
+
priority=9,
|
|
217
|
+
markdown=True,
|
|
218
|
+
click_url="https://example.com",
|
|
219
|
+
)
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
### 2. 实例化客户端模式(适合多应用 / 多服务器场景)
|
|
223
|
+
|
|
224
|
+
```python
|
|
225
|
+
from gotify_client import GotifyNotifier
|
|
226
|
+
|
|
227
|
+
notifier = GotifyNotifier(
|
|
228
|
+
server_url="https://example.com",
|
|
229
|
+
app_token="A1b2C3d4E5f6G7h",
|
|
230
|
+
default_title="爬虫监控",
|
|
231
|
+
default_priority=5,
|
|
232
|
+
timeout=10,
|
|
233
|
+
ignore_errors=False,
|
|
234
|
+
)
|
|
235
|
+
|
|
236
|
+
if notifier.check_health():
|
|
237
|
+
notifier.send("服务连通正常,开始执行抓取任务。")
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
---
|
|
241
|
+
|
|
242
|
+
## 📋 参数说明
|
|
243
|
+
|
|
244
|
+
### Python 初始化参数 (`GotifyNotifier` / `init`)
|
|
245
|
+
|
|
246
|
+
| 参数名 | 类型 | 默认值 | 说明 |
|
|
247
|
+
| :--- | :--- | :--- | :--- |
|
|
248
|
+
| `server_url` | `str` | 读环境变量 / 本地配置 | Gotify 服务器地址(如 `https://example.com`) |
|
|
249
|
+
| `app_token` | `str` | 读环境变量 / 本地配置 | Gotify 后台创建应用获取的 App Token |
|
|
250
|
+
| `default_title` | `str` | `"系统通知"` | 默认消息标题 |
|
|
251
|
+
| `default_priority` | `int` | `5` | 默认消息优先级(范围 `0`~`10`) |
|
|
252
|
+
| `timeout` | `int` | `10` | HTTP 请求超时时间(秒) |
|
|
253
|
+
| `ignore_errors` | `bool` | `False` | 设为 `True` 时,网络异常或推送失败仅打印错误,不抛出异常 |
|
|
254
|
+
|
|
255
|
+
### `gotify-client send` 命令行参数
|
|
256
|
+
|
|
257
|
+
| 参数 | 简写 | 默认值 | 说明 |
|
|
258
|
+
| :--- | :--- | :--- | :--- |
|
|
259
|
+
| `message` | - | 必填(或走管道) | 推送的消息正文,未传时自动读取标准输入管道 (`stdin`) |
|
|
260
|
+
| `--title` | `-t` | 读本地配置 / `"系统通知"` | 消息标题 |
|
|
261
|
+
| `--priority` | `-p` | 读本地配置 / `5` | 优先级(`0`~`10`):`0` 静默,`1-3` 低,`4-7` 普通,`8-10` 强提醒 |
|
|
262
|
+
| `--markdown` | `-m` | `False` | 启用 Markdown 格式渲染 |
|
|
263
|
+
| `--url` | `-u` | `None` | 点击通知跳转的网页链接 |
|
|
264
|
+
| `--style` | `-s` | `"rich"` | 终端输出风格:可选 `rich`(卡片)或 `plain`(原生彩色) |
|
|
265
|
+
| `--quiet` | `-q` | `False` | 静默模式:成功时不输出内容,仅出错时输出到 `stderr` |
|
|
266
|
+
| `--server` | - | 环境变量 / 本地配置 | 临时覆盖 Gotify 服务器地址 |
|
|
267
|
+
| `--token` | - | 环境变量 / 本地配置 | 临时覆盖 App Token |
|
|
268
|
+
|
|
269
|
+
---
|
|
270
|
+
|
|
271
|
+
## 🔒 安全说明
|
|
272
|
+
|
|
273
|
+
- **App Token 存在 `~/.gotify-client.json`,文件权限强制为 `0600`**(写入时先建 600 临时文件再原子替换)。
|
|
274
|
+
该 token 等价于对应 Gotify 应用的发送权限,请勿提交到仓库或贴进日志。
|
|
275
|
+
- **不跟随 HTTP 重定向。** 客户端把 `X-Gotify-Key` 放在 Session 默认请求头里,
|
|
276
|
+
而 `requests` 默认会带着自定义头跨主机跟随 3xx,等于把 token 送给重定向目标。
|
|
277
|
+
因此 `send` 显式 `allow_redirects=False`,遇到 3xx 直接报错并提示把地址指向 Gotify 真实地址。
|
|
278
|
+
如果你的服务器是 `http://` 被反代 301 到 `https://`,请直接把 `GOTIFY_URL` 写成 https 地址。
|
|
279
|
+
- **终端输出对消息内容做了 markup 转义。** 推送正文/标题里出现 `[/]`、`[bold]`、`[link=...]`
|
|
280
|
+
之类的 rich 标签时按普通文本显示,既不会崩,也不会被用来伪造终端里的告警样式。
|
|
281
|
+
- **优先级严格校验。** `priority` 必须是 `0`~`10` 的整数,`True`、`3.7`、`99` 都会被拒绝,
|
|
282
|
+
配置文件里的非法值会静默回落到 `5`。
|
|
283
|
+
|
|
284
|
+
---
|
|
285
|
+
|
|
286
|
+
## 🧪 测试
|
|
287
|
+
|
|
288
|
+
```bash
|
|
289
|
+
uv sync --all-extras
|
|
290
|
+
uv run pytest -q --cov=gotify_client
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
测试用 `http.server` 起一个本地假 Gotify,覆盖 payload 组装、URL 规范化、priority 校验、
|
|
294
|
+
markup 转义、重定向不泄漏 token、配置文件权限、GBK 终端等回归点,不依赖外网。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
gotify_client/__init__.py,sha256=xg_8Z30Nkv6zoKWnmiK4_xiBTD-fWHzL3fuJfnlKiHw,1253
|
|
2
|
+
gotify_client/__main__.py,sha256=sqbk9lJwtSBWMwpE6S_c9TZEhAlTlCCOF7SKOSMJbuk,109
|
|
3
|
+
gotify_client/cli.py,sha256=Womvvzfrkphy9NwDWaVeWcFwtPxogrFjTkb2w3nUXEQ,12303
|
|
4
|
+
gotify_client/client.py,sha256=zwP21qlNi65dEbcIr7DX2WKb6DWC89w7NTHjTRcKyaY,10184
|
|
5
|
+
gotify_client-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
|
|
6
|
+
gotify_client-0.1.0.dist-info/entry_points.txt,sha256=o_29JYQPj4_I7HPSi7hsljYB4TrGGQf79NPflH0ifls,57
|
|
7
|
+
gotify_client-0.1.0.dist-info/METADATA,sha256=0dJwTfUMkJRGS4dPklfrp5XzlIcjt-hjJ0qVxW_ikmY,11456
|
|
8
|
+
gotify_client-0.1.0.dist-info/RECORD,,
|