pywa-cloud-cli 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.
@@ -0,0 +1,287 @@
1
+ """
2
+ `pywa cloud tunnel` - connects to Pywa Cloud over a WebSocket and relays each
3
+ inbound webhook request to a bot process running locally, forwarding its response back. Opt-in and
4
+ explicit: a standalone command you run yourself, not automatic behavior, so your deployed
5
+ bot keeps receiving webhooks unless you deliberately start a tunnel session.
6
+
7
+ A dropped connection (network blip, laptop sleep, a server restart) is retried with backoff for as
8
+ long as the command runs. Only a close the server meant - taken over by a teammate, stopped from the
9
+ dashboard, not authorised - ends the session. While connected, a small heartbeat tells the server this
10
+ machine is still there; without it the server drops the tunnel and webhooks reach the deployed bot again.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import base64
17
+ import json
18
+ import os
19
+ from collections.abc import Callable
20
+
21
+ import httpx
22
+ import websockets
23
+ from websockets.exceptions import (
24
+ ConnectionClosed,
25
+ InvalidHandshake,
26
+ InvalidStatus,
27
+ ProxyError,
28
+ )
29
+
30
+ from pywa_cloud_cli import config
31
+ from pywa_cloud_cli.client import identity_headers
32
+
33
+ # Close codes the server sends on purpose: replaced by a newer connection or stopped from the dashboard (4000),
34
+ # not authorised (4401), bot in production (4403), idle or open too long (4409), this CLI too old (4426). Reconnecting would only fight them.
35
+ _TERMINAL_CLOSE_CODES = {4000, 4401, 4403, 4409, 4426}
36
+ HEARTBEAT_S = 15.0 # well inside the server's lease
37
+ LOCAL_TIMEOUT_S = (
38
+ 25.0 # shorter than the server's 30 s wait, so a slow bot gets a real 502 back
39
+ )
40
+ RECONNECT_MIN_S = 1.0
41
+ RECONNECT_MAX_S = 30.0
42
+ # httpx already decoded the body, so these would describe bytes the receiver never gets.
43
+ _DROPPED_RESPONSE_HEADERS = {
44
+ "content-encoding",
45
+ "content-length",
46
+ "transfer-encoding",
47
+ "connection",
48
+ }
49
+
50
+
51
+ def _ws_url(bot_id: str) -> str:
52
+ scheme = "wss" if config.API_URL.startswith("https") else "ws"
53
+ rest = config.API_URL.split("://", 1)[-1].rstrip("/")
54
+ return f"{scheme}://{rest}/tunnel/{bot_id}"
55
+
56
+
57
+ def _describe_local_error(e: httpx.HTTPError, port: str) -> str:
58
+ """Why the local server did not answer, in words (an httpx timeout has an empty message)."""
59
+ if isinstance(e, httpx.TimeoutException):
60
+ return f"no answer within {LOCAL_TIMEOUT_S:.0f}s: is the handler stuck?"
61
+ if isinstance(e, httpx.ConnectError):
62
+ return f"nothing is listening on port {port}: is `pywa dev` running?"
63
+ return str(e) or type(e).__name__
64
+
65
+
66
+ def local_base_url(host: str, port: int) -> str:
67
+ """Where the local bot is reached. `host` is what the bot binds to (`pywa dev --host`): a wildcard
68
+ bind address (`0.0.0.0`, `::`) accepts loopback connections, but is not itself something to
69
+ connect to."""
70
+ host = {"0.0.0.0": "127.0.0.1", "::": "::1", "": "127.0.0.1"}.get(host, host)
71
+ if ":" in host: # IPv6 literal
72
+ host = f"[{host.strip('[]')}]"
73
+ return f"http://{host}:{port}"
74
+
75
+
76
+ async def _forward(
77
+ ws: websockets.ClientConnection,
78
+ local: httpx.AsyncClient,
79
+ message: dict,
80
+ on_status: Callable[[str], None],
81
+ ) -> None:
82
+ method = message["method"]
83
+ path = message["path"]
84
+ if (
85
+ not isinstance(path, str)
86
+ or not path.startswith("/")
87
+ or path.startswith("//")
88
+ or "\\" in path
89
+ ):
90
+ # A path like `//host/x` is a network-path reference: the HTTP client would send the request to
91
+ # `host` instead of the local bot, i.e. a request from this developer's machine to anywhere.
92
+ await ws.send(
93
+ json.dumps(
94
+ {
95
+ "type": "response",
96
+ "id": message["id"],
97
+ "status": 400,
98
+ "headers": {},
99
+ "body_b64": "",
100
+ }
101
+ )
102
+ )
103
+ on_status(f"{method} {path!r} -> refused (not a plain path)")
104
+ return
105
+ query = message.get("query") or ""
106
+ target = f"{path}?{query}" if query else path
107
+ body = base64.b64decode(message["body_b64"]) if message.get("body_b64") else b""
108
+ try:
109
+ resp = await local.request(
110
+ method, target, headers=message.get("headers", {}), content=body or None
111
+ )
112
+ status_code, resp_headers, resp_body = (
113
+ resp.status_code,
114
+ {
115
+ k: v
116
+ for k, v in resp.headers.items()
117
+ if k.lower() not in _DROPPED_RESPONSE_HEADERS
118
+ },
119
+ resp.content,
120
+ )
121
+ # Successful requests are not logged: the bot prints its own line for every update, so a
122
+ # second one here would only be noise. Only what the bot can't report itself shows up.
123
+ except httpx.HTTPError as e:
124
+ status_code, resp_headers, resp_body = 502, {}, str(e).encode()
125
+ on_status(
126
+ f"{method} {path} -> your local server at {local.base_url} didn't respond "
127
+ f"({_describe_local_error(e, str(local.base_url.port))})"
128
+ )
129
+ await ws.send(
130
+ json.dumps(
131
+ {
132
+ "type": "response",
133
+ "id": message["id"],
134
+ "status": status_code,
135
+ "headers": resp_headers,
136
+ "body_b64": base64.b64encode(resp_body).decode("ascii"),
137
+ }
138
+ )
139
+ )
140
+
141
+
142
+ async def _heartbeat(ws: websockets.ClientConnection) -> None:
143
+ try:
144
+ while True:
145
+ await asyncio.sleep(HEARTBEAT_S)
146
+ await ws.send(json.dumps({"type": "ping"}))
147
+ except ConnectionClosed:
148
+ pass # the receive loop sees the close itself
149
+
150
+
151
+ async def run(
152
+ token: str,
153
+ bot_id: str,
154
+ local_port: int,
155
+ on_status: Callable[[str], None] = print,
156
+ host: str = "127.0.0.1",
157
+ ) -> None:
158
+ url = _ws_url(bot_id)
159
+ local_base = local_base_url(host, local_port)
160
+ request_count = 0
161
+
162
+ async def serve(ws: websockets.ClientConnection) -> None:
163
+ """One connection's lifetime: relay each request until the stream ends."""
164
+ nonlocal request_count
165
+ # One task per request, so a slow local handler never delays the webhook behind it (Meta sends
166
+ # them concurrently, and the deployed bot would handle them concurrently too).
167
+ in_flight: set[asyncio.Task] = set()
168
+
169
+ async def relay(local: httpx.AsyncClient, message: dict) -> None:
170
+ try:
171
+ await _forward(ws, local, message, on_status)
172
+ except ConnectionClosed:
173
+ pass # the tunnel went away mid-request; the server already failed it
174
+
175
+ heartbeat = asyncio.create_task(_heartbeat(ws))
176
+ try:
177
+ # trust_env=False: the target is this machine's own server. With HTTP_PROXY set and 127.0.0.1 missing from
178
+ # NO_PROXY, httpx would send the request through the proxy, which cannot reach it and times out.
179
+ async with httpx.AsyncClient(
180
+ base_url=local_base, timeout=LOCAL_TIMEOUT_S, trust_env=False
181
+ ) as local:
182
+ async for raw in ws:
183
+ message = json.loads(raw)
184
+ if isinstance(message, dict) and message.get("type") == "request":
185
+ request_count += 1
186
+ task = asyncio.create_task(relay(local, message))
187
+ in_flight.add(task)
188
+ task.add_done_callback(in_flight.discard)
189
+ finally:
190
+ # A closed connection cannot carry answers any more, and the server has already failed
191
+ # whatever was waiting on them.
192
+ for task in (heartbeat, *in_flight):
193
+ task.cancel()
194
+ await asyncio.gather(heartbeat, *in_flight, return_exceptions=True)
195
+
196
+ # websockets (as of 15.x) raises from `connection_lost` when a proxy drops the connection before answering the
197
+ # handshake, and asyncio prints that as an ERROR traceback even though the fallback below handles it. Drop that
198
+ # one case and leave every other loop error alone.
199
+ loop = asyncio.get_running_loop()
200
+ default_handler = loop.get_exception_handler()
201
+
202
+ def handle_loop_error(loop: asyncio.AbstractEventLoop, context: dict) -> None:
203
+ exc = context.get("exception")
204
+ if (
205
+ isinstance(exc, AttributeError)
206
+ and "status_code" in str(exc)
207
+ and "connection_lost" in str(context.get("message", ""))
208
+ ):
209
+ return
210
+ (default_handler or loop.default_exception_handler)(context)
211
+
212
+ loop.set_exception_handler(handle_loop_error)
213
+
214
+ delay = RECONNECT_MIN_S
215
+ connected_before = False
216
+ use_proxy = True # websockets follows the proxy settings of the environment; some proxies cannot carry WebSockets
217
+ try:
218
+ while True:
219
+ try:
220
+ async with websockets.connect(
221
+ url,
222
+ additional_headers={
223
+ **identity_headers(),
224
+ "Authorization": f"Bearer {token}",
225
+ },
226
+ proxy=True if use_proxy else None,
227
+ ) as ws:
228
+ on_status(
229
+ "Tunnel reconnected."
230
+ if connected_before
231
+ else "Tunnel connected."
232
+ )
233
+ connected_before = True
234
+ delay = RECONNECT_MIN_S
235
+ await serve(ws)
236
+ reason = "The server closed the tunnel."
237
+ except ConnectionClosed as e:
238
+ # `rcvd` is the server's own close frame - e.g. a takeover by a teammate's tunnel session.
239
+ if e.rcvd is not None and e.rcvd.code in _TERMINAL_CLOSE_CODES:
240
+ raise RuntimeError(
241
+ e.rcvd.reason or f"Tunnel closed ({e.rcvd.code})"
242
+ ) from None
243
+ reason = "The tunnel connection was lost."
244
+ except ProxyError:
245
+ if use_proxy:
246
+ use_proxy = False
247
+ on_status(
248
+ "Your proxy cannot carry WebSockets; connecting directly."
249
+ )
250
+ continue
251
+ reason = (
252
+ "Could not reach the server (the proxy refused the connection)."
253
+ )
254
+ except InvalidStatus as e:
255
+ status_code = e.response.status_code
256
+ if status_code in (401, 403, 404):
257
+ raise RuntimeError(
258
+ f"The server refused the tunnel (HTTP {status_code}): check `pywa cloud login`, "
259
+ "the bot id, and that you are an admin of its team."
260
+ ) from None
261
+ reason = f"The server answered HTTP {status_code}."
262
+ except (OSError, InvalidHandshake, TimeoutError) as e:
263
+ reason = f"Could not reach the server ({e})."
264
+ if any(
265
+ os.environ.get(v)
266
+ for v in ("HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy")
267
+ ):
268
+ reason += " An HTTPS_PROXY is set in your environment and the tunnel goes through it; if it can't pass WebSockets, unset it (or add api.pywa.cloud to NO_PROXY)."
269
+ if not connected_before:
270
+ raise RuntimeError(reason)
271
+ on_status(f"{reason} Reconnecting in {delay:.0f}s...")
272
+ await asyncio.sleep(delay)
273
+ delay = min(delay * 2, RECONNECT_MAX_S)
274
+ finally:
275
+ # A closing summary regardless of *how* the session ended (Ctrl+C, a takeover, a refused
276
+ # reconnect) - `finally` around the whole loop, not just one exit path.
277
+ on_status(f"{request_count} request(s) relayed this session.")
278
+
279
+
280
+ def run_sync(
281
+ token: str,
282
+ bot_id: str,
283
+ local_port: int,
284
+ on_status: Callable[[str], None] = print,
285
+ host: str = "127.0.0.1",
286
+ ) -> None:
287
+ asyncio.run(run(token, bot_id, local_port, on_status, host))
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: pywa-cloud-cli
3
+ Version: 0.1.0
4
+ Summary: CLI for Pywa Cloud - deploy and manage pywa WhatsApp bots
5
+ Keywords: whatsapp,whatsapp-cloud-api,pywa,cli,deployment,hosting,whatsapp-bot,chatbot-framework
6
+ Author: David Lev
7
+ Author-email: David Lev <david@davidlev.dev>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Environment :: Console
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Topic :: Communications :: Chat
22
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content
23
+ Classifier: Topic :: Software Development :: Build Tools
24
+ Classifier: Topic :: System :: Software Distribution
25
+ Requires-Dist: httpx>=0.27,<1.0
26
+ Requires-Dist: certifi>=2026.10.19
27
+ Requires-Dist: pathspec>=0.12
28
+ Requires-Dist: websockets>=15.0
29
+ Maintainer: David Lev
30
+ Maintainer-email: David Lev <david@davidlev.dev>
31
+ Requires-Python: >=3.10
32
+ Project-URL: Homepage, https://pywa.cloud
33
+ Project-URL: Documentation, https://docs.pywa.cloud
34
+ Description-Content-Type: text/markdown
35
+
36
+ # pywa-cloud-cli
37
+
38
+ Command line for [Pywa Cloud](https://pywa.cloud): deploy and manage WhatsApp bots built with
39
+ [pywa](https://github.com/david-lev/pywa).
40
+
41
+ ```bash
42
+ pip install pywa-cloud-cli
43
+ ```
44
+
45
+ ## Quick start
46
+
47
+ ```bash
48
+ pywa-cloud login # opens your browser to confirm
49
+ cd my-bot
50
+ pywa-cloud deploy # picks or creates a bot, builds, starts it
51
+ pywa-cloud logs --follow
52
+ ```
53
+
54
+ Your project needs `pywa[server]` in `pyproject.toml` or `requirements.txt`. The first deploy links the folder to a
55
+ bot (`.pywacloud/link.json`, git-ignored), so later deploys need no arguments.
56
+
57
+ ## Commands
58
+
59
+ | | |
60
+ |---|---|
61
+ | `login`, `logout`, `whoami` | Sign in, sign out, show the current account (`login --token` for CI) |
62
+ | `bots create/list/get` | Manage bots; `set-entrypoint` and `set-directory` for non-default layouts |
63
+ | `deploy [path]` | Package the folder, upload it, build and start the bot |
64
+ | `status`, `logs`, `stop`, `start`, `restart` | Run and inspect a deployed bot |
65
+ | `env set/get/list/delete` | Environment variables and secrets (`env set KEY --secret`) |
66
+ | `deployments list/get/log/rollback` | Deployment history and rollback |
67
+ | `connect`, `connect-status` | Connect a WhatsApp Business number |
68
+ | `tunnel [--port 8000]` | Send a bot's webhooks to a process on your machine while you develop |
69
+ | `deploy-tokens`, `setup-ci` | Deploy from GitHub Actions |
70
+ | `link`, `unlink` | Tie a folder to a bot |
71
+
72
+ Run `pywa-cloud <command> --help` for options. The full reference is at <https://docs.pywa.cloud>.
73
+
74
+ Files listed in `.gitignore` or `.pywacloudignore` are left out of the upload. If pywa is installed too, the same
75
+ commands are available as `pywa cloud <command>`.
76
+
77
+ ## Requirements
78
+
79
+ Python 3.10 or newer. Set `NO_COLOR=1` to turn colours off.
80
+
81
+ ## License
82
+
83
+ MIT
@@ -0,0 +1,13 @@
1
+ pywa_cloud_cli/__init__.py,sha256=bB6wcP84bEEHoFVbD8_NZphCW202VFeJL25eMGMd3fc,409
2
+ pywa_cloud_cli/archive.py,sha256=1ZVwZaXa0PF1kH2gEtzDOxle7FXyC20t5jLkrJU8yio,4348
3
+ pywa_cloud_cli/cli.py,sha256=T_9ETStKe2SB6OkLEmPnvVPcK2BtROGzPRaPZ6MVgys,81284
4
+ pywa_cloud_cli/client.py,sha256=6NIzk6s4zotK8HvYL0T7AaXalXgi2MCC9kar5W9UA-g,19119
5
+ pywa_cloud_cli/config.py,sha256=Ur2fl0D_gqPxsjtfnH_mU9cGF5xP8kZ9rzqVSBxC1gw,2106
6
+ pywa_cloud_cli/link.py,sha256=htkmo4XPPf3YCMheeRX49Tj96eT4eoq3QXgGUWjC6L0,1814
7
+ pywa_cloud_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pywa_cloud_cli/tunnel.py,sha256=GNYT8DtaVNQT3_3daBZhG085bp7_YjS4S0vVNiAZBEk,11898
9
+ pywa_cloud_cli-0.1.0.dist-info/licenses/LICENSE,sha256=UhbA0IuHDAFRzmPrah0W1YiLySimAxNxDn88hmv6tbY,1066
10
+ pywa_cloud_cli-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
11
+ pywa_cloud_cli-0.1.0.dist-info/entry_points.txt,sha256=pAR-qVfXeIyHplUXmGgeBkpIQE07h1ilCilsl26dZKE,52
12
+ pywa_cloud_cli-0.1.0.dist-info/METADATA,sha256=I-PTEJALClBiahddIv3OVX8q-eH7cJ0csJ_vltJmImw,3214
13
+ pywa_cloud_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ pywa-cloud = pywa_cloud_cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 David Lev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.