zulip-nod 0.1.0__tar.gz

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.
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: zulip-nod
3
+ Version: 0.1.0
4
+ Summary: Small non-interactive JSON CLI for Zulip
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: zulip==0.9.1
8
+
9
+ # zulip-nod
10
+
11
+ A small, non-interactive Zulip CLI using the official Python `zulip` client.
12
+ Requires Python 3.10 or newer. No Node.js or terminal UI is required.
13
+
14
+ ## Install and configure
15
+
16
+ Install the wheel with `python -m pip install ./zulip_nod-0.1.0-py3-none-any.whl`.
17
+ For Nod, supply these variables in private setup, not as CLI arguments:
18
+
19
+ - `ZULIP_URL`: your Zulip HTTPS origin, with no path or credentials.
20
+ - `ZULIP_EMAIL`: the user or bot's Zulip API email.
21
+ - `ZULIP_API_KEY`: the account's Zulip API key.
22
+
23
+ This CLI ignores `~/.zuliprc`, proxy settings and TLS override variables. It
24
+ verifies TLS, does not follow redirects, and disables SDK retries. The SDK fetches
25
+ server settings before the requested operation. No other commands mutate Zulip.
26
+
27
+ ## Usage
28
+
29
+ ```sh
30
+ zulip profile
31
+ zulip read --limit 10
32
+ zulip read --channel engineering --topic planning --limit 10
33
+ zulip search 'quarterly budget' --channel finance --limit 10
34
+ zulip send --channel-id 42 --topic planning < message.txt
35
+ zulip send --user-id 12 --user-id 34 < message.txt
36
+ ```
37
+
38
+ Reads and searches default to 20 messages and accept a limit of 1 to 100, with
39
+ no auto-pagination or mark-as-read calls. Search follows Zulip's own permissions
40
+ and history rules. `send` requires an explicit destination and a UTF-8 message
41
+ on stdin. It does not prompt. Use the same `--user-id` flag again for a group DM.
42
+ If a send reports an unknown outcome, check Zulip before retrying.
43
+
44
+ Commands write one JSON object to stdout. Exit codes: `0` success, `2` invalid
45
+ input or missing configuration, `1` request failure or unknown send outcome.
46
+ `--help` and `--version` are plain text and work offline. Successful profile and
47
+ message output contains private account data; treat it accordingly.
48
+
49
+ ## Package and upload
50
+
51
+ From the source tree, run `python -m pip install build twine` and then
52
+ `python -m build` to build both distributions. To publish the supplied files
53
+ without rebuilding, put only those two files in a clean `dist/` directory, review
54
+ them, and run:
55
+
56
+ ```sh
57
+ python -m twine check dist/zulip_nod-0.1.0*
58
+ python -m twine upload dist/zulip_nod-0.1.0*
59
+ ```
60
+
61
+ Use your own PyPI account and enter an upload token privately if prompted. Do
62
+ not put the token in the command line or send it in chat. The upload is public.
63
+
64
+ ## Offline tests
65
+
66
+ After installing the wheel, run `python -m unittest discover -s tests -v` from
67
+ an extracted source distribution. The tests exercise the installed package and
68
+ stub the HTTP adapter; no Zulip server or real credentials are used.
@@ -0,0 +1,60 @@
1
+ # zulip-nod
2
+
3
+ A small, non-interactive Zulip CLI using the official Python `zulip` client.
4
+ Requires Python 3.10 or newer. No Node.js or terminal UI is required.
5
+
6
+ ## Install and configure
7
+
8
+ Install the wheel with `python -m pip install ./zulip_nod-0.1.0-py3-none-any.whl`.
9
+ For Nod, supply these variables in private setup, not as CLI arguments:
10
+
11
+ - `ZULIP_URL`: your Zulip HTTPS origin, with no path or credentials.
12
+ - `ZULIP_EMAIL`: the user or bot's Zulip API email.
13
+ - `ZULIP_API_KEY`: the account's Zulip API key.
14
+
15
+ This CLI ignores `~/.zuliprc`, proxy settings and TLS override variables. It
16
+ verifies TLS, does not follow redirects, and disables SDK retries. The SDK fetches
17
+ server settings before the requested operation. No other commands mutate Zulip.
18
+
19
+ ## Usage
20
+
21
+ ```sh
22
+ zulip profile
23
+ zulip read --limit 10
24
+ zulip read --channel engineering --topic planning --limit 10
25
+ zulip search 'quarterly budget' --channel finance --limit 10
26
+ zulip send --channel-id 42 --topic planning < message.txt
27
+ zulip send --user-id 12 --user-id 34 < message.txt
28
+ ```
29
+
30
+ Reads and searches default to 20 messages and accept a limit of 1 to 100, with
31
+ no auto-pagination or mark-as-read calls. Search follows Zulip's own permissions
32
+ and history rules. `send` requires an explicit destination and a UTF-8 message
33
+ on stdin. It does not prompt. Use the same `--user-id` flag again for a group DM.
34
+ If a send reports an unknown outcome, check Zulip before retrying.
35
+
36
+ Commands write one JSON object to stdout. Exit codes: `0` success, `2` invalid
37
+ input or missing configuration, `1` request failure or unknown send outcome.
38
+ `--help` and `--version` are plain text and work offline. Successful profile and
39
+ message output contains private account data; treat it accordingly.
40
+
41
+ ## Package and upload
42
+
43
+ From the source tree, run `python -m pip install build twine` and then
44
+ `python -m build` to build both distributions. To publish the supplied files
45
+ without rebuilding, put only those two files in a clean `dist/` directory, review
46
+ them, and run:
47
+
48
+ ```sh
49
+ python -m twine check dist/zulip_nod-0.1.0*
50
+ python -m twine upload dist/zulip_nod-0.1.0*
51
+ ```
52
+
53
+ Use your own PyPI account and enter an upload token privately if prompted. Do
54
+ not put the token in the command line or send it in chat. The upload is public.
55
+
56
+ ## Offline tests
57
+
58
+ After installing the wheel, run `python -m unittest discover -s tests -v` from
59
+ an extracted source distribution. The tests exercise the installed package and
60
+ stub the HTTP adapter; no Zulip server or real credentials are used.
@@ -0,0 +1,17 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zulip-nod"
7
+ version = "0.1.0"
8
+ description = "Small non-interactive JSON CLI for Zulip"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = ["zulip==0.9.1"]
12
+
13
+ [project.scripts]
14
+ zulip = "zulip_nod.cli:main"
15
+
16
+ [tool.setuptools.packages.find]
17
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,186 @@
1
+ """Single-command JSON interface around the official Zulip client."""
2
+ import argparse
3
+ import json
4
+ import logging
5
+ import os
6
+ import sys
7
+ from urllib.parse import urlsplit
8
+
9
+
10
+ class InputError(Exception):
11
+ pass
12
+
13
+
14
+ class Parser(argparse.ArgumentParser):
15
+ def error(self, message):
16
+ # argparse diagnostics can contain arbitrary unrecognized arguments.
17
+ raise InputError("Invalid arguments. Run zulip --help for usage.")
18
+
19
+
20
+ def nonblank(value):
21
+ if not value.strip():
22
+ raise argparse.ArgumentTypeError("Expected nonblank text")
23
+ return value
24
+
25
+
26
+ def positive(value):
27
+ number = int(value)
28
+ if number < 1:
29
+ raise argparse.ArgumentTypeError("Expected a positive integer")
30
+ return number
31
+
32
+
33
+ def parser():
34
+ root = Parser(prog="zulip", allow_abbrev=False, description="Non-interactive Zulip JSON CLI")
35
+ root.add_argument("--version", action="version", version="%(prog)s 0.1.0")
36
+ sub = root.add_subparsers(dest="command", required=True)
37
+ sub.add_parser("profile", help="Read the authenticated profile", allow_abbrev=False)
38
+ for name in ("read", "search"):
39
+ command = sub.add_parser(name, help=f"{name.title()} recent messages", allow_abbrev=False)
40
+ if name == "search":
41
+ command.add_argument("query", type=nonblank)
42
+ command.add_argument("--channel", type=nonblank)
43
+ command.add_argument("--topic", type=nonblank)
44
+ command.add_argument("--limit", type=int, default=20, metavar="1..100")
45
+ send = sub.add_parser("send", help="Post one message with content from stdin", allow_abbrev=False)
46
+ dest = send.add_mutually_exclusive_group(required=True)
47
+ dest.add_argument("--channel-id", type=positive)
48
+ dest.add_argument("--user-id", type=positive, action="append", help="Repeat for a group DM")
49
+ send.add_argument("--topic", type=nonblank)
50
+ return root
51
+
52
+
53
+ def config():
54
+ site = os.environ.get("ZULIP_URL")
55
+ email = os.environ.get("ZULIP_EMAIL")
56
+ key = os.environ.get("ZULIP_API_KEY")
57
+ if not all((site, email, key)):
58
+ raise InputError("Set ZULIP_URL, ZULIP_EMAIL and ZULIP_API_KEY privately.")
59
+ try:
60
+ url = urlsplit(site)
61
+ valid = (
62
+ url.scheme == "https" and url.hostname and url.port != 0
63
+ and url.username is None and url.password is None
64
+ and url.path in ("", "/") and not any(c in site for c in "?#\\")
65
+ and not any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in site)
66
+ )
67
+ except ValueError:
68
+ valid = False
69
+ if not valid:
70
+ raise InputError("ZULIP_URL must be an HTTPS server origin without credentials or a path.")
71
+ return f"https://{url.netloc}", email, key
72
+
73
+
74
+ def prepare(args):
75
+ if args.command == "profile":
76
+ return "get_profile", ()
77
+ if args.command in {"read", "search"}:
78
+ if not 1 <= args.limit <= 100:
79
+ raise InputError("--limit must be between 1 and 100.")
80
+ if args.topic and not args.channel:
81
+ raise InputError("--topic requires --channel.")
82
+ narrow = []
83
+ if args.channel:
84
+ narrow.append({"operator": "stream", "operand": args.channel})
85
+ if args.topic:
86
+ narrow.append({"operator": "topic", "operand": args.topic})
87
+ if args.command == "search":
88
+ narrow.append({"operator": "search", "operand": args.query})
89
+ return "get_messages", ({"anchor": "newest", "num_before": args.limit,
90
+ "num_after": 0, "apply_markdown": False, "narrow": narrow},)
91
+ if bool(args.channel_id) != bool(args.topic):
92
+ raise InputError("Specify --topic with --channel-id only.")
93
+ if sys.stdin.isatty():
94
+ raise InputError("Pipe message content to send on stdin; no prompt is provided.")
95
+ body = sys.stdin.buffer.read(65537)
96
+ if len(body) > 65536:
97
+ raise InputError("Message exceeds the 64 KiB input limit.")
98
+ try:
99
+ content = body.decode("utf-8")
100
+ except UnicodeError:
101
+ raise InputError("Message content must be UTF-8.") from None
102
+ if not content.strip():
103
+ raise InputError("Message content cannot be empty.")
104
+ payload = {"content": content}
105
+ if args.channel_id:
106
+ payload.update(type="stream", to=args.channel_id, topic=args.topic)
107
+ else:
108
+ payload.update(type="private", to=list(dict.fromkeys(args.user_id)))
109
+ return "send_message", (payload,)
110
+
111
+
112
+ def make_client(site, email, key):
113
+ import zulip
114
+
115
+ class Client(zulip.Client):
116
+ def ensure_session(self):
117
+ if self.session is None:
118
+ super().ensure_session()
119
+ self.session.trust_env = False
120
+ request = self.session.request
121
+
122
+ def without_redirects(*args, **kwargs):
123
+ response = request(*args, allow_redirects=False, **kwargs)
124
+ if not 200 <= response.status_code < 300:
125
+ raise RuntimeError("Zulip returned a non-success HTTP status")
126
+ return response
127
+
128
+ self.session.request = without_redirects
129
+
130
+ # Ignore optional SDK certificate variables and never read ~/.zuliprc.
131
+ for name in ("ZULIP_CERT", "ZULIP_CERT_KEY", "ZULIP_CERT_BUNDLE"):
132
+ os.environ.pop(name, None)
133
+ return Client(site=site, email=email, api_key=key, config_file=os.devnull,
134
+ insecure=False, retry_on_errors=False, client="zulip-nod/0.1.0")
135
+
136
+
137
+ def redact(value, key):
138
+ if isinstance(value, str):
139
+ return value.replace(key, "<redacted>")
140
+ if isinstance(value, dict):
141
+ return {redact(k, key): redact(v, key) for k, v in value.items()}
142
+ if isinstance(value, list):
143
+ return [redact(v, key) for v in value]
144
+ return value
145
+
146
+
147
+ def emit(result, key=None):
148
+ print(json.dumps(redact(result, key) if key else result, allow_nan=False))
149
+
150
+
151
+ def main():
152
+ logging.disable(logging.CRITICAL)
153
+ try:
154
+ args = parser().parse_args()
155
+ site, email, key = config()
156
+ method, params = prepare(args)
157
+ except InputError as exc:
158
+ emit({"result": "error", "message": str(exc)})
159
+ return 2
160
+ except OSError:
161
+ emit({"result": "error", "message": "Could not read message input."})
162
+ return 2
163
+ attempted = False
164
+ try:
165
+ client = make_client(site, email, key)
166
+ attempted = args.command == "send"
167
+ response = getattr(client, method)(*params)
168
+ if not isinstance(response, dict) or response.get("result") != "success":
169
+ raise RuntimeError("Zulip API call failed")
170
+ if args.command in {"read", "search"}:
171
+ response["messages"] = response["messages"][-args.limit:]
172
+ if attempted:
173
+ if type(response.get("id")) is not int or response["id"] <= 0:
174
+ raise RuntimeError("No message ID returned")
175
+ response = {"result": "success", "id": response["id"]}
176
+ emit(response, key)
177
+ except Exception:
178
+ message = ("Send outcome unknown. Check Zulip before retrying." if attempted else
179
+ "Zulip request failed. Check the server URL, credentials and account access.")
180
+ emit({"result": "error", "message": message})
181
+ return 1
182
+ return 0
183
+
184
+
185
+ if __name__ == "__main__":
186
+ raise SystemExit(main())
@@ -0,0 +1,68 @@
1
+ Metadata-Version: 2.4
2
+ Name: zulip-nod
3
+ Version: 0.1.0
4
+ Summary: Small non-interactive JSON CLI for Zulip
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: zulip==0.9.1
8
+
9
+ # zulip-nod
10
+
11
+ A small, non-interactive Zulip CLI using the official Python `zulip` client.
12
+ Requires Python 3.10 or newer. No Node.js or terminal UI is required.
13
+
14
+ ## Install and configure
15
+
16
+ Install the wheel with `python -m pip install ./zulip_nod-0.1.0-py3-none-any.whl`.
17
+ For Nod, supply these variables in private setup, not as CLI arguments:
18
+
19
+ - `ZULIP_URL`: your Zulip HTTPS origin, with no path or credentials.
20
+ - `ZULIP_EMAIL`: the user or bot's Zulip API email.
21
+ - `ZULIP_API_KEY`: the account's Zulip API key.
22
+
23
+ This CLI ignores `~/.zuliprc`, proxy settings and TLS override variables. It
24
+ verifies TLS, does not follow redirects, and disables SDK retries. The SDK fetches
25
+ server settings before the requested operation. No other commands mutate Zulip.
26
+
27
+ ## Usage
28
+
29
+ ```sh
30
+ zulip profile
31
+ zulip read --limit 10
32
+ zulip read --channel engineering --topic planning --limit 10
33
+ zulip search 'quarterly budget' --channel finance --limit 10
34
+ zulip send --channel-id 42 --topic planning < message.txt
35
+ zulip send --user-id 12 --user-id 34 < message.txt
36
+ ```
37
+
38
+ Reads and searches default to 20 messages and accept a limit of 1 to 100, with
39
+ no auto-pagination or mark-as-read calls. Search follows Zulip's own permissions
40
+ and history rules. `send` requires an explicit destination and a UTF-8 message
41
+ on stdin. It does not prompt. Use the same `--user-id` flag again for a group DM.
42
+ If a send reports an unknown outcome, check Zulip before retrying.
43
+
44
+ Commands write one JSON object to stdout. Exit codes: `0` success, `2` invalid
45
+ input or missing configuration, `1` request failure or unknown send outcome.
46
+ `--help` and `--version` are plain text and work offline. Successful profile and
47
+ message output contains private account data; treat it accordingly.
48
+
49
+ ## Package and upload
50
+
51
+ From the source tree, run `python -m pip install build twine` and then
52
+ `python -m build` to build both distributions. To publish the supplied files
53
+ without rebuilding, put only those two files in a clean `dist/` directory, review
54
+ them, and run:
55
+
56
+ ```sh
57
+ python -m twine check dist/zulip_nod-0.1.0*
58
+ python -m twine upload dist/zulip_nod-0.1.0*
59
+ ```
60
+
61
+ Use your own PyPI account and enter an upload token privately if prompted. Do
62
+ not put the token in the command line or send it in chat. The upload is public.
63
+
64
+ ## Offline tests
65
+
66
+ After installing the wheel, run `python -m unittest discover -s tests -v` from
67
+ an extracted source distribution. The tests exercise the installed package and
68
+ stub the HTTP adapter; no Zulip server or real credentials are used.
@@ -0,0 +1,11 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/zulip_nod/__init__.py
4
+ src/zulip_nod/cli.py
5
+ src/zulip_nod.egg-info/PKG-INFO
6
+ src/zulip_nod.egg-info/SOURCES.txt
7
+ src/zulip_nod.egg-info/dependency_links.txt
8
+ src/zulip_nod.egg-info/entry_points.txt
9
+ src/zulip_nod.egg-info/requires.txt
10
+ src/zulip_nod.egg-info/top_level.txt
11
+ tests/test_cli.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zulip = zulip_nod.cli:main
@@ -0,0 +1 @@
1
+ zulip==0.9.1
@@ -0,0 +1 @@
1
+ zulip_nod
@@ -0,0 +1,101 @@
1
+ import contextlib
2
+ import io
3
+ import json
4
+ import os
5
+ import unittest
6
+ from unittest.mock import patch
7
+ from urllib.parse import parse_qs, urlsplit
8
+
9
+ import requests
10
+ from zulip_nod.cli import main
11
+
12
+ KEY = "offline-only-test-key"
13
+
14
+
15
+ class CLI(unittest.TestCase):
16
+ def invoke(self, argv, responses=(), body=b"", env=None):
17
+ self.calls = []
18
+ stdout, stderr = io.StringIO(), io.StringIO()
19
+ answers = iter(responses)
20
+
21
+ def fake_send(adapter, request, **kwargs):
22
+ self.calls.append((request, kwargs))
23
+ data = next(answers)
24
+ if isinstance(data, Exception):
25
+ raise data
26
+ status, payload = data if isinstance(data, tuple) else (200, data)
27
+ response = requests.Response()
28
+ response.status_code = status
29
+ response._content = json.dumps(payload).encode()
30
+ response.url = request.url
31
+ response.request = request
32
+ if status == 307:
33
+ response.headers["Location"] = "https://elsewhere.invalid/"
34
+ return response
35
+
36
+ with patch.dict(os.environ, env if env is not None else {
37
+ "ZULIP_URL": "https://server.invalid/", "ZULIP_EMAIL": "reader@example.invalid",
38
+ "ZULIP_API_KEY": KEY,
39
+ }, clear=True), patch.object(requests.adapters.HTTPAdapter, "send", fake_send), \
40
+ patch("sys.argv", ["zulip", *argv]), \
41
+ patch("sys.stdin", io.TextIOWrapper(io.BytesIO(body))), \
42
+ contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
43
+ code = main()
44
+ self.assertEqual(stderr.getvalue(), "")
45
+ self.assertNotIn(KEY, stdout.getvalue())
46
+ return code, json.loads(stdout.getvalue())
47
+
48
+ def test_profile_and_redaction(self):
49
+ code, data = self.invoke(["profile"], [SETTINGS, {"result": "success", "user_id": 4,
50
+ "echo": KEY}])
51
+ self.assertEqual((code, data["user_id"], data["echo"]), (0, 4, "<redacted>"))
52
+ self.assertEqual([r.path_url for r, _ in self.calls], ["/api/v1/server_settings", "/api/v1/users/me"])
53
+ self.assertTrue(all(k["verify"] and not k["proxies"] for _, k in self.calls))
54
+
55
+ def test_read_search_bounds_and_narrow(self):
56
+ for command in (["read"], ["search", "planning notes"]):
57
+ code, data = self.invoke(command + ["--channel", "general", "--topic", "June", "--limit", "2"],
58
+ [SETTINGS, {"result": "success", "messages": [1, 2, 3]}])
59
+ self.assertEqual((code, data["messages"]), (0, [2, 3]))
60
+ request = self.calls[-1][0]
61
+ self.assertEqual(request.method, "GET")
62
+ query = parse_qs(urlsplit(request.url).query)
63
+ self.assertEqual(query["num_before"], ["2"])
64
+ self.assertEqual(query["num_after"], ["0"])
65
+ expected = [dict(operator="stream", operand="general"), dict(operator="topic", operand="June")]
66
+ if len(command) == 2:
67
+ expected.append(dict(operator="search", operand=command[1]))
68
+ self.assertEqual(json.loads(query["narrow"][0]), expected)
69
+
70
+ def test_send_payloads(self):
71
+ for args, expected in [(["--channel-id", "42", "--topic", "Plans"],
72
+ {"type": ["stream"], "to": ["42"], "topic": ["Plans"]}),
73
+ (["--user-id", "12", "--user-id", "34"],
74
+ {"type": ["private"], "to": ["[12, 34]"]})]:
75
+ self.assertEqual(self.invoke(["send", *args], [SETTINGS, {"result": "success", "id": 99}],
76
+ b"Hello!"), (0, {"result": "success", "id": 99}))
77
+ request = self.calls[-1][0]
78
+ self.assertEqual((request.method, request.path_url), ("POST", "/api/v1/messages"))
79
+ self.assertEqual(parse_qs(request.body), dict(expected, content=["Hello!"]))
80
+
81
+ def test_no_network_on_invalid_input(self):
82
+ for args in (["read", "--limit", "101"], ["search", " "], ["profile", "--key", KEY],
83
+ ["send", "--channel-id", "42"], ["send", "--user-id", "3"]):
84
+ self.assertEqual(self.invoke(args)[0], 2)
85
+ self.assertEqual(self.calls, [])
86
+ self.assertEqual(self.invoke(["profile"], env={})[0], 2)
87
+ self.assertEqual(self.calls, [])
88
+
89
+ def test_send_timeout_is_not_retried(self):
90
+ code, data = self.invoke(["send", "--user-id", "7"],
91
+ [SETTINGS, requests.Timeout(KEY)], b"hello")
92
+ self.assertEqual(code, 1)
93
+ self.assertIn("outcome unknown", data["message"])
94
+ self.assertEqual(len(self.calls), 2)
95
+
96
+ def test_redirect_is_not_followed(self):
97
+ self.assertEqual(self.invoke(["profile"], [(307, SETTINGS)])[0], 1)
98
+ self.assertEqual(len(self.calls), 1)
99
+
100
+
101
+ SETTINGS = {"result": "success", "zulip_version": "10.0", "zulip_feature_level": 350}