-
Notifications
You must be signed in to change notification settings - Fork 2
/
gotify-read.py
executable file
·77 lines (64 loc) · 1.93 KB
/
gotify-read.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python3
# SPDX-License-Identifier: WTFPL
# /// script
# dependencies = ["requests"]
# ///
import argparse
import json
import os
import re
from urllib.parse import urljoin
import requests
# parser
parser = argparse.ArgumentParser(
description="Read Gotify notifications and output in JSON",
)
parser.add_argument("--url", help="URL of Gotify server")
parser.add_argument("--limit", type=int, help="Limit the number of retrieved messages")
parser.add_argument("--after", type=int, help="Display messages after this id only")
parser.add_argument("--appid", type=int, dest="app_id", help="Gotify app (reader) ID")
parser.add_argument("--pretty", action="store_true", help="Display in human format instead of JSON")
args = parser.parse_args()
if not args.url:
parser.error("missing --url param")
# session
session = requests.Session()
session.headers["X-Gotify-Key"] = os.environ["GOTIFY_TOKEN"]
# url
route = "message"
if args.app_id:
route = f"application/{args.app_id}/message"
full_url = urljoin(args.url, route)
# request
response = session.get(full_url)
response.raise_for_status()
# paging loop
messages = []
while True:
jdata = response.json()
messages.extend(jdata["messages"])
if args.limit and len(messages) >= args.limit:
messages = messages[:args.limit]
break
if args.after and messages and messages[-1]["id"] <= args.after:
messages = [
msg for msg in messages
if msg["id"] > args.after
]
break
if not jdata["paging"].get("next"):
break
response = session.get(full_url, params={"since": jdata["paging"]["since"]})
response.raise_for_status()
if not args.pretty:
print(json.dumps(messages, indent=2))
else:
for msg in messages:
print(f"""+----------\n| {msg["title"]}\n+----------""")
print(re.sub(r"^", "| ", msg["message"], flags=re.M))
if msg.get("extras"):
print("+----------")
for k, sub in msg["extras"].items():
for subk, v in sub.items():
print(f"| {k} {subk} = {v}")
print()