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.
- pywa_cloud_cli/__init__.py +13 -0
- pywa_cloud_cli/archive.py +115 -0
- pywa_cloud_cli/cli.py +2070 -0
- pywa_cloud_cli/client.py +497 -0
- pywa_cloud_cli/config.py +72 -0
- pywa_cloud_cli/link.py +55 -0
- pywa_cloud_cli/py.typed +0 -0
- pywa_cloud_cli/tunnel.py +287 -0
- pywa_cloud_cli-0.1.0.dist-info/METADATA +83 -0
- pywa_cloud_cli-0.1.0.dist-info/RECORD +13 -0
- pywa_cloud_cli-0.1.0.dist-info/WHEEL +4 -0
- pywa_cloud_cli-0.1.0.dist-info/entry_points.txt +3 -0
- pywa_cloud_cli-0.1.0.dist-info/licenses/LICENSE +21 -0
pywa_cloud_cli/cli.py
ADDED
|
@@ -0,0 +1,2070 @@
|
|
|
1
|
+
"""The `pywa-cloud` command line: deploy and manage bots built with pywa on Pywa Cloud.
|
|
2
|
+
|
|
3
|
+
There are two entry points. `main()` is the standalone `pywa-cloud` executable. `register()` mounts the same
|
|
4
|
+
commands as `pywa cloud ...` on pywa's own CLI when both packages are installed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import datetime
|
|
11
|
+
import getpass
|
|
12
|
+
import os
|
|
13
|
+
import pathlib
|
|
14
|
+
import re
|
|
15
|
+
import subprocess
|
|
16
|
+
import sys
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
import webbrowser
|
|
20
|
+
from collections.abc import Callable, Iterable
|
|
21
|
+
|
|
22
|
+
from pywa_cloud_cli import archive, config, link
|
|
23
|
+
from pywa_cloud_cli import tunnel as pywa_tunnel
|
|
24
|
+
from pywa_cloud_cli.client import ApiError, DeployFailed, PywaCloudClient
|
|
25
|
+
|
|
26
|
+
# The workflow `setup-ci` writes. Not an f-string: GitHub's own `${{ ... }}` syntax would clash with it.
|
|
27
|
+
# "__BRANCH__" is the only placeholder.
|
|
28
|
+
_CI_WORKFLOW_TEMPLATE = """\
|
|
29
|
+
name: Deploy to Pywa Cloud
|
|
30
|
+
|
|
31
|
+
on:
|
|
32
|
+
push:
|
|
33
|
+
branches: [__BRANCH__]
|
|
34
|
+
|
|
35
|
+
jobs:
|
|
36
|
+
deploy:
|
|
37
|
+
runs-on: ubuntu-latest
|
|
38
|
+
steps:
|
|
39
|
+
- uses: actions/checkout@v4
|
|
40
|
+
- uses: actions/setup-python@v5
|
|
41
|
+
with:
|
|
42
|
+
python-version: "3.12"
|
|
43
|
+
- run: pip install pywa-cloud-cli
|
|
44
|
+
- name: Deploy
|
|
45
|
+
env:
|
|
46
|
+
PYWA_CLOUD_TOKEN: ${{ secrets.PYWA_CLOUD_TOKEN }}
|
|
47
|
+
PYWA_CLOUD_BOT_ID: ${{ secrets.PYWA_CLOUD_BOT_ID }}
|
|
48
|
+
run: pywa-cloud deploy
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
# The command name used in hints such as "run `{PROG} login`". `main()` and `register()` set it to match how the
|
|
52
|
+
# CLI was invoked.
|
|
53
|
+
PROG = "pywa cloud"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class PywaCloudCLIError(Exception):
|
|
57
|
+
"""Base exception for all pywa-cloud CLI errors."""
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _positive_int(text: str) -> int:
|
|
61
|
+
try:
|
|
62
|
+
value = int(text)
|
|
63
|
+
except ValueError:
|
|
64
|
+
raise argparse.ArgumentTypeError(f"invalid number: {text!r}") from None
|
|
65
|
+
if value < 1:
|
|
66
|
+
raise argparse.ArgumentTypeError("must be 1 or more")
|
|
67
|
+
return value
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _port(text: str) -> int:
|
|
71
|
+
value = _positive_int(text)
|
|
72
|
+
if value > 65535:
|
|
73
|
+
raise argparse.ArgumentTypeError("must be between 1 and 65535")
|
|
74
|
+
return value
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
_BRANCH_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._/-]*")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _require_config() -> config.Config:
|
|
81
|
+
cfg = config.load()
|
|
82
|
+
if cfg is None:
|
|
83
|
+
raise PywaCloudCLIError(f"Not logged in. Run `{PROG} login` first.")
|
|
84
|
+
return cfg
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _make_client(token: str | None) -> PywaCloudClient:
|
|
88
|
+
"""The one place the HTTP client is built, so tests can swap it."""
|
|
89
|
+
return PywaCloudClient(base_url=config.API_URL, token=token)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _bot_id(args: argparse.Namespace) -> str:
|
|
93
|
+
"""The bot a command acts on: `--bot`, `$PYWA_CLOUD_BOT_ID`, or the linked project's bot."""
|
|
94
|
+
return _resolve_bot_id(args.bot_id, pathlib.Path.cwd())
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _client_from_config() -> PywaCloudClient:
|
|
98
|
+
cfg = _require_config()
|
|
99
|
+
return _make_client(cfg.token)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _ask(prompt: str) -> str:
|
|
103
|
+
"""`input()` that turns Ctrl+C / Ctrl+D into a clean "Cancelled." instead of a traceback."""
|
|
104
|
+
try:
|
|
105
|
+
return input(prompt).strip()
|
|
106
|
+
except (KeyboardInterrupt, EOFError):
|
|
107
|
+
print()
|
|
108
|
+
raise PywaCloudCLIError("Cancelled.") from None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _paint(text: str, code: str) -> str:
|
|
112
|
+
"""ANSI colour for a terminal; plain text in a pipe, in CI logs, and when `NO_COLOR` is set."""
|
|
113
|
+
if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
|
|
114
|
+
return text
|
|
115
|
+
return f"\033[{code}m{text}\033[0m"
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _ok(message: str) -> None:
|
|
119
|
+
print(f"✅ {message}")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _warn(message: str) -> None:
|
|
123
|
+
print(f"⚠️ {message}")
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _dim(text: str) -> str:
|
|
127
|
+
return _paint(text, "2")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# Deployment status -> ANSI colour; anything else (stopped, a future status) stays plain.
|
|
131
|
+
_STATUS_COLORS = {"running": "32", "failed": "31", "building": "33"}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _status(status: str) -> str:
|
|
135
|
+
return _paint(status, _STATUS_COLORS.get(status, "0"))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _print_rows(rows: list[tuple[str, str]]) -> None:
|
|
139
|
+
"""Indented `Label value` lines with the values lined up (the detail view of one thing)."""
|
|
140
|
+
for label, value in rows:
|
|
141
|
+
print(f" {label:<13} {value}")
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _print_table(
|
|
145
|
+
headers: list[str],
|
|
146
|
+
rows: list[list[str]],
|
|
147
|
+
colors: dict[int, Callable[[str], str]] | None = None,
|
|
148
|
+
) -> None:
|
|
149
|
+
"""A dim header row and aligned columns. Cells are padded before they are coloured (colour codes have no width);
|
|
150
|
+
the last column is not padded. `colors` maps a column index to a function that paints that column's cells."""
|
|
151
|
+
widths = [
|
|
152
|
+
max(len(h), *(len(row[i]) for row in rows)) for i, h in enumerate(headers)
|
|
153
|
+
]
|
|
154
|
+
last = len(headers) - 1
|
|
155
|
+
print(
|
|
156
|
+
_dim(
|
|
157
|
+
" ".join(
|
|
158
|
+
h if i == last else h.ljust(widths[i]) for i, h in enumerate(headers)
|
|
159
|
+
)
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
for row in rows:
|
|
163
|
+
cells = []
|
|
164
|
+
for i, cell in enumerate(row):
|
|
165
|
+
padded = cell if i == last else cell.ljust(widths[i])
|
|
166
|
+
cells.append(colors[i](padded) if colors and i in colors else padded)
|
|
167
|
+
print(" ".join(cells))
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _choose(title: str, options: list[str], default: int = 1) -> int:
|
|
171
|
+
"""Numbered picker; returns the chosen 0-based index. Enter takes `default` (1-based), a bad
|
|
172
|
+
answer re-prompts (a typo shouldn't throw away a multi-step flow) up to 3 times."""
|
|
173
|
+
print(_paint(title, "1"))
|
|
174
|
+
for i, option in enumerate(options, start=1):
|
|
175
|
+
marker = _paint(f"{i})", "36")
|
|
176
|
+
print(f" {marker} {option}" + (_dim(" (default)") if i == default else ""))
|
|
177
|
+
for _ in range(3):
|
|
178
|
+
raw = _ask(f"Choose [1-{len(options)}] (Enter = {default}): ")
|
|
179
|
+
if not raw:
|
|
180
|
+
return default - 1
|
|
181
|
+
if raw.isdigit() and 1 <= int(raw) <= len(options):
|
|
182
|
+
return int(raw) - 1
|
|
183
|
+
print(f" Please enter a number between 1 and {len(options)}.")
|
|
184
|
+
raise PywaCloudCLIError("Too many invalid choices.")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _confirm(question: str, default: bool = True) -> bool:
|
|
188
|
+
raw = _ask(f"{question} [{'Y/n' if default else 'y/N'}] ").lower()
|
|
189
|
+
return default if not raw else raw in ("y", "yes")
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def _identity(email: str, name: str | None) -> str:
|
|
193
|
+
return f"{name} ({email})" if name else email
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def cmd_login(args: argparse.Namespace) -> None:
|
|
197
|
+
if args.token:
|
|
198
|
+
with _make_client(args.token) as client:
|
|
199
|
+
who = client.whoami()
|
|
200
|
+
config.save(config.Config(token=args.token))
|
|
201
|
+
print(f"✅ Logged in as {_identity(who['owner'], who.get('name'))}")
|
|
202
|
+
return
|
|
203
|
+
_device_login()
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _device_login() -> None:
|
|
207
|
+
"""OAuth2 device-code flow: opens the confirmation page in a browser, prints the code as a
|
|
208
|
+
fallback for headless environments, and polls until the user confirms it or the code expires.
|
|
209
|
+
`--token` remains the way to log in non-interactively (CI, `PYWA_CLOUD_TOKEN`) - this is the
|
|
210
|
+
default for a human running the CLI directly."""
|
|
211
|
+
with _make_client(None) as client:
|
|
212
|
+
device = client.start_device_login()
|
|
213
|
+
print(
|
|
214
|
+
f"To finish logging in, open:\n\n {device['verification_uri_complete']}\n"
|
|
215
|
+
)
|
|
216
|
+
print(f"and confirm the code shown there: {device['user_code']}\n")
|
|
217
|
+
try:
|
|
218
|
+
opened = webbrowser.open(device["verification_uri_complete"])
|
|
219
|
+
except webbrowser.Error:
|
|
220
|
+
opened = False
|
|
221
|
+
if not opened:
|
|
222
|
+
print(
|
|
223
|
+
"(couldn't open a browser automatically - visit the link above manually)"
|
|
224
|
+
)
|
|
225
|
+
print("Waiting for you to confirm in the browser (Ctrl+C to cancel)...")
|
|
226
|
+
|
|
227
|
+
interval = device.get("interval", 5)
|
|
228
|
+
deadline = time.monotonic() + device.get("expires_in", 600)
|
|
229
|
+
result = None
|
|
230
|
+
try:
|
|
231
|
+
while time.monotonic() < deadline:
|
|
232
|
+
time.sleep(interval)
|
|
233
|
+
result = client.poll_device_token(device["device_code"])
|
|
234
|
+
if result is not None:
|
|
235
|
+
break
|
|
236
|
+
except KeyboardInterrupt:
|
|
237
|
+
print()
|
|
238
|
+
raise PywaCloudCLIError("Cancelled.") from None
|
|
239
|
+
|
|
240
|
+
if result is None:
|
|
241
|
+
raise PywaCloudCLIError(
|
|
242
|
+
f"Login timed out waiting for confirmation. Run `{PROG} login` again."
|
|
243
|
+
)
|
|
244
|
+
config.save(config.Config(token=result["access_token"]))
|
|
245
|
+
print(
|
|
246
|
+
f"✅ Logged in as {_identity(result['user']['email'], result['user'].get('name'))}"
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def cmd_logout(_: argparse.Namespace) -> None:
|
|
251
|
+
cfg = config.load()
|
|
252
|
+
if cfg is not None:
|
|
253
|
+
# Best effort: revoke the token server-side so a copied auth.json is useless. Offline or an
|
|
254
|
+
# already-expired token must not stop the local logout.
|
|
255
|
+
try:
|
|
256
|
+
with _make_client(cfg.token) as client:
|
|
257
|
+
client.logout()
|
|
258
|
+
except ApiError:
|
|
259
|
+
pass
|
|
260
|
+
config.clear()
|
|
261
|
+
print("✅ Logged out")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cmd_whoami(_: argparse.Namespace) -> None:
|
|
265
|
+
cfg = _require_config()
|
|
266
|
+
with _make_client(cfg.token) as client:
|
|
267
|
+
who = client.whoami()
|
|
268
|
+
print(_identity(who["owner"], who.get("name")))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def cmd_bots_create(args: argparse.Namespace) -> None:
|
|
272
|
+
with _client_from_config() as client:
|
|
273
|
+
app = client.create_bot(
|
|
274
|
+
name=args.name,
|
|
275
|
+
entrypoint_override=args.entrypoint_override,
|
|
276
|
+
bot_directory=args.bot_directory,
|
|
277
|
+
)
|
|
278
|
+
print(f"✅ Created bot {app['name']!r} (id: {app['id']})")
|
|
279
|
+
|
|
280
|
+
project_dir = pathlib.Path.cwd()
|
|
281
|
+
if link.load(project_dir) is None:
|
|
282
|
+
# `--link`/`--no-link` decide explicitly; unset, only a human at a terminal is asked.
|
|
283
|
+
should_link = args.link
|
|
284
|
+
if should_link is None:
|
|
285
|
+
should_link = sys.stdin.isatty() and _confirm(
|
|
286
|
+
f"Link {project_dir} to this bot?"
|
|
287
|
+
)
|
|
288
|
+
if should_link:
|
|
289
|
+
link.save(project_dir, link.Link(bot_id=app["id"]))
|
|
290
|
+
print(f"✅ Linked {project_dir}")
|
|
291
|
+
print(
|
|
292
|
+
f"\nNext: `{PROG} deploy` - it connects a WhatsApp number first if the bot has none."
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def cmd_bots_set_entrypoint(args: argparse.Namespace) -> None:
|
|
297
|
+
bot_id = _bot_id(args)
|
|
298
|
+
with _client_from_config() as client:
|
|
299
|
+
app = client.update_bot(bot_id, entrypoint_override=args.entrypoint)
|
|
300
|
+
if app["entrypoint_override"]:
|
|
301
|
+
print(
|
|
302
|
+
f"✅ Entrypoint override for {app['name']!r} set to {app['entrypoint_override']!r}"
|
|
303
|
+
)
|
|
304
|
+
else:
|
|
305
|
+
print(
|
|
306
|
+
f"✅ Entrypoint override for {app['name']!r} cleared (falling back to default discovery)"
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def cmd_bots_set_directory(args: argparse.Namespace) -> None:
|
|
311
|
+
bot_id = _bot_id(args)
|
|
312
|
+
with _client_from_config() as client:
|
|
313
|
+
app = client.update_bot(bot_id, bot_directory=args.directory)
|
|
314
|
+
if app["bot_directory"]:
|
|
315
|
+
print(f"✅ Bot directory for {app['name']!r} set to {app['bot_directory']!r}")
|
|
316
|
+
else:
|
|
317
|
+
print(
|
|
318
|
+
f"✅ Bot directory for {app['name']!r} cleared (deploying from the project root)"
|
|
319
|
+
)
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def cmd_bots_list(_: argparse.Namespace) -> None:
|
|
323
|
+
with _client_from_config() as client:
|
|
324
|
+
apps = client.list_bots()
|
|
325
|
+
if not apps:
|
|
326
|
+
print(f"No bots yet. Create one with `{PROG} bots create <name>`.")
|
|
327
|
+
return
|
|
328
|
+
_print_table(
|
|
329
|
+
["NAME", "WHATSAPP", "LAST DEPLOY", "ID"],
|
|
330
|
+
[
|
|
331
|
+
[
|
|
332
|
+
app["name"],
|
|
333
|
+
app.get("whatsapp_display_phone_number") or "no number",
|
|
334
|
+
_relative(app["last_deployed_at"])
|
|
335
|
+
if app.get("last_deployed_at")
|
|
336
|
+
else "never",
|
|
337
|
+
app["id"],
|
|
338
|
+
]
|
|
339
|
+
for app in apps
|
|
340
|
+
],
|
|
341
|
+
)
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def cmd_bots_get(args: argparse.Namespace) -> None:
|
|
345
|
+
bot_id = _bot_id(args)
|
|
346
|
+
with _client_from_config() as client:
|
|
347
|
+
app = client.get_bot(bot_id)
|
|
348
|
+
print(f"{_paint(app['name'], '1')} {_dim(app['id'])}")
|
|
349
|
+
rows = [
|
|
350
|
+
("Environment", app.get("environment") or "development"),
|
|
351
|
+
("WhatsApp", app.get("whatsapp_display_phone_number") or "not connected"),
|
|
352
|
+
(
|
|
353
|
+
"Last deploy",
|
|
354
|
+
_relative(app["last_deployed_at"])
|
|
355
|
+
if app.get("last_deployed_at")
|
|
356
|
+
else "never",
|
|
357
|
+
),
|
|
358
|
+
]
|
|
359
|
+
if app.get("entrypoint_override"):
|
|
360
|
+
rows.append(("Entrypoint", app["entrypoint_override"]))
|
|
361
|
+
if app.get("bot_directory"):
|
|
362
|
+
rows.append(("Bot directory", app["bot_directory"]))
|
|
363
|
+
if app.get("is_suspended"):
|
|
364
|
+
rows.append(("Suspended", app.get("suspended_reason") or "yes"))
|
|
365
|
+
if app.get("stale_since"):
|
|
366
|
+
rows.append(
|
|
367
|
+
("Config", f"changed {_relative(app['stale_since'])}; redeploy to apply it")
|
|
368
|
+
)
|
|
369
|
+
if app.get("tunnel_active"):
|
|
370
|
+
rows.append(("Tunnel", "active: webhooks go to a developer's machine"))
|
|
371
|
+
_print_rows(rows)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _read_env_value(key: str) -> str:
|
|
375
|
+
"""The value when it wasn't given on the command line (where it would land in shell history
|
|
376
|
+
and `ps`): a hidden prompt at a terminal, otherwise stdin (`echo $TOKEN | pywa cloud env set ...`)."""
|
|
377
|
+
try:
|
|
378
|
+
value = (
|
|
379
|
+
getpass.getpass(f"Value for {key}: ")
|
|
380
|
+
if sys.stdin.isatty()
|
|
381
|
+
else sys.stdin.read().rstrip("\r\n")
|
|
382
|
+
)
|
|
383
|
+
except (KeyboardInterrupt, EOFError):
|
|
384
|
+
print()
|
|
385
|
+
raise PywaCloudCLIError("Cancelled.") from None
|
|
386
|
+
if not value and sys.stdin.isatty():
|
|
387
|
+
raise PywaCloudCLIError("No value given.")
|
|
388
|
+
return value
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def cmd_env_set(args: argparse.Namespace) -> None:
|
|
392
|
+
bot_id = _bot_id(args)
|
|
393
|
+
if "=" in args.key and args.value is None:
|
|
394
|
+
name, _, value = args.key.partition("=")
|
|
395
|
+
raise PywaCloudCLIError(
|
|
396
|
+
f"Give the name and the value as two arguments: `{PROG} env set {name} {value or '<value>'}`."
|
|
397
|
+
)
|
|
398
|
+
value = args.value if args.value is not None else _read_env_value(args.key)
|
|
399
|
+
with _client_from_config() as client:
|
|
400
|
+
_, created = client.set_env(bot_id, args.key, value, is_secret=args.secret)
|
|
401
|
+
label = _bot_label(client, bot_id)
|
|
402
|
+
verb = "Set" if created else "Updated"
|
|
403
|
+
note = ""
|
|
404
|
+
if not created and args.secret:
|
|
405
|
+
note = " (--secret ignored: the secret/plain designation is fixed at creation)"
|
|
406
|
+
print(f"✅ {verb} {args.key} on {label}{note}")
|
|
407
|
+
print(f" A running bot picks it up on its next deploy: `{PROG} deploy`.")
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def cmd_env_get(args: argparse.Namespace) -> None:
|
|
411
|
+
bot_id = _bot_id(args)
|
|
412
|
+
with _client_from_config() as client:
|
|
413
|
+
env_var = client.get_env(bot_id, args.key)
|
|
414
|
+
if env_var["is_secret"]:
|
|
415
|
+
updated = _relative(env_var["updated_at"])
|
|
416
|
+
print(
|
|
417
|
+
f"{env_var['key']}={_dim('<secret, value not shown>')} {_dim(f'(updated {updated})')}"
|
|
418
|
+
)
|
|
419
|
+
else:
|
|
420
|
+
print(f"{env_var['key']}={env_var['value']}")
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def cmd_env_list(args: argparse.Namespace) -> None:
|
|
424
|
+
bot_id = _bot_id(args)
|
|
425
|
+
with _client_from_config() as client:
|
|
426
|
+
env_vars = client.list_env(bot_id)
|
|
427
|
+
if not env_vars:
|
|
428
|
+
print("No env vars set on this bot yet.")
|
|
429
|
+
return
|
|
430
|
+
for env_var in env_vars:
|
|
431
|
+
value = _dim("<secret>") if env_var["is_secret"] else env_var["value"]
|
|
432
|
+
print(f"{env_var['key']}={value}")
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def cmd_env_delete(args: argparse.Namespace) -> None:
|
|
436
|
+
bot_id = _bot_id(args)
|
|
437
|
+
with _client_from_config() as client:
|
|
438
|
+
client.delete_env(bot_id, args.key)
|
|
439
|
+
label = _bot_label(client, bot_id)
|
|
440
|
+
print(f"✅ Deleted {args.key} from {label}")
|
|
441
|
+
print(f" A running bot stops seeing it on its next deploy: `{PROG} deploy`.")
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def cmd_link(args: argparse.Namespace) -> None:
|
|
445
|
+
project_dir = pathlib.Path(args.path or ".").resolve()
|
|
446
|
+
with _client_from_config() as client:
|
|
447
|
+
app = client.get_bot(
|
|
448
|
+
args.bot_id
|
|
449
|
+
) # fail fast if the bot doesn't exist/isn't ours
|
|
450
|
+
link.save(project_dir, link.Link(bot_id=app["id"]))
|
|
451
|
+
print(f"✅ Linked {project_dir} to {app['name']!r} ({app['id']})")
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def cmd_unlink(args: argparse.Namespace) -> None:
|
|
455
|
+
project_dir = pathlib.Path(args.path or ".").resolve()
|
|
456
|
+
was_linked = link.load(project_dir) is not None
|
|
457
|
+
link.clear(project_dir)
|
|
458
|
+
print(
|
|
459
|
+
f"✅ Unlinked {project_dir}"
|
|
460
|
+
if was_linked
|
|
461
|
+
else f"{project_dir} wasn't linked to a bot."
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _detect_default_branch(project_dir: pathlib.Path) -> str:
|
|
466
|
+
"""The project's current git branch; "main" when it is not a git repository or has no branch yet."""
|
|
467
|
+
result = subprocess.run(
|
|
468
|
+
["git", "-C", str(project_dir), "symbolic-ref", "--short", "HEAD"],
|
|
469
|
+
capture_output=True,
|
|
470
|
+
text=True,
|
|
471
|
+
check=False,
|
|
472
|
+
)
|
|
473
|
+
branch = result.stdout.strip()
|
|
474
|
+
return branch if result.returncode == 0 and branch else "main"
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def cmd_setup_ci(args: argparse.Namespace) -> None:
|
|
478
|
+
"""Writes a GitHub Actions workflow that deploys on push, using the repository secrets
|
|
479
|
+
`PYWA_CLOUD_TOKEN` (a deploy token) and `PYWA_CLOUD_BOT_ID`."""
|
|
480
|
+
project_dir = pathlib.Path.cwd()
|
|
481
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
482
|
+
workflow_dir = project_dir / ".github" / "workflows"
|
|
483
|
+
workflow_path = workflow_dir / "deploy.yml"
|
|
484
|
+
if workflow_path.exists() and not args.force:
|
|
485
|
+
raise PywaCloudCLIError(
|
|
486
|
+
f"{workflow_path} already exists. Pass --force to overwrite it."
|
|
487
|
+
)
|
|
488
|
+
branch = args.branch or _detect_default_branch(project_dir)
|
|
489
|
+
if not _BRANCH_NAME.fullmatch(branch):
|
|
490
|
+
raise PywaCloudCLIError(
|
|
491
|
+
f"{branch!r} isn't a usable branch name (letters, digits, '.', '_', '-' and '/')."
|
|
492
|
+
)
|
|
493
|
+
workflow_dir.mkdir(parents=True, exist_ok=True)
|
|
494
|
+
workflow_path.write_text(_CI_WORKFLOW_TEMPLATE.replace("__BRANCH__", branch))
|
|
495
|
+
print(f"✅ Wrote {workflow_path} (deploys on push to {branch!r})")
|
|
496
|
+
print(
|
|
497
|
+
"\nBefore this runs, add these repository secrets "
|
|
498
|
+
"(Settings > Secrets and variables > Actions):\n"
|
|
499
|
+
f" PYWA_CLOUD_TOKEN a deploy token - `{PROG} deploy-tokens create ci --bot {bot_id}`\n"
|
|
500
|
+
f" PYWA_CLOUD_BOT_ID {bot_id}\n"
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _resolve_bot_id(bot_id: str | None, project_dir: pathlib.Path) -> str:
|
|
505
|
+
if bot_id:
|
|
506
|
+
return bot_id
|
|
507
|
+
env_bot_id = os.environ.get("PYWA_CLOUD_BOT_ID")
|
|
508
|
+
if env_bot_id:
|
|
509
|
+
return env_bot_id
|
|
510
|
+
existing = link.load(project_dir)
|
|
511
|
+
if existing is not None:
|
|
512
|
+
return existing.bot_id
|
|
513
|
+
raise PywaCloudCLIError(
|
|
514
|
+
f"{project_dir} isn't linked to a bot yet. Pass --bot <bot-id>, or run "
|
|
515
|
+
f"`{PROG} link <bot-id>` first."
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _deploy_client(args: argparse.Namespace) -> PywaCloudClient:
|
|
520
|
+
"""`deploy` also accepts a deploy token in `$PYWA_CLOUD_TOKEN`, so CI never needs a personal login.
|
|
521
|
+
A deploy token can only deploy, so no other command reads it."""
|
|
522
|
+
env_token = os.environ.get("PYWA_CLOUD_TOKEN")
|
|
523
|
+
if env_token:
|
|
524
|
+
return _make_client(env_token)
|
|
525
|
+
return _client_from_config()
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _human_size(n: int) -> str:
|
|
529
|
+
size = float(n)
|
|
530
|
+
for unit in ("B", "KB", "MB"):
|
|
531
|
+
if size < 1024:
|
|
532
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
533
|
+
size /= 1024
|
|
534
|
+
return f"{size:.1f} GB"
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
def _seconds_since(iso: str) -> int:
|
|
538
|
+
"""Seconds from an ISO timestamp from the API (UTC, with or without an offset) to now; negative if in the future."""
|
|
539
|
+
# Python before 3.11 parses at most 6 fractional digits.
|
|
540
|
+
trimmed = re.sub(r"(\.\d{6})\d+", r"\1", iso.replace("Z", "+00:00"))
|
|
541
|
+
when = datetime.datetime.fromisoformat(trimmed)
|
|
542
|
+
if when.tzinfo is None:
|
|
543
|
+
when = when.replace(tzinfo=datetime.timezone.utc)
|
|
544
|
+
return int((datetime.datetime.now(datetime.timezone.utc) - when).total_seconds())
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _relative(iso: str | None) -> str:
|
|
548
|
+
""" "3 days ago", "just now" or (for a time still to come) "in 30 minutes"; "unknown" for none."""
|
|
549
|
+
if not iso:
|
|
550
|
+
return "unknown"
|
|
551
|
+
seconds = _seconds_since(iso)
|
|
552
|
+
future = seconds < 0
|
|
553
|
+
for unit, size in (("day", 86400), ("hour", 3600), ("minute", 60)):
|
|
554
|
+
if abs(seconds) >= size:
|
|
555
|
+
n = abs(seconds) // size
|
|
556
|
+
span = f"{n} {unit}{'s' if n != 1 else ''}"
|
|
557
|
+
return f"in {span}" if future else f"{span} ago"
|
|
558
|
+
return "in under a minute" if future else "just now"
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _clock(iso: str) -> str:
|
|
562
|
+
""" "2026-11-24 22:58 UTC": the minute is enough; the API's microseconds are noise."""
|
|
563
|
+
trimmed = re.sub(r"(\.\d{6})\d+", r"\1", iso.replace("Z", "+00:00"))
|
|
564
|
+
when = datetime.datetime.fromisoformat(trimmed)
|
|
565
|
+
if when.tzinfo is not None:
|
|
566
|
+
when = when.astimezone(datetime.timezone.utc)
|
|
567
|
+
return when.strftime("%Y-%m-%d %H:%M UTC")
|
|
568
|
+
|
|
569
|
+
|
|
570
|
+
def _ago(iso: str | None) -> str:
|
|
571
|
+
""" "deployed 3 days ago" for an ISO timestamp from the API; "not deployed yet" for none."""
|
|
572
|
+
return f"deployed {_relative(iso)}" if iso else "not deployed yet"
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _compact_duration(seconds: int) -> str:
|
|
576
|
+
""" "2d 4h", "3h 12m", "12m" or "under a minute"."""
|
|
577
|
+
seconds = max(0, seconds)
|
|
578
|
+
days, rest = divmod(seconds, 86400)
|
|
579
|
+
hours, rest = divmod(rest, 3600)
|
|
580
|
+
minutes = rest // 60
|
|
581
|
+
if days:
|
|
582
|
+
return f"{days}d {hours}h"
|
|
583
|
+
if hours:
|
|
584
|
+
return f"{hours}h {minutes}m"
|
|
585
|
+
if minutes:
|
|
586
|
+
return f"{minutes}m"
|
|
587
|
+
return "under a minute"
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _bot_label(client: PywaCloudClient, bot_id: str) -> str:
|
|
591
|
+
"""The bot's name for a confirmation line (its id if the name cannot be read: the action itself already worked)."""
|
|
592
|
+
try:
|
|
593
|
+
return repr(client.get_bot(bot_id)["name"])
|
|
594
|
+
except ApiError:
|
|
595
|
+
return bot_id
|
|
596
|
+
|
|
597
|
+
|
|
598
|
+
def _api_error_message(e: ApiError) -> str:
|
|
599
|
+
"""What to show for a failed API call: what to do about it for the common ones, and the server's own words
|
|
600
|
+
without the HTTP status number for the rest (a person cannot act on "404:")."""
|
|
601
|
+
if e.status_code == 401:
|
|
602
|
+
return f"You're not logged in, or your login has expired. Run `{PROG} login` to sign in."
|
|
603
|
+
if e.status_code == 404 and "bot not found" in str(e.detail).lower():
|
|
604
|
+
return f"Bot not found. It may have been deleted, or it belongs to another account (`{PROG} bots list` shows yours)."
|
|
605
|
+
message = str(e)
|
|
606
|
+
prefix = f"{e.status_code}: "
|
|
607
|
+
if 400 <= e.status_code < 500 and message.startswith(prefix):
|
|
608
|
+
message = message[len(prefix) :]
|
|
609
|
+
return re.sub(r"^\w+: Value error, ", "", message)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _describe_bots(apps: list[dict]) -> list[str]:
|
|
613
|
+
"""Picker lines in aligned columns: enough to tell two bots apart (number and last deploy), not an opaque id."""
|
|
614
|
+
name_width = max(len(app["name"]) for app in apps)
|
|
615
|
+
phone_width = max(
|
|
616
|
+
len(app.get("whatsapp_display_phone_number") or "no number") for app in apps
|
|
617
|
+
)
|
|
618
|
+
return [
|
|
619
|
+
f"{app['name']:<{name_width}} "
|
|
620
|
+
f"{app.get('whatsapp_display_phone_number') or 'no number':<{phone_width}} "
|
|
621
|
+
+ _dim(_ago(app.get("last_deployed_at")))
|
|
622
|
+
for app in apps
|
|
623
|
+
]
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _interactive_pick_or_create_bot(
|
|
627
|
+
client: PywaCloudClient, project_dir: pathlib.Path
|
|
628
|
+
) -> tuple[str, bool]:
|
|
629
|
+
"""First-deploy bot picker. Only used in a terminal; scripts and CI get the "pass --bot" error instead of a prompt."""
|
|
630
|
+
apps = client.list_bots()
|
|
631
|
+
if apps:
|
|
632
|
+
options = _describe_bots(apps)
|
|
633
|
+
options.append("Create a new bot")
|
|
634
|
+
# Enter must not overwrite a running bot that merely comes first in the list: it takes the bot named like
|
|
635
|
+
# this directory, and otherwise creates a new one (an unlinked directory is usually a new project).
|
|
636
|
+
same_name = next(
|
|
637
|
+
(
|
|
638
|
+
i
|
|
639
|
+
for i, app in enumerate(apps)
|
|
640
|
+
if app["name"].lower() == project_dir.name.lower()
|
|
641
|
+
),
|
|
642
|
+
len(apps),
|
|
643
|
+
)
|
|
644
|
+
choice = _choose(
|
|
645
|
+
"Which bot is this project for?", options, default=same_name + 1
|
|
646
|
+
)
|
|
647
|
+
if choice < len(apps):
|
|
648
|
+
return apps[choice]["id"], False
|
|
649
|
+
else:
|
|
650
|
+
print("You have no bots yet - let's create one.")
|
|
651
|
+
|
|
652
|
+
default_name = project_dir.name
|
|
653
|
+
name = _ask(f"Bot name [{default_name}]: ") or default_name
|
|
654
|
+
app = client.create_bot(name=name)
|
|
655
|
+
_ok(f"Created bot {app['name']!r} {_dim(app['id'])}")
|
|
656
|
+
return app["id"], True
|
|
657
|
+
|
|
658
|
+
|
|
659
|
+
_STAGE_LABELS = {
|
|
660
|
+
"preparing": "Preparing your project",
|
|
661
|
+
"building": "Building your bot",
|
|
662
|
+
"validating": "Checking that your bot starts",
|
|
663
|
+
"starting": "Starting your bot",
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
def _print_deploy_failure(what: str, e: DeployFailed) -> None:
|
|
668
|
+
"""Where it stopped and why, then how to read more: the deploy log has every step."""
|
|
669
|
+
last_line = next(
|
|
670
|
+
(ln for ln in reversed(e.build_log.splitlines()) if ln.strip()), ""
|
|
671
|
+
)
|
|
672
|
+
reason = (e.reason or last_line or "unknown error").strip()
|
|
673
|
+
where = _STAGE_LABELS.get(e.stage or "")
|
|
674
|
+
print(
|
|
675
|
+
f"❌ {what} failed{f' while {where[0].lower()}{where[1:]}' if where else ''}:"
|
|
676
|
+
)
|
|
677
|
+
print("\n".join(f" {line}" if line else "" for line in reason.splitlines()))
|
|
678
|
+
print(f"\nDeploy log: {PROG} deployments log {e.deployment_id}")
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _python_label(deployment: dict) -> str:
|
|
682
|
+
""" "Python 3.14", plus why that version when the build log says (a project that doesn't pin
|
|
683
|
+
one gets the newest supported, which is worth knowing). The "-slim" suffix of the tag is left out."""
|
|
684
|
+
tag = deployment.get("python_version") or ""
|
|
685
|
+
label = f"Python {tag.split('-')[0]}" if tag else "Python version unknown"
|
|
686
|
+
why = re.search(
|
|
687
|
+
r"Resolved Python version: \S+ \((.+)\)", deployment.get("build_log") or ""
|
|
688
|
+
)
|
|
689
|
+
return f"{label}, {why.group(1)}" if why else label
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
class _BuildProgress:
|
|
693
|
+
"""Shows that a build is alive and which stage it is in: a live line in a terminal; in a log (CI) a line whenever
|
|
694
|
+
the stage changes and one every 30 s otherwise."""
|
|
695
|
+
|
|
696
|
+
def __init__(self) -> None:
|
|
697
|
+
self._tty = sys.stdout.isatty()
|
|
698
|
+
self._shown = False
|
|
699
|
+
self._last_line = 0.0
|
|
700
|
+
self._stage: str | None = None
|
|
701
|
+
self._label = "Building"
|
|
702
|
+
|
|
703
|
+
def __call__(self, elapsed: float, deployment: dict | None = None) -> None:
|
|
704
|
+
stage = (deployment or {}).get("stage")
|
|
705
|
+
# A stage the CLI has no name for (or none yet) keeps the last known label instead of jumping back to "Building".
|
|
706
|
+
label = self._label = _STAGE_LABELS.get(stage or "", self._label)
|
|
707
|
+
if self._tty:
|
|
708
|
+
print(
|
|
709
|
+
f"\r{_paint('•', '36')} {label}... {int(elapsed)}s\033[K",
|
|
710
|
+
end="",
|
|
711
|
+
flush=True,
|
|
712
|
+
)
|
|
713
|
+
self._shown = True
|
|
714
|
+
elif stage != self._stage or elapsed - self._last_line >= 30:
|
|
715
|
+
self._stage, self._last_line = stage, elapsed
|
|
716
|
+
print(f" {label.lower()} ({int(elapsed)}s)...", flush=True)
|
|
717
|
+
|
|
718
|
+
def done(self) -> None:
|
|
719
|
+
if self._shown:
|
|
720
|
+
print("\r\033[K", end="", flush=True)
|
|
721
|
+
self._shown = False
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def _read_dotenv(path: pathlib.Path) -> dict[str, str]:
|
|
725
|
+
"""KEY=VALUE pairs of a `.env` file (`export` prefix, quotes and trailing comments handled; blank values skipped)."""
|
|
726
|
+
values: dict[str, str] = {}
|
|
727
|
+
if not path.is_file():
|
|
728
|
+
return values
|
|
729
|
+
for line in path.read_text(errors="replace").splitlines():
|
|
730
|
+
line = line.strip().removeprefix("export ").strip()
|
|
731
|
+
if not line or line.startswith("#") or "=" not in line:
|
|
732
|
+
continue
|
|
733
|
+
key, value = (part.strip() for part in line.split("=", 1))
|
|
734
|
+
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
|
735
|
+
value = value[1:-1]
|
|
736
|
+
elif " #" in value:
|
|
737
|
+
value = value.split(" #", 1)[0].rstrip()
|
|
738
|
+
if key.isidentifier() and value:
|
|
739
|
+
values[key] = value
|
|
740
|
+
return values
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _offer_env_upload(
|
|
744
|
+
client: PywaCloudClient, bot_id: str, project_dir: pathlib.Path
|
|
745
|
+
) -> None:
|
|
746
|
+
"""`.env` is never uploaded (it holds secrets), so a bot that reads its keys from the environment crashes on its
|
|
747
|
+
first deploy. Offer to set the ones the bot does not have yet, as secrets."""
|
|
748
|
+
local = _read_dotenv(project_dir / ".env")
|
|
749
|
+
if not local:
|
|
750
|
+
return
|
|
751
|
+
have = {v["key"] for v in client.list_env(bot_id)}
|
|
752
|
+
reserved = client.reserved_env_keys()
|
|
753
|
+
missing = {k: v for k, v in local.items() if k not in have and k not in reserved}
|
|
754
|
+
if not missing:
|
|
755
|
+
return
|
|
756
|
+
print(f"Found in your .env but not set on this bot: {', '.join(sorted(missing))}")
|
|
757
|
+
print(_dim("(.env itself is never uploaded.)"))
|
|
758
|
+
if not _confirm("Set them on the bot as secrets before deploying?"):
|
|
759
|
+
print(f"Skipped. Set one later with `{PROG} env set KEY --secret`.\n")
|
|
760
|
+
return
|
|
761
|
+
for key, value in missing.items():
|
|
762
|
+
try:
|
|
763
|
+
client.set_env(bot_id, key, value, is_secret=True)
|
|
764
|
+
except ApiError as e:
|
|
765
|
+
_warn(f"Could not set {key}: {_api_error_message(e)}")
|
|
766
|
+
print()
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def _ensure_whatsapp(client: PywaCloudClient, bot_id: str, interactive: bool) -> dict:
|
|
770
|
+
"""A bot cannot run without a WhatsApp number and the server refuses to deploy one: find that out before packaging
|
|
771
|
+
and uploading, and in a terminal fix it right here instead of sending the user off to another command."""
|
|
772
|
+
status = client.connect_status(bot_id)
|
|
773
|
+
if not status["connected"]:
|
|
774
|
+
if not interactive:
|
|
775
|
+
raise PywaCloudCLIError(
|
|
776
|
+
"This bot has no WhatsApp number yet, and a bot can't run without one. "
|
|
777
|
+
f"Run `{PROG} connect` in a terminal first."
|
|
778
|
+
)
|
|
779
|
+
print("This bot has no WhatsApp number yet - let's connect one first.\n")
|
|
780
|
+
_connect_whatsapp(client, client.get_bot(bot_id))
|
|
781
|
+
status = client.connect_status(bot_id)
|
|
782
|
+
print()
|
|
783
|
+
elif status.get("connection_status") not in (None, "active"):
|
|
784
|
+
_warn(
|
|
785
|
+
f"The bot's WhatsApp account is {status['connection_status']}; "
|
|
786
|
+
"messages may not get through (see the dashboard)."
|
|
787
|
+
)
|
|
788
|
+
return status
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
_DEPENDENCY_FILES = (
|
|
792
|
+
"pyproject.toml",
|
|
793
|
+
"requirements.txt",
|
|
794
|
+
"setup.py",
|
|
795
|
+
"setup.cfg",
|
|
796
|
+
"Pipfile",
|
|
797
|
+
)
|
|
798
|
+
|
|
799
|
+
|
|
800
|
+
# `pywa` as a requirement: quoted anywhere (`dependencies = ["pywa[server]", ...]`, setup.py, Pipfile) or at the start
|
|
801
|
+
# of a line (requirements.txt, setup.cfg, Pipfile). Not `pywa-cloud-cli`, `pywa.cli:main`, or the project's own name.
|
|
802
|
+
_PYWA_REQUIREMENT = re.compile(r"""["']\s*pywa(?:\[[^\]]*\])?\s*(?:[<>=!~;@]|["'])""")
|
|
803
|
+
_PYWA_REQUIREMENT_LINE = re.compile(r"^\s*pywa(?:\[[^\]]*\])?\s*(?:[<>=!~;@#]|$)")
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def _looks_like_pywa_project(project_dir: pathlib.Path) -> bool:
|
|
807
|
+
"""A cheap local guess, so a folder that is obviously not a bot (e.g. the pywa library itself, or an empty
|
|
808
|
+
directory) is caught *before* a bot is created for it. The build's own import check stays the authority."""
|
|
809
|
+
for name in _DEPENDENCY_FILES:
|
|
810
|
+
path = project_dir / name
|
|
811
|
+
if not path.is_file():
|
|
812
|
+
continue
|
|
813
|
+
for line in path.read_text(errors="replace").splitlines():
|
|
814
|
+
if re.match(r"\s*name\s*=", line):
|
|
815
|
+
continue
|
|
816
|
+
if _PYWA_REQUIREMENT.search(line):
|
|
817
|
+
return True
|
|
818
|
+
if name != "pyproject.toml" and _PYWA_REQUIREMENT_LINE.match(line):
|
|
819
|
+
return True
|
|
820
|
+
return False
|
|
821
|
+
|
|
822
|
+
|
|
823
|
+
_LOCAL_DEPENDENCY_FILES = (
|
|
824
|
+
"uv.lock",
|
|
825
|
+
"pylock.toml",
|
|
826
|
+
"pyproject.toml",
|
|
827
|
+
"requirements.txt",
|
|
828
|
+
)
|
|
829
|
+
_LOCAL_PATH = re.compile(
|
|
830
|
+
r"""(?x)
|
|
831
|
+
(?: \b(?:editable|directory|path|virtual)\s*=\s*["'] # uv.lock / pyproject.toml sources
|
|
832
|
+
| file:// # file URLs, in any of the files
|
|
833
|
+
| ^\s*-e\s+ # requirements.txt: `-e /path`
|
|
834
|
+
)
|
|
835
|
+
(/[^\s"')]+ | [A-Za-z]:[\\/][^\s"')]+) # an absolute path
|
|
836
|
+
""",
|
|
837
|
+
re.MULTILINE,
|
|
838
|
+
)
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def _local_path_dependencies(project_dir: pathlib.Path) -> list[str]:
|
|
842
|
+
"""Absolute paths outside the project that its dependency files point at (e.g. a `[tool.uv.sources]` editable
|
|
843
|
+
install of a local checkout). The build runs elsewhere, where those paths don't exist, so it would fail."""
|
|
844
|
+
found: dict[str, None] = {}
|
|
845
|
+
for name in _LOCAL_DEPENDENCY_FILES:
|
|
846
|
+
path = project_dir / name
|
|
847
|
+
if not path.is_file():
|
|
848
|
+
continue
|
|
849
|
+
for match in _LOCAL_PATH.finditer(path.read_text(errors="replace")):
|
|
850
|
+
dependency = pathlib.Path(match.group(1))
|
|
851
|
+
if not dependency.is_relative_to(project_dir):
|
|
852
|
+
found[str(dependency)] = None
|
|
853
|
+
return list(found)
|
|
854
|
+
|
|
855
|
+
|
|
856
|
+
def _warn_local_path_dependencies(project_dir: pathlib.Path) -> None:
|
|
857
|
+
paths = _local_path_dependencies(project_dir)
|
|
858
|
+
if not paths:
|
|
859
|
+
return
|
|
860
|
+
listing = "\n".join(f" {path}" for path in paths)
|
|
861
|
+
print(
|
|
862
|
+
f"⚠️ This project depends on files on this computer, which the build can't see:\n{listing}\n"
|
|
863
|
+
" Use a published version instead (remove the local path from pyproject.toml, then re-run `uv lock`).\n"
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def _is_bot_not_found(e: ApiError) -> bool:
|
|
868
|
+
return e.status_code == 404 and "bot not found" in str(e.detail).lower()
|
|
869
|
+
|
|
870
|
+
|
|
871
|
+
def cmd_deploy(args: argparse.Namespace) -> None:
|
|
872
|
+
try:
|
|
873
|
+
_deploy(args)
|
|
874
|
+
except ApiError as e:
|
|
875
|
+
if not _is_bot_not_found(e):
|
|
876
|
+
raise
|
|
877
|
+
project_dir = pathlib.Path(args.path or ".").resolve()
|
|
878
|
+
hint = (
|
|
879
|
+
f"`{PROG} unlink` removes the link from this folder, and the next `{PROG} deploy` can pick or create "
|
|
880
|
+
"another bot."
|
|
881
|
+
if link.load(project_dir) is not None
|
|
882
|
+
and not args.bot_id
|
|
883
|
+
and not os.environ.get("PYWA_CLOUD_BOT_ID")
|
|
884
|
+
else "Check the bot id."
|
|
885
|
+
)
|
|
886
|
+
raise PywaCloudCLIError(
|
|
887
|
+
f"That bot no longer exists (it may have been deleted). {hint}"
|
|
888
|
+
) from None
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def _offer_relink_if_bot_is_gone(
|
|
892
|
+
args: argparse.Namespace, project_dir: pathlib.Path, bot_id: str
|
|
893
|
+
) -> str:
|
|
894
|
+
"""In a terminal, a folder linked to a bot that has since been deleted offers to pick another one right away, instead of
|
|
895
|
+
failing on the first request. CI and scripts (no terminal, a deploy token) keep the plain error from `cmd_deploy`."""
|
|
896
|
+
if (
|
|
897
|
+
args.bot_id
|
|
898
|
+
or os.environ.get("PYWA_CLOUD_BOT_ID")
|
|
899
|
+
or os.environ.get("PYWA_CLOUD_TOKEN")
|
|
900
|
+
):
|
|
901
|
+
return bot_id
|
|
902
|
+
if link.load(project_dir) is None:
|
|
903
|
+
return bot_id
|
|
904
|
+
with _deploy_client(args) as client:
|
|
905
|
+
try:
|
|
906
|
+
client.get_bot(bot_id)
|
|
907
|
+
return bot_id
|
|
908
|
+
except ApiError as e:
|
|
909
|
+
if not _is_bot_not_found(e):
|
|
910
|
+
return bot_id
|
|
911
|
+
print(
|
|
912
|
+
"The bot this folder is linked to no longer exists - it may have been deleted."
|
|
913
|
+
)
|
|
914
|
+
if not _confirm("Unlink it and choose another bot?"):
|
|
915
|
+
raise PywaCloudCLIError(
|
|
916
|
+
f"Cancelled - nothing changed. `{PROG} unlink` removes the stale link from this folder."
|
|
917
|
+
)
|
|
918
|
+
link.clear(project_dir)
|
|
919
|
+
new_bot_id, _ = _interactive_pick_or_create_bot(client, project_dir)
|
|
920
|
+
return new_bot_id
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def _deploy(args: argparse.Namespace) -> None:
|
|
924
|
+
project_dir = pathlib.Path(args.path or ".").resolve()
|
|
925
|
+
if not project_dir.is_dir():
|
|
926
|
+
raise PywaCloudCLIError(
|
|
927
|
+
f"{project_dir} is not a folder."
|
|
928
|
+
if project_dir.exists()
|
|
929
|
+
else f"{project_dir} does not exist."
|
|
930
|
+
)
|
|
931
|
+
interactive = sys.stdin.isatty()
|
|
932
|
+
try:
|
|
933
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
934
|
+
except PywaCloudCLIError:
|
|
935
|
+
if not interactive:
|
|
936
|
+
raise
|
|
937
|
+
if not _looks_like_pywa_project(project_dir):
|
|
938
|
+
print(
|
|
939
|
+
f"{project_dir} doesn't list `pywa` in pyproject.toml or requirements.txt, so it "
|
|
940
|
+
"probably isn't a bot project (add `pywa[server]`)."
|
|
941
|
+
)
|
|
942
|
+
if not _confirm("Create a bot and deploy it anyway?", default=False):
|
|
943
|
+
raise PywaCloudCLIError("Cancelled - nothing changed.")
|
|
944
|
+
with _deploy_client(args) as client:
|
|
945
|
+
bot_id, _ = _interactive_pick_or_create_bot(client, project_dir)
|
|
946
|
+
else:
|
|
947
|
+
# Outside the `try`: declining the offer raises a PywaCloudCLIError that must stop the deploy, not look like "no bot".
|
|
948
|
+
if interactive:
|
|
949
|
+
bot_id = _offer_relink_if_bot_is_gone(args, project_dir, bot_id)
|
|
950
|
+
|
|
951
|
+
# A deploy token (CI) can only deploy: it cannot read the connection or the env, and nobody is there to answer.
|
|
952
|
+
personal_login = not os.environ.get("PYWA_CLOUD_TOKEN")
|
|
953
|
+
with _deploy_client(args) as client:
|
|
954
|
+
whatsapp = (
|
|
955
|
+
_ensure_whatsapp(client, bot_id, interactive) if personal_login else None
|
|
956
|
+
)
|
|
957
|
+
if interactive and personal_login:
|
|
958
|
+
_offer_env_upload(client, bot_id, project_dir)
|
|
959
|
+
|
|
960
|
+
_warn_local_path_dependencies(project_dir)
|
|
961
|
+
print(f"{_paint('•', '36')} Packaging {project_dir}")
|
|
962
|
+
try:
|
|
963
|
+
archive_bytes = archive.build_archive(project_dir)
|
|
964
|
+
except OSError as e:
|
|
965
|
+
raise PywaCloudCLIError(
|
|
966
|
+
f"Could not read {e.filename or project_dir}: {e.strerror or e}"
|
|
967
|
+
) from None
|
|
968
|
+
files, largest = archive.describe(archive_bytes)
|
|
969
|
+
print(f" {_dim(f'{files} files, {_human_size(len(archive_bytes))}')}")
|
|
970
|
+
if secrets := archive.secret_like(archive_bytes):
|
|
971
|
+
_warn(
|
|
972
|
+
f"These files look like secrets and are being uploaded: {', '.join(secrets[:5])}"
|
|
973
|
+
+ (f" and {len(secrets) - 5} more" if len(secrets) > 5 else "")
|
|
974
|
+
+ ". Keep secrets in environment variables (pywa env set), or list the files in .pywacloudignore."
|
|
975
|
+
)
|
|
976
|
+
if len(archive_bytes) > archive.MAX_ARCHIVE_BYTES:
|
|
977
|
+
biggest = "\n".join(
|
|
978
|
+
f" {_human_size(size):>9} {name}" for name, size in largest
|
|
979
|
+
)
|
|
980
|
+
raise PywaCloudCLIError(
|
|
981
|
+
f"The upload is {_human_size(len(archive_bytes))}; the limit is {_human_size(archive.MAX_ARCHIVE_BYTES)}. "
|
|
982
|
+
f"Largest files:\n{biggest}\nList what the bot doesn't need in .pywacloudignore."
|
|
983
|
+
)
|
|
984
|
+
|
|
985
|
+
if link.load(project_dir) is None:
|
|
986
|
+
# First deploy in this directory - link it (once the project packaged fine), so the next one needs no questions.
|
|
987
|
+
link.save(project_dir, link.Link(bot_id=bot_id))
|
|
988
|
+
_ok(f"Linked this folder {_dim(f'(next time just run `{PROG} deploy`)')}")
|
|
989
|
+
print(f"{_paint('•', '36')} Uploading and building {_dim('(a minute or two)')}")
|
|
990
|
+
began = time.monotonic()
|
|
991
|
+
progress = _BuildProgress()
|
|
992
|
+
try:
|
|
993
|
+
deployment = client.deploy(bot_id, archive_bytes, on_wait=progress)
|
|
994
|
+
except DeployFailed as e:
|
|
995
|
+
progress.done()
|
|
996
|
+
_print_deploy_failure("Deploy", e)
|
|
997
|
+
sys.exit(1)
|
|
998
|
+
except KeyboardInterrupt:
|
|
999
|
+
progress.done()
|
|
1000
|
+
print(
|
|
1001
|
+
"\nStopped waiting. A deploy that was already uploaded carries on in the background: "
|
|
1002
|
+
f"`{PROG} deployments list` shows how it ends."
|
|
1003
|
+
)
|
|
1004
|
+
sys.exit(130)
|
|
1005
|
+
progress.done()
|
|
1006
|
+
|
|
1007
|
+
_ok(
|
|
1008
|
+
_paint(f"Deployed in {int(time.monotonic() - began)}s", "1")
|
|
1009
|
+
+ f" {_dim(f'({_python_label(deployment)})')}"
|
|
1010
|
+
)
|
|
1011
|
+
print()
|
|
1012
|
+
if whatsapp and whatsapp.get("display_phone_number"):
|
|
1013
|
+
print(f" Try it message {whatsapp['display_phone_number']} on WhatsApp")
|
|
1014
|
+
print(f" Dashboard {config.DASHBOARD_URL.rstrip('/')}/bots/{bot_id}")
|
|
1015
|
+
print(f" Watch {PROG} logs --follow · {PROG} status")
|
|
1016
|
+
|
|
1017
|
+
|
|
1018
|
+
_TUNNEL_LOGS_NOTE = (
|
|
1019
|
+
"A local tunnel is active: webhooks go to a developer's machine, so the deployed bot is idle and these logs are "
|
|
1020
|
+
"from before. The live output is in the terminal running `pywa dev`."
|
|
1021
|
+
)
|
|
1022
|
+
# How often `logs --follow` re-checks whether the tunnel started or stopped.
|
|
1023
|
+
_TUNNEL_RECHECK_S = 15.0
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
def _tunnel_active(client, bot_id: str) -> bool | None:
|
|
1027
|
+
"""Whether a tunnel is relaying this bot's webhooks right now; None if that can't be told (the logs still show)."""
|
|
1028
|
+
try:
|
|
1029
|
+
return bool(client.get_bot(bot_id).get("tunnel_active"))
|
|
1030
|
+
except ApiError:
|
|
1031
|
+
return None
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
def cmd_logs(args: argparse.Namespace) -> None:
|
|
1035
|
+
project_dir = pathlib.Path.cwd()
|
|
1036
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1037
|
+
with _client_from_config() as client:
|
|
1038
|
+
# --follow keeps its own cursor, so --since only applies to a one-off fetch.
|
|
1039
|
+
initial_since = None if args.follow else args.since
|
|
1040
|
+
# Taken before the first fetch, so a line written meanwhile may show twice but never goes missing.
|
|
1041
|
+
cursor = datetime.datetime.now(datetime.timezone.utc)
|
|
1042
|
+
# On stderr, like the empty-logs note below, so piping the logs stays clean.
|
|
1043
|
+
tunnel = _tunnel_active(client, bot_id)
|
|
1044
|
+
if tunnel:
|
|
1045
|
+
print(_dim(_TUNNEL_LOGS_NOTE), file=sys.stderr)
|
|
1046
|
+
first = client.get_logs(bot_id, tail=args.tail, since=initial_since)
|
|
1047
|
+
print(first, end="")
|
|
1048
|
+
if not first.strip():
|
|
1049
|
+
# On stderr, so `pywa cloud logs | grep ...` stays empty when there is nothing to show.
|
|
1050
|
+
print(
|
|
1051
|
+
_dim(
|
|
1052
|
+
"No log lines yet."
|
|
1053
|
+
if args.follow
|
|
1054
|
+
else "No log lines yet (the bot may have just started)."
|
|
1055
|
+
),
|
|
1056
|
+
file=sys.stderr,
|
|
1057
|
+
)
|
|
1058
|
+
if not args.follow:
|
|
1059
|
+
return
|
|
1060
|
+
# --follow polls; each round asks only for lines since the previous one.
|
|
1061
|
+
next_tunnel_check = time.monotonic() + _TUNNEL_RECHECK_S
|
|
1062
|
+
offline = False
|
|
1063
|
+
try:
|
|
1064
|
+
while True:
|
|
1065
|
+
time.sleep(args.interval)
|
|
1066
|
+
if time.monotonic() >= next_tunnel_check:
|
|
1067
|
+
next_tunnel_check = time.monotonic() + _TUNNEL_RECHECK_S
|
|
1068
|
+
now_active = _tunnel_active(client, bot_id)
|
|
1069
|
+
if now_active is not None and now_active != tunnel:
|
|
1070
|
+
tunnel = now_active
|
|
1071
|
+
print(
|
|
1072
|
+
_dim(
|
|
1073
|
+
_TUNNEL_LOGS_NOTE
|
|
1074
|
+
if tunnel
|
|
1075
|
+
else "The tunnel closed: the deployed bot gets webhooks again."
|
|
1076
|
+
),
|
|
1077
|
+
file=sys.stderr,
|
|
1078
|
+
)
|
|
1079
|
+
# Microseconds: with whole seconds, every line in the cursor's second would print twice.
|
|
1080
|
+
since = cursor.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
|
1081
|
+
now = datetime.datetime.now(datetime.timezone.utc)
|
|
1082
|
+
try:
|
|
1083
|
+
new_logs = client.get_logs(bot_id, since=since)
|
|
1084
|
+
except ApiError as e:
|
|
1085
|
+
if e.status_code == 0 or e.status_code >= 500:
|
|
1086
|
+
if not offline:
|
|
1087
|
+
offline = True
|
|
1088
|
+
print(
|
|
1089
|
+
_dim("Connection lost - retrying..."), file=sys.stderr
|
|
1090
|
+
)
|
|
1091
|
+
continue # a dropped connection: keep following from the same point
|
|
1092
|
+
raise
|
|
1093
|
+
if offline:
|
|
1094
|
+
offline = False
|
|
1095
|
+
print(_dim("Reconnected."), file=sys.stderr)
|
|
1096
|
+
cursor = now
|
|
1097
|
+
if new_logs:
|
|
1098
|
+
print(new_logs, end="")
|
|
1099
|
+
except KeyboardInterrupt:
|
|
1100
|
+
pass
|
|
1101
|
+
|
|
1102
|
+
|
|
1103
|
+
def cmd_status(args: argparse.Namespace) -> None:
|
|
1104
|
+
project_dir = pathlib.Path.cwd()
|
|
1105
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1106
|
+
with _client_from_config() as client:
|
|
1107
|
+
status = client.get_status(bot_id)
|
|
1108
|
+
health = (
|
|
1109
|
+
client.get_health(bot_id)
|
|
1110
|
+
if status["running"] and status["status"] == "running"
|
|
1111
|
+
else None
|
|
1112
|
+
)
|
|
1113
|
+
restarts = status["restart_count"]
|
|
1114
|
+
restarts_text = f"{restarts} restart{'' if restarts == 1 else 's'} since deploy"
|
|
1115
|
+
if status["status"] == "restarting":
|
|
1116
|
+
state = "🔴 crashing and restarting"
|
|
1117
|
+
elif status["running"]:
|
|
1118
|
+
up = (
|
|
1119
|
+
f" for {_compact_duration(_seconds_since(status['started_at']))}"
|
|
1120
|
+
if status.get("started_at")
|
|
1121
|
+
else ""
|
|
1122
|
+
)
|
|
1123
|
+
state = f"🟢 running{up}"
|
|
1124
|
+
else:
|
|
1125
|
+
state = "🔴 stopped"
|
|
1126
|
+
print(f"{state} · {restarts_text}")
|
|
1127
|
+
if status["status"] == "restarting":
|
|
1128
|
+
print(f"The bot keeps exiting - see why with `{PROG} logs`.")
|
|
1129
|
+
if health is not None:
|
|
1130
|
+
if health["healthy"]:
|
|
1131
|
+
print("🟢 responding")
|
|
1132
|
+
else:
|
|
1133
|
+
detail = (
|
|
1134
|
+
f" (HTTP {health['http_status']})"
|
|
1135
|
+
if health["http_status"] is not None
|
|
1136
|
+
else ""
|
|
1137
|
+
)
|
|
1138
|
+
print(f"🔴 not responding {health['reason']}{detail}")
|
|
1139
|
+
|
|
1140
|
+
|
|
1141
|
+
def _require_development(bot: dict) -> None:
|
|
1142
|
+
if bot.get("environment", "development") != "development":
|
|
1143
|
+
raise PywaCloudCLIError(
|
|
1144
|
+
f"{bot['name']!r} is in production and cannot be tunneled. "
|
|
1145
|
+
"Move it to development in the dashboard first."
|
|
1146
|
+
)
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
def _print_tunnel_banner(bot: dict, host: str, port: int) -> None:
|
|
1150
|
+
"""A clear banner distinguishing this from a normal local run, shared by both the foreground
|
|
1151
|
+
`cmd_tunnel` and the background `start_dev_tunnel` (`pywa dev --tunnel`). Names the bot
|
|
1152
|
+
(useful with multiple terminals open for different bots at once) and links straight to its
|
|
1153
|
+
dashboard overview page."""
|
|
1154
|
+
dashboard_url = config.DASHBOARD_URL.rstrip("/") + f"/bots/{bot['id']}"
|
|
1155
|
+
print(
|
|
1156
|
+
f"Tunneling {bot['name']!r} to {pywa_tunnel.local_base_url(host, port)} - the deployed bot "
|
|
1157
|
+
"gets no webhooks until you stop (Ctrl+C)."
|
|
1158
|
+
)
|
|
1159
|
+
print(f"Dashboard: {dashboard_url}\n")
|
|
1160
|
+
|
|
1161
|
+
|
|
1162
|
+
def cmd_tunnel(args: argparse.Namespace) -> None:
|
|
1163
|
+
"""Relays this bot's inbound webhook traffic to a local process instead of its deployed
|
|
1164
|
+
bot, for developing against real Meta webhooks without a separate tunnel tool or
|
|
1165
|
+
repointing the callback URL. Only active while this command runs; Ctrl+C (or a disconnect) hands
|
|
1166
|
+
webhooks straight back to the deployed bot."""
|
|
1167
|
+
project_dir = pathlib.Path.cwd()
|
|
1168
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1169
|
+
cfg = _require_config()
|
|
1170
|
+
with _client_from_config() as client:
|
|
1171
|
+
bot = client.get_bot(bot_id)
|
|
1172
|
+
_require_development(bot)
|
|
1173
|
+
_print_tunnel_banner(bot, args.host, args.port)
|
|
1174
|
+
try:
|
|
1175
|
+
pywa_tunnel.run_sync(cfg.token, bot_id, args.port, host=args.host)
|
|
1176
|
+
except KeyboardInterrupt:
|
|
1177
|
+
print("\nTunnel closed.")
|
|
1178
|
+
except RuntimeError as e:
|
|
1179
|
+
raise PywaCloudCLIError(str(e)) from None
|
|
1180
|
+
|
|
1181
|
+
|
|
1182
|
+
def _confirm_live_tunnel(bot: dict) -> bool:
|
|
1183
|
+
"""`dev --tunnel` sends a bot's real WhatsApp messages to this machine and starts it with the bot's token and
|
|
1184
|
+
secrets, so an interactive run says so and asks first (Enter continues: only a development bot can be tunnelled).
|
|
1185
|
+
A run with no terminal to ask on (a script) is told once and goes ahead: whoever wrote that script chose it."""
|
|
1186
|
+
print(
|
|
1187
|
+
f"Tunnel for {bot['name']!r}:\n"
|
|
1188
|
+
" - its WhatsApp messages come to this machine instead of the deployed bot, until you press Ctrl+C\n"
|
|
1189
|
+
" - your code runs with the bot's real WhatsApp token and env vars, so what it sends reaches real people"
|
|
1190
|
+
)
|
|
1191
|
+
if not sys.stdin.isatty():
|
|
1192
|
+
return True
|
|
1193
|
+
return _confirm("Start the tunnel?")
|
|
1194
|
+
|
|
1195
|
+
|
|
1196
|
+
def start_dev_tunnel(
|
|
1197
|
+
project_dir: pathlib.Path,
|
|
1198
|
+
bot_id: str | None,
|
|
1199
|
+
port: int,
|
|
1200
|
+
host: str = "127.0.0.1",
|
|
1201
|
+
inject_env: bool = False,
|
|
1202
|
+
) -> threading.Thread:
|
|
1203
|
+
"""What `pywa dev --tunnel` calls: the same relay as `cmd_tunnel`, on a background thread, because
|
|
1204
|
+
`pywa dev` needs the main thread for its own server.
|
|
1205
|
+
|
|
1206
|
+
Anything that can fail up front (not logged in, no bot) raises here, before the thread starts.
|
|
1207
|
+
|
|
1208
|
+
It also loads the credentials Pywa Cloud generated for the bot (`PYWA_TOKEN`, `PYWA_PHONE_ID`, ...) into this
|
|
1209
|
+
process before returning: without them the relayed bot could not reply, and the owner has no other copy. They
|
|
1210
|
+
replace whatever is set. The bot's own env vars and secrets are loaded only with `inject_env=True`, and then
|
|
1211
|
+
never replace a value that is already set, so a local `.env` can still point at a local database.
|
|
1212
|
+
|
|
1213
|
+
It asks for confirmation first (`_confirm_live_tunnel`)."""
|
|
1214
|
+
resolved_bot_id = _resolve_bot_id(bot_id, project_dir)
|
|
1215
|
+
cfg = _require_config()
|
|
1216
|
+
with _client_from_config() as client:
|
|
1217
|
+
bot = client.get_bot(resolved_bot_id)
|
|
1218
|
+
_require_development(bot)
|
|
1219
|
+
if not _confirm_live_tunnel(bot):
|
|
1220
|
+
raise PywaCloudCLIError("Cancelled - nothing changed.")
|
|
1221
|
+
try:
|
|
1222
|
+
credentials = client.get_dev_credentials(resolved_bot_id)
|
|
1223
|
+
except ApiError as e:
|
|
1224
|
+
if e.status_code == 404:
|
|
1225
|
+
raise PywaCloudCLIError(
|
|
1226
|
+
f"{bot['name']!r} has no WhatsApp number connected yet - connect one first."
|
|
1227
|
+
) from None
|
|
1228
|
+
raise
|
|
1229
|
+
whatsapp = credentials["credentials"]
|
|
1230
|
+
own = credentials["env"] if inject_env else {}
|
|
1231
|
+
os.environ.update(whatsapp)
|
|
1232
|
+
kept_local = sorted(k for k in own if k in os.environ)
|
|
1233
|
+
for key, value in own.items():
|
|
1234
|
+
os.environ.setdefault(key, value)
|
|
1235
|
+
print(f"Injected live WhatsApp credentials: {', '.join(sorted(whatsapp))}.")
|
|
1236
|
+
if own:
|
|
1237
|
+
print(
|
|
1238
|
+
f"Injected env vars from Pywa Cloud: {', '.join(sorted(set(own) - set(kept_local)))}."
|
|
1239
|
+
)
|
|
1240
|
+
if kept_local:
|
|
1241
|
+
print(f"Kept your local value for: {', '.join(kept_local)}.")
|
|
1242
|
+
|
|
1243
|
+
def _run() -> None:
|
|
1244
|
+
try:
|
|
1245
|
+
pywa_tunnel.run_sync(cfg.token, resolved_bot_id, port, host=host)
|
|
1246
|
+
except RuntimeError as e:
|
|
1247
|
+
print(f"❌ Pywa Cloud tunnel stopped: {e}")
|
|
1248
|
+
|
|
1249
|
+
_print_tunnel_banner(bot, host, port)
|
|
1250
|
+
thread = threading.Thread(target=_run, name="pywa-cloud-tunnel", daemon=True)
|
|
1251
|
+
thread.start()
|
|
1252
|
+
return thread
|
|
1253
|
+
|
|
1254
|
+
|
|
1255
|
+
def _open_connect_url(page_url: str, expires_at: str) -> None:
|
|
1256
|
+
# `audience=cli` makes the page end with "return to the terminal".
|
|
1257
|
+
if not page_url.startswith(("http://", "https://")):
|
|
1258
|
+
page_url = config.API_URL.rstrip("/") + page_url
|
|
1259
|
+
url = page_url + "?audience=cli"
|
|
1260
|
+
print(f"To connect a WhatsApp Business Account, open:\n\n {url}\n")
|
|
1261
|
+
try:
|
|
1262
|
+
opened = webbrowser.open(url)
|
|
1263
|
+
except webbrowser.Error:
|
|
1264
|
+
opened = False
|
|
1265
|
+
if not opened:
|
|
1266
|
+
print("(couldn't open a browser automatically - visit the link above manually)")
|
|
1267
|
+
print(f"This link works once and expires {_relative(expires_at)}.\n")
|
|
1268
|
+
|
|
1269
|
+
|
|
1270
|
+
def _wait_for_new_connection(
|
|
1271
|
+
client, team_id: str, known_ids: set[str], timeout: float = 600.0
|
|
1272
|
+
) -> dict:
|
|
1273
|
+
deadline = time.monotonic() + timeout
|
|
1274
|
+
print("Waiting for you to finish in the browser (Ctrl+C to cancel)", end="")
|
|
1275
|
+
sys.stdout.flush()
|
|
1276
|
+
try:
|
|
1277
|
+
while time.monotonic() < deadline:
|
|
1278
|
+
time.sleep(3)
|
|
1279
|
+
print(".", end="")
|
|
1280
|
+
sys.stdout.flush()
|
|
1281
|
+
connections = client.list_waba_connections(team_id)
|
|
1282
|
+
new = [c for c in connections if c["id"] not in known_ids]
|
|
1283
|
+
if new:
|
|
1284
|
+
print()
|
|
1285
|
+
return new[0]
|
|
1286
|
+
except KeyboardInterrupt:
|
|
1287
|
+
print()
|
|
1288
|
+
raise PywaCloudCLIError("Cancelled.") from None
|
|
1289
|
+
print()
|
|
1290
|
+
raise PywaCloudCLIError(
|
|
1291
|
+
"Timed out waiting for the WhatsApp connection to complete."
|
|
1292
|
+
)
|
|
1293
|
+
|
|
1294
|
+
|
|
1295
|
+
def _describe_phone(n: dict) -> str:
|
|
1296
|
+
"""One picker line: number, verified name, and anything that affects whether it can actually
|
|
1297
|
+
send (a non-CONNECTED status or a poor quality rating), plus which bot already holds it."""
|
|
1298
|
+
parts = [n.get("display_phone_number") or n["id"]]
|
|
1299
|
+
if n.get("verified_name"):
|
|
1300
|
+
parts.append(f"- {n['verified_name']}")
|
|
1301
|
+
flags = []
|
|
1302
|
+
if n.get("status") == "PENDING":
|
|
1303
|
+
flags.append("not verified yet")
|
|
1304
|
+
elif n.get("status") and n["status"] != "CONNECTED":
|
|
1305
|
+
flags.append(f"status {n['status'].lower()}")
|
|
1306
|
+
if n.get("quality_rating") in ("YELLOW", "RED"):
|
|
1307
|
+
flags.append(f"quality {n['quality_rating'].lower()}")
|
|
1308
|
+
if flags:
|
|
1309
|
+
parts.append(f"[{', '.join(flags)}]")
|
|
1310
|
+
if n.get("assigned_bot_id"):
|
|
1311
|
+
parts.append(f"(in use by {n['assigned_bot_name']!r})")
|
|
1312
|
+
return " ".join(parts)
|
|
1313
|
+
|
|
1314
|
+
|
|
1315
|
+
def _resolve_bot_for_connect(
|
|
1316
|
+
client: PywaCloudClient, bot_id: str | None, project_dir: pathlib.Path
|
|
1317
|
+
) -> str:
|
|
1318
|
+
"""Like `_resolve_bot_id`, but in a terminal a missing bot isn't a dead end: offer to pick or
|
|
1319
|
+
create one (and link this directory to it) so `connect` works as the very first command."""
|
|
1320
|
+
try:
|
|
1321
|
+
return _resolve_bot_id(bot_id, project_dir)
|
|
1322
|
+
except PywaCloudCLIError:
|
|
1323
|
+
resolved, _ = _interactive_pick_or_create_bot(client, project_dir)
|
|
1324
|
+
if link.load(project_dir) is None:
|
|
1325
|
+
link.save(project_dir, link.Link(bot_id=resolved))
|
|
1326
|
+
print(f"✅ Linked {project_dir}")
|
|
1327
|
+
return resolved
|
|
1328
|
+
|
|
1329
|
+
|
|
1330
|
+
def _describe_connection(c: dict) -> str:
|
|
1331
|
+
label = (
|
|
1332
|
+
f"{c['name']} ({c['waba_id']})"
|
|
1333
|
+
if c.get("name")
|
|
1334
|
+
else f"WhatsApp account {c['waba_id']}"
|
|
1335
|
+
)
|
|
1336
|
+
how = {"manual": "your own token", "embedded_signup": "Meta sign-up"}.get(
|
|
1337
|
+
c.get("source"), c.get("source") or ""
|
|
1338
|
+
)
|
|
1339
|
+
state = "" if c.get("status") == "active" else f", {c['status']}"
|
|
1340
|
+
return f"{label} [{how}{state}]" if how or state else label
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def _connect_whatsapp(
|
|
1344
|
+
client: PywaCloudClient, bot: dict, announce_next: bool = False
|
|
1345
|
+
) -> None:
|
|
1346
|
+
"""The interactive steps of connecting a number, asking only what cannot be decided: a team runs Meta's Embedded
|
|
1347
|
+
Signup popup once per WABA and reuses it for every bot, so a team's only active WABA is used without asking, and so
|
|
1348
|
+
is a WABA's only phone number. Needs a terminal (a browser step and, sometimes, a picker)."""
|
|
1349
|
+
bot_id, team_id = bot["id"], bot["team_id"]
|
|
1350
|
+
connections = client.list_waba_connections(team_id)
|
|
1351
|
+
|
|
1352
|
+
connection = None
|
|
1353
|
+
if len(connections) == 1 and connections[0]["status"] == "active":
|
|
1354
|
+
connection = connections[0]
|
|
1355
|
+
print(
|
|
1356
|
+
f"Using your WhatsApp Business Account {_describe_connection(connection)}"
|
|
1357
|
+
)
|
|
1358
|
+
elif connections:
|
|
1359
|
+
options = [_describe_connection(c) for c in connections]
|
|
1360
|
+
options.append("Connect a different WhatsApp Business Account")
|
|
1361
|
+
choice = _choose("Which WhatsApp Business Account?", options)
|
|
1362
|
+
if choice < len(connections):
|
|
1363
|
+
connection = connections[choice]
|
|
1364
|
+
|
|
1365
|
+
if connection is None:
|
|
1366
|
+
known_ids = {c["id"] for c in connections}
|
|
1367
|
+
session = client.start_connect_session(team_id)
|
|
1368
|
+
_open_connect_url(session["page_url"], session["expires_at"])
|
|
1369
|
+
connection = _wait_for_new_connection(client, team_id, known_ids)
|
|
1370
|
+
print(f"✅ Connected WhatsApp Business Account {connection['waba_id']!r}\n")
|
|
1371
|
+
|
|
1372
|
+
numbers = client.list_connection_phone_numbers(team_id, connection["id"])
|
|
1373
|
+
if not numbers:
|
|
1374
|
+
raise PywaCloudCLIError(
|
|
1375
|
+
f"This WhatsApp Business Account ({connection['waba_id']}) has no phone numbers yet. Add one in Meta "
|
|
1376
|
+
f"Business Manager, then run `{PROG} connect` again."
|
|
1377
|
+
)
|
|
1378
|
+
# Free numbers first, and the cursor default is the first of them - Enter should never
|
|
1379
|
+
# land on taking a number away from another bot.
|
|
1380
|
+
numbers.sort(
|
|
1381
|
+
key=lambda n: (bool(n["assigned_bot_id"]), n.get("status") == "PENDING")
|
|
1382
|
+
)
|
|
1383
|
+
if len(numbers) == 1:
|
|
1384
|
+
phone = numbers[0]
|
|
1385
|
+
print(f"Using the only phone number: {_describe_phone(phone)}")
|
|
1386
|
+
if phone["assigned_bot_id"] == bot_id:
|
|
1387
|
+
print(f"✅ It is already assigned to {bot['name']!r}.")
|
|
1388
|
+
return
|
|
1389
|
+
else:
|
|
1390
|
+
phone = numbers[
|
|
1391
|
+
_choose(
|
|
1392
|
+
"Which phone number should this bot use?",
|
|
1393
|
+
[_describe_phone(n) for n in numbers],
|
|
1394
|
+
)
|
|
1395
|
+
]
|
|
1396
|
+
taken_by_other = phone["assigned_bot_id"] not in (None, bot_id)
|
|
1397
|
+
if taken_by_other and not _confirm(
|
|
1398
|
+
f"{phone['display_phone_number'] or phone['id']} is used by "
|
|
1399
|
+
f"{phone['assigned_bot_name']!r}. Move it to {bot['name']!r}? "
|
|
1400
|
+
"That bot will stop receiving messages.",
|
|
1401
|
+
default=False,
|
|
1402
|
+
):
|
|
1403
|
+
raise PywaCloudCLIError("Cancelled - nothing changed.")
|
|
1404
|
+
|
|
1405
|
+
result = client.assign_phone(bot_id, connection["id"], phone["id"])
|
|
1406
|
+
print(
|
|
1407
|
+
f"✅ Assigned {phone.get('display_phone_number') or phone['id']} to {bot['name']!r}."
|
|
1408
|
+
)
|
|
1409
|
+
if result.get("webhook_error"):
|
|
1410
|
+
_warn(
|
|
1411
|
+
f"Meta did not accept the bot's webhook ({result['webhook_error']}); messages will not reach it. "
|
|
1412
|
+
"Retry it from the bot's Settings in the dashboard."
|
|
1413
|
+
)
|
|
1414
|
+
if announce_next:
|
|
1415
|
+
print(f"\nNext: `{PROG} deploy` to ship your bot.")
|
|
1416
|
+
|
|
1417
|
+
|
|
1418
|
+
def cmd_connect(args: argparse.Namespace) -> None:
|
|
1419
|
+
"""Connects a WhatsApp number to a bot. Requires a real terminal - there is no non-interactive path for picking a
|
|
1420
|
+
WABA/phone by hand. `deploy` runs the same steps by itself when the bot has no number yet."""
|
|
1421
|
+
if not sys.stdin.isatty():
|
|
1422
|
+
raise PywaCloudCLIError(
|
|
1423
|
+
f"`{PROG} connect` is interactive only; connect a number from the dashboard instead."
|
|
1424
|
+
)
|
|
1425
|
+
project_dir = pathlib.Path.cwd()
|
|
1426
|
+
_require_config()
|
|
1427
|
+
with _client_from_config() as client:
|
|
1428
|
+
bot_id = _resolve_bot_for_connect(client, args.bot_id, project_dir)
|
|
1429
|
+
bot = client.get_bot(bot_id)
|
|
1430
|
+
current = client.connect_status(bot_id)
|
|
1431
|
+
if current["connected"]:
|
|
1432
|
+
shown = current.get("display_phone_number") or current["phone_id"]
|
|
1433
|
+
print(f"{bot['name']!r} already has the WhatsApp number {shown}.")
|
|
1434
|
+
if not _confirm("Replace it?", default=False):
|
|
1435
|
+
raise PywaCloudCLIError("Cancelled - nothing changed.")
|
|
1436
|
+
_connect_whatsapp(client, bot, announce_next=True)
|
|
1437
|
+
|
|
1438
|
+
|
|
1439
|
+
def cmd_connect_status(args: argparse.Namespace) -> None:
|
|
1440
|
+
project_dir = pathlib.Path.cwd()
|
|
1441
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1442
|
+
with _client_from_config() as client:
|
|
1443
|
+
conn = client.connect_status(bot_id)
|
|
1444
|
+
if conn["connected"]:
|
|
1445
|
+
shown = conn.get("display_phone_number") or conn["phone_id"]
|
|
1446
|
+
print(
|
|
1447
|
+
f"🟢 connected ({shown}, account {conn['waba_id']}, since {_relative(conn['connected_at'])})"
|
|
1448
|
+
)
|
|
1449
|
+
if conn.get("connection_status") and conn["connection_status"] != "active":
|
|
1450
|
+
detail = (
|
|
1451
|
+
f" - {conn['connection_status_detail']}"
|
|
1452
|
+
if conn.get("connection_status_detail")
|
|
1453
|
+
else ""
|
|
1454
|
+
)
|
|
1455
|
+
_warn(
|
|
1456
|
+
f"The WhatsApp account connection is {conn['connection_status']}{detail}"
|
|
1457
|
+
)
|
|
1458
|
+
if conn.get("webhook_error"):
|
|
1459
|
+
_warn(
|
|
1460
|
+
f"Messages are not reaching this bot: Meta did not accept its webhook ({conn['webhook_error']}). "
|
|
1461
|
+
"Retry it from the bot's Settings in the dashboard."
|
|
1462
|
+
)
|
|
1463
|
+
else:
|
|
1464
|
+
print(
|
|
1465
|
+
f"🔴 not connected (run `{PROG} connect` to link a WhatsApp Business Account)"
|
|
1466
|
+
)
|
|
1467
|
+
|
|
1468
|
+
|
|
1469
|
+
def cmd_stop(args: argparse.Namespace) -> None:
|
|
1470
|
+
project_dir = pathlib.Path.cwd()
|
|
1471
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1472
|
+
with _client_from_config() as client:
|
|
1473
|
+
client.stop(bot_id)
|
|
1474
|
+
label = _bot_label(client, bot_id)
|
|
1475
|
+
print(f"✅ Stopped {label} (it stays stopped until you run `{PROG} start`)")
|
|
1476
|
+
|
|
1477
|
+
|
|
1478
|
+
def cmd_start(args: argparse.Namespace) -> None:
|
|
1479
|
+
project_dir = pathlib.Path.cwd()
|
|
1480
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1481
|
+
with _client_from_config() as client:
|
|
1482
|
+
client.start(bot_id)
|
|
1483
|
+
label = _bot_label(client, bot_id)
|
|
1484
|
+
print(f"✅ Started {label}")
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
def cmd_restart(args: argparse.Namespace) -> None:
|
|
1488
|
+
project_dir = pathlib.Path.cwd()
|
|
1489
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1490
|
+
with _client_from_config() as client:
|
|
1491
|
+
client.restart(bot_id)
|
|
1492
|
+
label = _bot_label(client, bot_id)
|
|
1493
|
+
print(
|
|
1494
|
+
f"✅ Restarted {label} (no rebuild - code and env var changes need `{PROG} deploy` instead)"
|
|
1495
|
+
)
|
|
1496
|
+
|
|
1497
|
+
|
|
1498
|
+
def _deploy_source(d: dict) -> str:
|
|
1499
|
+
"""Where a deployment's code came from: "cli", "studio", or "github main@1a2b3c4"."""
|
|
1500
|
+
kind = d.get("source_kind") or "unknown"
|
|
1501
|
+
ref, sha = d.get("source_ref"), (d.get("source_sha") or "")[:7]
|
|
1502
|
+
detail = "@".join(part for part in (ref, sha) if part)
|
|
1503
|
+
return f"{kind} {detail}" if detail else kind
|
|
1504
|
+
|
|
1505
|
+
|
|
1506
|
+
def cmd_deployments_list(args: argparse.Namespace) -> None:
|
|
1507
|
+
project_dir = pathlib.Path.cwd()
|
|
1508
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1509
|
+
with _client_from_config() as client:
|
|
1510
|
+
deployments = client.list_deployments(bot_id, limit=args.limit, skip=args.skip)
|
|
1511
|
+
if not deployments:
|
|
1512
|
+
print("No more deployments." if args.skip else "No deployments yet.")
|
|
1513
|
+
return
|
|
1514
|
+
_print_table(
|
|
1515
|
+
["ID", "STATUS", "WHEN", "SOURCE"],
|
|
1516
|
+
[
|
|
1517
|
+
[d["id"], d["status"], _relative(d["created_at"]), _deploy_source(d)]
|
|
1518
|
+
for d in deployments
|
|
1519
|
+
],
|
|
1520
|
+
colors={1: lambda cell: _paint(cell, _STATUS_COLORS.get(cell.strip(), "0"))},
|
|
1521
|
+
)
|
|
1522
|
+
|
|
1523
|
+
|
|
1524
|
+
def cmd_deployments_get(args: argparse.Namespace) -> None:
|
|
1525
|
+
project_dir = pathlib.Path.cwd()
|
|
1526
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1527
|
+
with _client_from_config() as client:
|
|
1528
|
+
d = client.get_deployment(bot_id, args.deployment_id)
|
|
1529
|
+
created = (
|
|
1530
|
+
f"{_relative(d['created_at'])} {_dim('(' + _clock(d['created_at']) + ')')}"
|
|
1531
|
+
)
|
|
1532
|
+
print(f"{_paint('Deployment', '1')} {_dim(d['id'])}")
|
|
1533
|
+
rows = [
|
|
1534
|
+
("Bot", bot_id),
|
|
1535
|
+
("Status", _status(d["status"])),
|
|
1536
|
+
("Python", (d.get("python_version") or "unknown").split("-")[0]),
|
|
1537
|
+
("Pywa", d.get("pywa_version") or "unknown"),
|
|
1538
|
+
("Source", _deploy_source(d)),
|
|
1539
|
+
("Created", created),
|
|
1540
|
+
]
|
|
1541
|
+
if d["status"] == "failed":
|
|
1542
|
+
reason = d.get("failure_reason") or "see the deploy log"
|
|
1543
|
+
stage = _STAGE_LABELS.get(d.get("stage") or "")
|
|
1544
|
+
rows.append(("Failed", f"while {stage.lower()}: {reason}" if stage else reason))
|
|
1545
|
+
_print_rows(rows)
|
|
1546
|
+
print("\n" + _dim(f"Deploy log: {PROG} deployments log {d['id']}"))
|
|
1547
|
+
|
|
1548
|
+
|
|
1549
|
+
def cmd_deployments_log(args: argparse.Namespace) -> None:
|
|
1550
|
+
project_dir = pathlib.Path.cwd()
|
|
1551
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1552
|
+
with _client_from_config() as client:
|
|
1553
|
+
d = client.get_deployment(bot_id, args.deployment_id)
|
|
1554
|
+
log = d.get("build_log", "")
|
|
1555
|
+
print(log if log.strip() else "No deploy log recorded for this deployment.")
|
|
1556
|
+
|
|
1557
|
+
|
|
1558
|
+
def cmd_deployments_rollback(args: argparse.Namespace) -> None:
|
|
1559
|
+
project_dir = pathlib.Path.cwd()
|
|
1560
|
+
bot_id = _resolve_bot_id(args.bot_id, project_dir)
|
|
1561
|
+
with _client_from_config() as client:
|
|
1562
|
+
try:
|
|
1563
|
+
deployment = client.rollback_deployment(bot_id, args.deployment_id)
|
|
1564
|
+
except DeployFailed as e:
|
|
1565
|
+
_print_deploy_failure("Rollback", e)
|
|
1566
|
+
sys.exit(1)
|
|
1567
|
+
print(
|
|
1568
|
+
f"✅ Rolled back to deployment {args.deployment_id} (new deployment: {deployment['id']})"
|
|
1569
|
+
)
|
|
1570
|
+
|
|
1571
|
+
|
|
1572
|
+
def _print_new_token(token: str, bot_id: str) -> None:
|
|
1573
|
+
"""The token on a line of its own (easy to copy or capture), then once-only warning and how to use it."""
|
|
1574
|
+
print(f"\n{token}\n")
|
|
1575
|
+
_warn("Copy it now - it will not be shown again.")
|
|
1576
|
+
print(
|
|
1577
|
+
_dim(
|
|
1578
|
+
f"In CI, set PYWA_CLOUD_TOKEN to it and PYWA_CLOUD_BOT_ID to {bot_id}, then run `{PROG} deploy`."
|
|
1579
|
+
)
|
|
1580
|
+
)
|
|
1581
|
+
|
|
1582
|
+
|
|
1583
|
+
def cmd_deploy_tokens_create(args: argparse.Namespace) -> None:
|
|
1584
|
+
bot_id = _bot_id(args)
|
|
1585
|
+
with _client_from_config() as client:
|
|
1586
|
+
token = client.create_deploy_token(bot_id, args.name, args.expires_in_days)
|
|
1587
|
+
print(
|
|
1588
|
+
f"✅ Created deploy token {token['id']} (expires {_relative(token['expires_at'])})"
|
|
1589
|
+
)
|
|
1590
|
+
_print_new_token(token["token"], bot_id)
|
|
1591
|
+
|
|
1592
|
+
|
|
1593
|
+
def cmd_deploy_tokens_list(args: argparse.Namespace) -> None:
|
|
1594
|
+
bot_id = _bot_id(args)
|
|
1595
|
+
with _client_from_config() as client:
|
|
1596
|
+
tokens = client.list_deploy_tokens(bot_id)
|
|
1597
|
+
if not tokens:
|
|
1598
|
+
print("No deploy tokens yet.")
|
|
1599
|
+
return
|
|
1600
|
+
|
|
1601
|
+
def expiry(t: dict) -> str:
|
|
1602
|
+
when = _relative(t["expires_at"])
|
|
1603
|
+
return f"expired {when}" if _seconds_since(t["expires_at"]) > 0 else when
|
|
1604
|
+
|
|
1605
|
+
_print_table(
|
|
1606
|
+
["ID", "NAME", "EXPIRES"],
|
|
1607
|
+
[[t["id"], t["name"], expiry(t)] for t in tokens],
|
|
1608
|
+
colors={
|
|
1609
|
+
2: lambda cell: _paint(cell, "31") if cell.startswith("expired") else cell
|
|
1610
|
+
},
|
|
1611
|
+
)
|
|
1612
|
+
|
|
1613
|
+
|
|
1614
|
+
def cmd_deploy_tokens_delete(args: argparse.Namespace) -> None:
|
|
1615
|
+
bot_id = _bot_id(args)
|
|
1616
|
+
with _client_from_config() as client:
|
|
1617
|
+
client.delete_deploy_token(bot_id, args.token_id)
|
|
1618
|
+
print(f"✅ Deleted deploy token {args.token_id}")
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
def cmd_deploy_tokens_regenerate(args: argparse.Namespace) -> None:
|
|
1622
|
+
bot_id = _bot_id(args)
|
|
1623
|
+
with _client_from_config() as client:
|
|
1624
|
+
token = client.regenerate_deploy_token(
|
|
1625
|
+
bot_id, args.token_id, args.expires_in_days
|
|
1626
|
+
)
|
|
1627
|
+
print(f"✅ Regenerated (expires {_relative(token['expires_at'])})")
|
|
1628
|
+
_print_new_token(token["token"], bot_id)
|
|
1629
|
+
|
|
1630
|
+
|
|
1631
|
+
def _configure_login_parser(p: argparse.ArgumentParser) -> None:
|
|
1632
|
+
p.add_argument(
|
|
1633
|
+
"--token",
|
|
1634
|
+
default=None,
|
|
1635
|
+
help="Skip the interactive device-code flow and log in with an existing API token (CI)",
|
|
1636
|
+
)
|
|
1637
|
+
p.set_defaults(func=cmd_login)
|
|
1638
|
+
|
|
1639
|
+
|
|
1640
|
+
def _configure_logout_parser(p: argparse.ArgumentParser) -> None:
|
|
1641
|
+
p.set_defaults(func=cmd_logout)
|
|
1642
|
+
|
|
1643
|
+
|
|
1644
|
+
def _configure_whoami_parser(p: argparse.ArgumentParser) -> None:
|
|
1645
|
+
p.set_defaults(func=cmd_whoami)
|
|
1646
|
+
|
|
1647
|
+
|
|
1648
|
+
def _configure_deploy_parser(p: argparse.ArgumentParser) -> None:
|
|
1649
|
+
p.add_argument(
|
|
1650
|
+
"path", nargs="?", default=None, help="Defaults to the current directory"
|
|
1651
|
+
)
|
|
1652
|
+
p.add_argument(
|
|
1653
|
+
"--bot",
|
|
1654
|
+
dest="bot_id",
|
|
1655
|
+
default=None,
|
|
1656
|
+
help="Bot id (required on first deploy, unless linked)",
|
|
1657
|
+
)
|
|
1658
|
+
p.set_defaults(func=cmd_deploy)
|
|
1659
|
+
|
|
1660
|
+
|
|
1661
|
+
# Commands common enough to deserve a top-level shortcut on pywa's own CLI (`pywa deploy` instead
|
|
1662
|
+
# of `pywa cloud deploy`) - see `register_shallow()`. Each entry's configure function is the exact
|
|
1663
|
+
# same one `_add_commands()` uses for the `cloud` subcommand, so the two can never drift apart.
|
|
1664
|
+
_SHALLOW_COMMANDS: dict[str, tuple[str, Callable[[argparse.ArgumentParser], None]]] = {
|
|
1665
|
+
"login": (
|
|
1666
|
+
"Log in to Pywa Cloud (opens a browser device-code flow, or pass --token for CI)",
|
|
1667
|
+
_configure_login_parser,
|
|
1668
|
+
),
|
|
1669
|
+
"logout": ("Forget the stored Pywa Cloud login", _configure_logout_parser),
|
|
1670
|
+
"whoami": ("Show the current Pywa Cloud login", _configure_whoami_parser),
|
|
1671
|
+
"deploy": (
|
|
1672
|
+
"Build and deploy this folder to a bot on Pywa Cloud",
|
|
1673
|
+
_configure_deploy_parser,
|
|
1674
|
+
),
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
|
|
1678
|
+
def register_shallow(
|
|
1679
|
+
subparsers: argparse._SubParsersAction, names: Iterable[str] = ()
|
|
1680
|
+
) -> None:
|
|
1681
|
+
"""Adds top-level shortcuts (`pywa deploy` for `pywa cloud deploy`) to pywa's own parser.
|
|
1682
|
+
Call `register()` first so the help text uses the right command name."""
|
|
1683
|
+
for name in names:
|
|
1684
|
+
help_text, configure = _SHALLOW_COMMANDS[name]
|
|
1685
|
+
p = subparsers.add_parser(name, help=help_text)
|
|
1686
|
+
configure(p)
|
|
1687
|
+
|
|
1688
|
+
|
|
1689
|
+
def _add_commands(subparsers: argparse._SubParsersAction) -> None:
|
|
1690
|
+
"""Adds every subcommand to the given subparsers action."""
|
|
1691
|
+
login_p = subparsers.add_parser(
|
|
1692
|
+
"login",
|
|
1693
|
+
help="Log in (opens a browser device-code flow, or pass --token for CI)",
|
|
1694
|
+
)
|
|
1695
|
+
_configure_login_parser(login_p)
|
|
1696
|
+
|
|
1697
|
+
logout_p = subparsers.add_parser("logout", help="Forget the stored login")
|
|
1698
|
+
_configure_logout_parser(logout_p)
|
|
1699
|
+
|
|
1700
|
+
whoami_p = subparsers.add_parser("whoami", help="Show the current login")
|
|
1701
|
+
_configure_whoami_parser(whoami_p)
|
|
1702
|
+
|
|
1703
|
+
bots_p = subparsers.add_parser("bots", help="Manage bots")
|
|
1704
|
+
bots_sub = bots_p.add_subparsers(dest="bots_command", required=True)
|
|
1705
|
+
|
|
1706
|
+
bots_create_p = bots_sub.add_parser("create", help="Create a new bot")
|
|
1707
|
+
bots_create_p.add_argument("name", help="Display name")
|
|
1708
|
+
bots_create_p.add_argument(
|
|
1709
|
+
"--entrypoint-override",
|
|
1710
|
+
default=None,
|
|
1711
|
+
help="'module:var' to use instead of pywa's default discovery (see docs/guides/deploying)",
|
|
1712
|
+
)
|
|
1713
|
+
bots_create_p.add_argument(
|
|
1714
|
+
"--bot-directory",
|
|
1715
|
+
default=None,
|
|
1716
|
+
help="Relative subdirectory to deploy from, for a monorepo (default: the archive root)",
|
|
1717
|
+
)
|
|
1718
|
+
bots_create_p.add_argument(
|
|
1719
|
+
"--link",
|
|
1720
|
+
action=argparse.BooleanOptionalAction,
|
|
1721
|
+
default=None,
|
|
1722
|
+
help="Link the current directory to the new bot (default: ask, in a terminal)",
|
|
1723
|
+
)
|
|
1724
|
+
bots_create_p.set_defaults(func=cmd_bots_create)
|
|
1725
|
+
|
|
1726
|
+
bots_list_p = bots_sub.add_parser("list", help="List bots")
|
|
1727
|
+
bots_list_p.set_defaults(func=cmd_bots_list)
|
|
1728
|
+
|
|
1729
|
+
bots_get_p = bots_sub.add_parser("get", help="Show one bot")
|
|
1730
|
+
bots_get_p.add_argument(
|
|
1731
|
+
"bot_id", nargs="?", default=None, help="Bot id (defaults to the linked bot)"
|
|
1732
|
+
)
|
|
1733
|
+
bots_get_p.set_defaults(func=cmd_bots_get)
|
|
1734
|
+
|
|
1735
|
+
bots_set_entrypoint_p = bots_sub.add_parser(
|
|
1736
|
+
"set-entrypoint", help="Set or clear a bot's entrypoint override"
|
|
1737
|
+
)
|
|
1738
|
+
bots_set_entrypoint_p.add_argument(
|
|
1739
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1740
|
+
)
|
|
1741
|
+
bots_set_entrypoint_p.add_argument(
|
|
1742
|
+
"entrypoint",
|
|
1743
|
+
nargs="?",
|
|
1744
|
+
default=None,
|
|
1745
|
+
help="'module:var' (omit to clear, falling back to pywa's default discovery)",
|
|
1746
|
+
)
|
|
1747
|
+
bots_set_entrypoint_p.set_defaults(func=cmd_bots_set_entrypoint)
|
|
1748
|
+
|
|
1749
|
+
bots_set_directory_p = bots_sub.add_parser(
|
|
1750
|
+
"set-directory",
|
|
1751
|
+
help="Set or clear a bot's directory to deploy from (for a monorepo)",
|
|
1752
|
+
)
|
|
1753
|
+
bots_set_directory_p.add_argument(
|
|
1754
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1755
|
+
)
|
|
1756
|
+
bots_set_directory_p.add_argument(
|
|
1757
|
+
"directory",
|
|
1758
|
+
nargs="?",
|
|
1759
|
+
default=None,
|
|
1760
|
+
help="Relative subdirectory to deploy from (omit to clear, deploying from the archive root)",
|
|
1761
|
+
)
|
|
1762
|
+
bots_set_directory_p.set_defaults(func=cmd_bots_set_directory)
|
|
1763
|
+
|
|
1764
|
+
env_p = subparsers.add_parser(
|
|
1765
|
+
"env", help="Manage a bot's environment variables/secrets"
|
|
1766
|
+
)
|
|
1767
|
+
env_sub = env_p.add_subparsers(dest="env_command", required=True)
|
|
1768
|
+
|
|
1769
|
+
env_set_p = env_sub.add_parser("set", help="Create or update an env var")
|
|
1770
|
+
env_set_p.add_argument(
|
|
1771
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1772
|
+
)
|
|
1773
|
+
env_set_p.add_argument("key")
|
|
1774
|
+
env_set_p.add_argument(
|
|
1775
|
+
"value",
|
|
1776
|
+
nargs="?",
|
|
1777
|
+
help="Omit to be prompted (hidden) or to read it from stdin, keeping it out of shell history",
|
|
1778
|
+
)
|
|
1779
|
+
env_set_p.add_argument(
|
|
1780
|
+
"--secret",
|
|
1781
|
+
action="store_true",
|
|
1782
|
+
help="Mark as a secret (never readable back once set - fixed at creation)",
|
|
1783
|
+
)
|
|
1784
|
+
env_set_p.set_defaults(func=cmd_env_set)
|
|
1785
|
+
|
|
1786
|
+
env_get_p = env_sub.add_parser("get", help="Show one env var")
|
|
1787
|
+
env_get_p.add_argument(
|
|
1788
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1789
|
+
)
|
|
1790
|
+
env_get_p.add_argument("key")
|
|
1791
|
+
env_get_p.set_defaults(func=cmd_env_get)
|
|
1792
|
+
|
|
1793
|
+
env_list_p = env_sub.add_parser("list", help="List a bot's env vars")
|
|
1794
|
+
env_list_p.add_argument(
|
|
1795
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1796
|
+
)
|
|
1797
|
+
env_list_p.set_defaults(func=cmd_env_list)
|
|
1798
|
+
|
|
1799
|
+
env_delete_p = env_sub.add_parser("delete", help="Delete an env var")
|
|
1800
|
+
env_delete_p.add_argument(
|
|
1801
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1802
|
+
)
|
|
1803
|
+
env_delete_p.add_argument("key")
|
|
1804
|
+
env_delete_p.set_defaults(func=cmd_env_delete)
|
|
1805
|
+
|
|
1806
|
+
link_p = subparsers.add_parser(
|
|
1807
|
+
"link", help="Link a local directory to an existing bot"
|
|
1808
|
+
)
|
|
1809
|
+
link_p.add_argument("bot_id")
|
|
1810
|
+
link_p.add_argument(
|
|
1811
|
+
"path", nargs="?", default=None, help="Defaults to the current directory"
|
|
1812
|
+
)
|
|
1813
|
+
link_p.set_defaults(func=cmd_link)
|
|
1814
|
+
|
|
1815
|
+
unlink_p = subparsers.add_parser(
|
|
1816
|
+
"unlink", help="Unlink a local directory from its bot"
|
|
1817
|
+
)
|
|
1818
|
+
unlink_p.add_argument(
|
|
1819
|
+
"path", nargs="?", default=None, help="Defaults to the current directory"
|
|
1820
|
+
)
|
|
1821
|
+
unlink_p.set_defaults(func=cmd_unlink)
|
|
1822
|
+
|
|
1823
|
+
setup_ci_p = subparsers.add_parser(
|
|
1824
|
+
"setup-ci",
|
|
1825
|
+
help="Scaffold a GitHub Actions workflow that deploys this project on push",
|
|
1826
|
+
)
|
|
1827
|
+
setup_ci_p.add_argument(
|
|
1828
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1829
|
+
)
|
|
1830
|
+
setup_ci_p.add_argument(
|
|
1831
|
+
"--branch",
|
|
1832
|
+
default=None,
|
|
1833
|
+
help="Branch to deploy on push to (auto-detected if omitted)",
|
|
1834
|
+
)
|
|
1835
|
+
setup_ci_p.add_argument(
|
|
1836
|
+
"--force",
|
|
1837
|
+
action="store_true",
|
|
1838
|
+
help="Overwrite an existing .github/workflows/deploy.yml",
|
|
1839
|
+
)
|
|
1840
|
+
setup_ci_p.set_defaults(func=cmd_setup_ci)
|
|
1841
|
+
|
|
1842
|
+
deploy_p = subparsers.add_parser(
|
|
1843
|
+
"deploy", help="Build and deploy this folder to a bot"
|
|
1844
|
+
)
|
|
1845
|
+
_configure_deploy_parser(deploy_p)
|
|
1846
|
+
|
|
1847
|
+
logs_p = subparsers.add_parser("logs", help="Show a bot's running logs")
|
|
1848
|
+
logs_p.add_argument(
|
|
1849
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1850
|
+
)
|
|
1851
|
+
logs_p.add_argument(
|
|
1852
|
+
"--tail", type=_positive_int, default=200, help="Number of lines (default: 200)"
|
|
1853
|
+
)
|
|
1854
|
+
logs_p.add_argument(
|
|
1855
|
+
"--since",
|
|
1856
|
+
default=None,
|
|
1857
|
+
help="Only show lines from this RFC3339 timestamp on (e.g. 2024-01-01T00:00:00Z); "
|
|
1858
|
+
"ignored with --follow, which manages its own cursor",
|
|
1859
|
+
)
|
|
1860
|
+
logs_p.add_argument(
|
|
1861
|
+
"--follow",
|
|
1862
|
+
action="store_true",
|
|
1863
|
+
help="Keep polling for new log lines (Ctrl+C to stop)",
|
|
1864
|
+
)
|
|
1865
|
+
logs_p.add_argument(
|
|
1866
|
+
"--interval",
|
|
1867
|
+
type=float,
|
|
1868
|
+
default=2.0,
|
|
1869
|
+
help="Seconds between polls with --follow (default: 2.0)",
|
|
1870
|
+
)
|
|
1871
|
+
logs_p.set_defaults(func=cmd_logs)
|
|
1872
|
+
|
|
1873
|
+
status_p = subparsers.add_parser("status", help="Show a bot's live status")
|
|
1874
|
+
status_p.add_argument(
|
|
1875
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1876
|
+
)
|
|
1877
|
+
status_p.set_defaults(func=cmd_status)
|
|
1878
|
+
|
|
1879
|
+
tunnel_p = subparsers.add_parser(
|
|
1880
|
+
"tunnel", help="Relay a bot's webhook traffic to a locally-running process"
|
|
1881
|
+
)
|
|
1882
|
+
tunnel_p.add_argument(
|
|
1883
|
+
"--host",
|
|
1884
|
+
default="127.0.0.1",
|
|
1885
|
+
help="Host your bot's own server is bound to (default: 127.0.0.1)",
|
|
1886
|
+
)
|
|
1887
|
+
tunnel_p.add_argument(
|
|
1888
|
+
"--port",
|
|
1889
|
+
type=_port,
|
|
1890
|
+
default=8000,
|
|
1891
|
+
help="Local port your bot's own server is listening on (default: 8000)",
|
|
1892
|
+
)
|
|
1893
|
+
tunnel_p.add_argument(
|
|
1894
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1895
|
+
)
|
|
1896
|
+
tunnel_p.set_defaults(func=cmd_tunnel)
|
|
1897
|
+
|
|
1898
|
+
connect_p = subparsers.add_parser(
|
|
1899
|
+
"connect",
|
|
1900
|
+
help="Connect a WhatsApp Business Account to a bot (Meta Embedded Signup)",
|
|
1901
|
+
)
|
|
1902
|
+
connect_p.add_argument(
|
|
1903
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1904
|
+
)
|
|
1905
|
+
connect_p.set_defaults(func=cmd_connect)
|
|
1906
|
+
|
|
1907
|
+
connect_status_p = subparsers.add_parser(
|
|
1908
|
+
"connect-status", help="Show a bot's WhatsApp connection status"
|
|
1909
|
+
)
|
|
1910
|
+
connect_status_p.add_argument(
|
|
1911
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1912
|
+
)
|
|
1913
|
+
connect_status_p.set_defaults(func=cmd_connect_status)
|
|
1914
|
+
|
|
1915
|
+
stop_p = subparsers.add_parser("stop", help="Stop a running bot")
|
|
1916
|
+
stop_p.add_argument(
|
|
1917
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1918
|
+
)
|
|
1919
|
+
stop_p.set_defaults(func=cmd_stop)
|
|
1920
|
+
|
|
1921
|
+
start_p = subparsers.add_parser(
|
|
1922
|
+
"start", help="Resume a stopped bot, without rebuilding"
|
|
1923
|
+
)
|
|
1924
|
+
start_p.add_argument(
|
|
1925
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1926
|
+
)
|
|
1927
|
+
start_p.set_defaults(func=cmd_start)
|
|
1928
|
+
|
|
1929
|
+
restart_p = subparsers.add_parser(
|
|
1930
|
+
"restart", help="Restart a bot in place, without rebuilding"
|
|
1931
|
+
)
|
|
1932
|
+
restart_p.add_argument(
|
|
1933
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1934
|
+
)
|
|
1935
|
+
restart_p.set_defaults(func=cmd_restart)
|
|
1936
|
+
|
|
1937
|
+
deployments_p = subparsers.add_parser("deployments", help="View deployment history")
|
|
1938
|
+
deployments_sub = deployments_p.add_subparsers(
|
|
1939
|
+
dest="deployments_command", required=True
|
|
1940
|
+
)
|
|
1941
|
+
deployments_list_p = deployments_sub.add_parser(
|
|
1942
|
+
"list", help="List deployments for a bot"
|
|
1943
|
+
)
|
|
1944
|
+
deployments_list_p.add_argument(
|
|
1945
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1946
|
+
)
|
|
1947
|
+
deployments_list_p.add_argument(
|
|
1948
|
+
"--limit", type=int, default=50, help="How many to show, newest first (default 50, max 200)"
|
|
1949
|
+
)
|
|
1950
|
+
deployments_list_p.add_argument(
|
|
1951
|
+
"--skip", type=int, default=0, help="Skip this many of the newest, to see older ones"
|
|
1952
|
+
)
|
|
1953
|
+
deployments_list_p.set_defaults(func=cmd_deployments_list)
|
|
1954
|
+
|
|
1955
|
+
deployments_get_p = deployments_sub.add_parser("get", help="Get deployment details")
|
|
1956
|
+
deployments_get_p.add_argument("deployment_id", help="Deployment id")
|
|
1957
|
+
deployments_get_p.add_argument(
|
|
1958
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1959
|
+
)
|
|
1960
|
+
deployments_get_p.set_defaults(func=cmd_deployments_get)
|
|
1961
|
+
|
|
1962
|
+
deployments_log_p = deployments_sub.add_parser(
|
|
1963
|
+
"log", aliases=["logs"], help="View the deploy log of a deployment"
|
|
1964
|
+
)
|
|
1965
|
+
deployments_log_p.add_argument("deployment_id", help="Deployment id")
|
|
1966
|
+
deployments_log_p.add_argument(
|
|
1967
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1968
|
+
)
|
|
1969
|
+
deployments_log_p.set_defaults(func=cmd_deployments_log)
|
|
1970
|
+
|
|
1971
|
+
deployments_rollback_p = deployments_sub.add_parser(
|
|
1972
|
+
"rollback",
|
|
1973
|
+
help="Re-run a previous deployment's already-built image, no rebuild",
|
|
1974
|
+
)
|
|
1975
|
+
deployments_rollback_p.add_argument(
|
|
1976
|
+
"deployment_id", help="Deployment id to roll back to"
|
|
1977
|
+
)
|
|
1978
|
+
deployments_rollback_p.add_argument(
|
|
1979
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1980
|
+
)
|
|
1981
|
+
deployments_rollback_p.set_defaults(func=cmd_deployments_rollback)
|
|
1982
|
+
|
|
1983
|
+
tokens_p = subparsers.add_parser(
|
|
1984
|
+
"deploy-tokens", help="Manage a bot's deploy tokens"
|
|
1985
|
+
)
|
|
1986
|
+
tokens_sub = tokens_p.add_subparsers(dest="deploy_tokens_command", required=True)
|
|
1987
|
+
|
|
1988
|
+
tokens_create_p = tokens_sub.add_parser("create", help="Create a deploy token")
|
|
1989
|
+
tokens_create_p.add_argument(
|
|
1990
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
1991
|
+
)
|
|
1992
|
+
tokens_create_p.add_argument("name")
|
|
1993
|
+
tokens_create_p.add_argument(
|
|
1994
|
+
"--expires-in-days", type=int, default=90, help="1-365, default 90"
|
|
1995
|
+
)
|
|
1996
|
+
tokens_create_p.set_defaults(func=cmd_deploy_tokens_create)
|
|
1997
|
+
|
|
1998
|
+
tokens_list_p = tokens_sub.add_parser("list", help="List deploy tokens")
|
|
1999
|
+
tokens_list_p.add_argument(
|
|
2000
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
2001
|
+
)
|
|
2002
|
+
tokens_list_p.set_defaults(func=cmd_deploy_tokens_list)
|
|
2003
|
+
|
|
2004
|
+
tokens_delete_p = tokens_sub.add_parser("delete", help="Revoke a deploy token")
|
|
2005
|
+
tokens_delete_p.add_argument(
|
|
2006
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
2007
|
+
)
|
|
2008
|
+
tokens_delete_p.add_argument("token_id")
|
|
2009
|
+
tokens_delete_p.set_defaults(func=cmd_deploy_tokens_delete)
|
|
2010
|
+
|
|
2011
|
+
tokens_regen_p = tokens_sub.add_parser(
|
|
2012
|
+
"regenerate", help="Issue a new value for an existing deploy token"
|
|
2013
|
+
)
|
|
2014
|
+
tokens_regen_p.add_argument(
|
|
2015
|
+
"--bot", dest="bot_id", default=None, help="Bot id (defaults to the linked bot)"
|
|
2016
|
+
)
|
|
2017
|
+
tokens_regen_p.add_argument("token_id")
|
|
2018
|
+
tokens_regen_p.add_argument(
|
|
2019
|
+
"--expires-in-days", type=int, default=90, help="1-365, default 90"
|
|
2020
|
+
)
|
|
2021
|
+
tokens_regen_p.set_defaults(func=cmd_deploy_tokens_regenerate)
|
|
2022
|
+
|
|
2023
|
+
|
|
2024
|
+
def register(subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
|
|
2025
|
+
"""Mounts every command as `cloud <command>` on an existing subparsers action (this is how pywa's own CLI
|
|
2026
|
+
offers `pywa cloud deploy`), and sets `PROG` so hints say `pywa cloud login`."""
|
|
2027
|
+
global PROG
|
|
2028
|
+
cloud_parser = subparsers.add_parser(
|
|
2029
|
+
"cloud",
|
|
2030
|
+
help="Deploy and manage Pywa Cloud bots (build and run a pywa project)",
|
|
2031
|
+
)
|
|
2032
|
+
PROG = cloud_parser.prog
|
|
2033
|
+
_add_commands(cloud_parser.add_subparsers(dest="pywa_cloud_command", required=True))
|
|
2034
|
+
return cloud_parser
|
|
2035
|
+
|
|
2036
|
+
|
|
2037
|
+
def dispatch(args: argparse.Namespace) -> None:
|
|
2038
|
+
"""Runs a parsed command, turning errors into a one-line message and exit code 1 instead of a traceback."""
|
|
2039
|
+
if not sys.stdout.isatty():
|
|
2040
|
+
# Piped (CI, `| tee`): flush every line, or a long-running command (tunnel, logs --follow) shows nothing for minutes.
|
|
2041
|
+
reconfigure = getattr(sys.stdout, "reconfigure", None)
|
|
2042
|
+
if reconfigure is not None:
|
|
2043
|
+
reconfigure(line_buffering=True)
|
|
2044
|
+
try:
|
|
2045
|
+
args.func(args)
|
|
2046
|
+
except KeyboardInterrupt:
|
|
2047
|
+
print("\nCancelled.")
|
|
2048
|
+
sys.exit(130)
|
|
2049
|
+
except PywaCloudCLIError as e:
|
|
2050
|
+
print(f"❌ Error: {e}")
|
|
2051
|
+
sys.exit(1)
|
|
2052
|
+
except ApiError as e:
|
|
2053
|
+
print(f"❌ Error: {_api_error_message(e)}")
|
|
2054
|
+
sys.exit(1)
|
|
2055
|
+
|
|
2056
|
+
|
|
2057
|
+
def main(argv: list[str] | None = None) -> None:
|
|
2058
|
+
"""Entry point of the `pywa-cloud` executable. Works without pywa installed."""
|
|
2059
|
+
global PROG
|
|
2060
|
+
parser = argparse.ArgumentParser(
|
|
2061
|
+
prog="pywa-cloud", description="Deploy and manage Pywa Cloud bots."
|
|
2062
|
+
)
|
|
2063
|
+
PROG = parser.prog
|
|
2064
|
+
from pywa_cloud_cli import __version__
|
|
2065
|
+
|
|
2066
|
+
parser.add_argument(
|
|
2067
|
+
"--version", action="version", version=f"pywa-cloud {__version__}"
|
|
2068
|
+
)
|
|
2069
|
+
_add_commands(parser.add_subparsers(dest="pywa_cloud_command", required=True))
|
|
2070
|
+
dispatch(parser.parse_args(argv))
|