rtcloud 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rtcloud-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RT Cloud
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
rtcloud-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: rtcloud
3
+ Version: 1.0.0
4
+ Summary: Biblioteca oficial da RTCloud para Python: aplicações, arquivos, variáveis, snapshots, bancos e equipes pela API pública.
5
+ Author: RT Cloud
6
+ License: MIT
7
+ Project-URL: Homepage, https://rtcloud.com.br
8
+ Project-URL: Documentation, https://docs.rtcloud.com.br/sdk-python
9
+ Keywords: rtcloud,hospedagem,api,sdk,deploy,bot,discord
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Natural Language :: Portuguese (Brazilian)
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # rtcloud (Python)
21
+
22
+ Biblioteca oficial da **RTCloud** para Python. Controle aplicações, arquivos, variáveis, snapshots, bancos de dados e equipes pelo seu código — a mesma API pública que a CLI e a extensão do VS Code usam.
23
+
24
+ - Só biblioteca padrão: nenhuma dependência.
25
+ - Python 3.8 ou mais novo, com tipos.
26
+ - Repete sozinha quando a RTCloud está publicando uma atualização (503) e quando uma leitura bate no limite (429).
27
+
28
+ ## Instalação
29
+
30
+ ```bash
31
+ pip install rtcloud
32
+ ```
33
+
34
+ ## Primeiros passos
35
+
36
+ Gere uma chave no painel (**menu da conta → Chaves de API**) e guarde em `RTCLOUD_API_KEY`.
37
+
38
+ ```python
39
+ from rtcloud import RTCloud
40
+
41
+ rt = RTCloud() # lê RTCLOUD_API_KEY
42
+
43
+ for app in rt.apps.list():
44
+ print(app["name"], "no ar" if app["online"] else "parada")
45
+
46
+ rt.apps.restart("meu-bot") # aceita o id ou o nome exato
47
+ ```
48
+
49
+ ## Exemplos
50
+
51
+ ```python
52
+ # publicar uma versão nova
53
+ with open("projeto.zip", "rb") as f:
54
+ rt.apps.commit("minha-api", f.read())
55
+
56
+ # buscar texto em todos os arquivos
57
+ r = rt.files.search("meu-bot", "DISCORD_TOKEN", ext="py")
58
+ for f in r["files"]:
59
+ print(f["path"], f["matches"])
60
+
61
+ # trocar um trecho de arquivo e reiniciar
62
+ rt.files.edit("meu-bot", "config.py", [{"old": 'PREFIXO = "!"', "new": 'PREFIXO = "?"'}])
63
+ rt.apps.restart("meu-bot")
64
+
65
+ # variáveis: grava só as enviadas
66
+ rt.envs.set("minha-api", {"LOG_LEVEL": "debug"})
67
+
68
+ # restaurar o snapshot mais novo e esperar terminar
69
+ ultimo = rt.snapshots.list("minha-api")[0]
70
+ rt.snapshots.restore_and_wait("minha-api", ultimo["version"])
71
+ ```
72
+
73
+ ## Erros
74
+
75
+ ```python
76
+ from rtcloud import RTCloudError
77
+
78
+ try:
79
+ rt.apps.get("nao-existe")
80
+ except RTCloudError as e:
81
+ print(e.status, e.code, e.message) # 404 NOT_FOUND Aplicação não encontrada.
82
+ ```
83
+
84
+ ## Segurança
85
+
86
+ - A chave age como você: guarde em variável de ambiente, nunca no código.
87
+ - Arquivos de credenciais (`.env`, chaves, certificados) não passam pela API de arquivos — use `rt.envs`.
88
+
89
+ Documentação: <https://docs.rtcloud.com.br/sdk-python> · Licença MIT.
@@ -0,0 +1,70 @@
1
+ # rtcloud (Python)
2
+
3
+ Biblioteca oficial da **RTCloud** para Python. Controle aplicações, arquivos, variáveis, snapshots, bancos de dados e equipes pelo seu código — a mesma API pública que a CLI e a extensão do VS Code usam.
4
+
5
+ - Só biblioteca padrão: nenhuma dependência.
6
+ - Python 3.8 ou mais novo, com tipos.
7
+ - Repete sozinha quando a RTCloud está publicando uma atualização (503) e quando uma leitura bate no limite (429).
8
+
9
+ ## Instalação
10
+
11
+ ```bash
12
+ pip install rtcloud
13
+ ```
14
+
15
+ ## Primeiros passos
16
+
17
+ Gere uma chave no painel (**menu da conta → Chaves de API**) e guarde em `RTCLOUD_API_KEY`.
18
+
19
+ ```python
20
+ from rtcloud import RTCloud
21
+
22
+ rt = RTCloud() # lê RTCLOUD_API_KEY
23
+
24
+ for app in rt.apps.list():
25
+ print(app["name"], "no ar" if app["online"] else "parada")
26
+
27
+ rt.apps.restart("meu-bot") # aceita o id ou o nome exato
28
+ ```
29
+
30
+ ## Exemplos
31
+
32
+ ```python
33
+ # publicar uma versão nova
34
+ with open("projeto.zip", "rb") as f:
35
+ rt.apps.commit("minha-api", f.read())
36
+
37
+ # buscar texto em todos os arquivos
38
+ r = rt.files.search("meu-bot", "DISCORD_TOKEN", ext="py")
39
+ for f in r["files"]:
40
+ print(f["path"], f["matches"])
41
+
42
+ # trocar um trecho de arquivo e reiniciar
43
+ rt.files.edit("meu-bot", "config.py", [{"old": 'PREFIXO = "!"', "new": 'PREFIXO = "?"'}])
44
+ rt.apps.restart("meu-bot")
45
+
46
+ # variáveis: grava só as enviadas
47
+ rt.envs.set("minha-api", {"LOG_LEVEL": "debug"})
48
+
49
+ # restaurar o snapshot mais novo e esperar terminar
50
+ ultimo = rt.snapshots.list("minha-api")[0]
51
+ rt.snapshots.restore_and_wait("minha-api", ultimo["version"])
52
+ ```
53
+
54
+ ## Erros
55
+
56
+ ```python
57
+ from rtcloud import RTCloudError
58
+
59
+ try:
60
+ rt.apps.get("nao-existe")
61
+ except RTCloudError as e:
62
+ print(e.status, e.code, e.message) # 404 NOT_FOUND Aplicação não encontrada.
63
+ ```
64
+
65
+ ## Segurança
66
+
67
+ - A chave age como você: guarde em variável de ambiente, nunca no código.
68
+ - Arquivos de credenciais (`.env`, chaves, certificados) não passam pela API de arquivos — use `rt.envs`.
69
+
70
+ Documentação: <https://docs.rtcloud.com.br/sdk-python> · Licença MIT.
@@ -0,0 +1,31 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "rtcloud"
7
+ version = "1.0.0"
8
+ description = "Biblioteca oficial da RTCloud para Python: aplicações, arquivos, variáveis, snapshots, bancos e equipes pela API pública."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "RT Cloud" }]
13
+ keywords = ["rtcloud", "hospedagem", "api", "sdk", "deploy", "bot", "discord"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ "Natural Language :: Portuguese (Brazilian)",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://rtcloud.com.br"
25
+ Documentation = "https://docs.rtcloud.com.br/sdk-python"
26
+
27
+ [tool.setuptools]
28
+ packages = ["rtcloud"]
29
+
30
+ [tool.setuptools.package-data]
31
+ rtcloud = ["py.typed"]
@@ -0,0 +1,372 @@
1
+ """
2
+ rtcloud — a biblioteca oficial da RTCloud para Python.
3
+
4
+ from rtcloud import RTCloud
5
+ rt = RTCloud() # lê RTCLOUD_API_KEY
6
+ for app in rt.apps.list():
7
+ print(app["name"], "no ar" if app["online"] else "parada")
8
+
9
+ Fala com a API pública (/api/v1). A resposta da API vem num envelope
10
+ ``{"status", "response"}``; aqui você recebe só o ``response``. Erro vira
11
+ ``RTCloudError`` com ``status`` (HTTP), ``code`` e a mensagem da API.
12
+
13
+ Repetições automáticas (as mesmas da CLI):
14
+ * 503 "em atualização" (a RTCloud publicando uma versão nova): o pedido
15
+ nem chegou a rodar, então repete — inclusive POST — por até 5 minutos;
16
+ * 429 em leitura (GET): espera o tempo pedido (até 30 s), no máximo 2 vezes.
17
+
18
+ Só biblioteca padrão: nenhuma dependência para instalar.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import time
25
+ import uuid
26
+ import urllib.error
27
+ import urllib.parse
28
+ import urllib.request
29
+ from typing import Any, Dict, Iterable, List, Optional
30
+
31
+ __all__ = ["RTCloud", "RTCloudError", "__version__"]
32
+ __version__ = "1.0.0"
33
+
34
+ _BASE_PADRAO = "https://rtcloud.com.br/api/v1"
35
+ _ATUALIZACAO_MAX_S = 5 * 60
36
+
37
+
38
+ class RTCloudError(Exception):
39
+ """Erro devolvido pela API (status 0 = sem resposta)."""
40
+
41
+ def __init__(self, message: str, status: int = 0, code: str = "UNKNOWN", body: Any = None):
42
+ super().__init__(message)
43
+ self.message = message
44
+ self.status = status
45
+ self.code = code
46
+ self.body = body
47
+
48
+ def __repr__(self) -> str: # pragma: no cover - só exibição
49
+ return f"RTCloudError(status={self.status}, code={self.code!r}, message={self.message!r})"
50
+
51
+
52
+ def _q(**valores: Any) -> str:
53
+ pares = []
54
+ for k, v in valores.items():
55
+ if v is None or v == "" or v is False:
56
+ continue
57
+ pares.append((k, "1" if v is True else str(v)))
58
+ return ("?" + urllib.parse.urlencode(pares)) if pares else ""
59
+
60
+
61
+ def _id(v: str) -> str:
62
+ return urllib.parse.quote(str(v), safe="")
63
+
64
+
65
+ class _Area:
66
+ def __init__(self, cliente: "RTCloud"):
67
+ self._c = cliente
68
+
69
+
70
+ class _Conta(_Area):
71
+ def me(self) -> Dict[str, Any]:
72
+ """Perfil, plano e uso de memória da conta."""
73
+ return self._c.request("GET", "/users/me")
74
+
75
+ def teams(self) -> List[Dict[str, Any]]:
76
+ """Equipes que você criou ou de que participa."""
77
+ return self._c.request("GET", "/teams")
78
+
79
+
80
+ class _Plataforma(_Area):
81
+ def status(self) -> Dict[str, Any]:
82
+ return self._c.request("GET", "/service/status")
83
+
84
+
85
+ class _Apps(_Area):
86
+ def list(self) -> List[Dict[str, Any]]:
87
+ return self._c.request("GET", "/apps")
88
+
89
+ def status_all(self) -> List[Dict[str, Any]]:
90
+ return self._c.request("GET", "/apps/status")
91
+
92
+ def get(self, app: str) -> Dict[str, Any]:
93
+ return self._c.request("GET", f"/apps/{_id(app)}")
94
+
95
+ def status(self, app: str) -> Dict[str, Any]:
96
+ return self._c.request("GET", f"/apps/{_id(app)}/status")
97
+
98
+ def metrics(self, app: str, range: str = "24h") -> Dict[str, Any]: # noqa: A002 - nome da API
99
+ return self._c.request("GET", f"/apps/{_id(app)}/metrics{_q(range=range)}")
100
+
101
+ def logs(self, app: str) -> Dict[str, Any]:
102
+ return self._c.request("GET", f"/apps/{_id(app)}/logs")
103
+
104
+ def start(self, app: str) -> Dict[str, Any]:
105
+ return self._c.request("POST", f"/apps/{_id(app)}/start")
106
+
107
+ def stop(self, app: str) -> Dict[str, Any]:
108
+ return self._c.request("POST", f"/apps/{_id(app)}/stop")
109
+
110
+ def restart(self, app: str) -> Dict[str, Any]:
111
+ return self._c.request("POST", f"/apps/{_id(app)}/restart")
112
+
113
+ def deployments(self, app: str) -> List[Dict[str, Any]]:
114
+ return self._c.request("GET", f"/apps/{_id(app)}/deployments")
115
+
116
+ def commit(self, app: str, zip_bytes: bytes, filename: str = "projeto.zip") -> Dict[str, Any]:
117
+ """Publica uma versão nova a partir dos bytes de um .zip."""
118
+ return self._c.request("POST", f"/apps/{_id(app)}/commit", arquivo=("file", filename, zip_bytes), timeout=max(self._c.timeout, 600))
119
+
120
+ def delete(self, app: str, confirm: str) -> Dict[str, Any]:
121
+ """Exclui de vez. ``confirm`` precisa ser o nome exato da aplicação."""
122
+ return self._c.request("DELETE", f"/apps/{_id(app)}", json_body={"confirm": confirm})
123
+
124
+
125
+ class _Arquivos(_Area):
126
+ def list(self, app: str, path: str = "") -> Dict[str, Any]:
127
+ return self._c.request("GET", f"/apps/{_id(app)}/files{_q(path=path)}")
128
+
129
+ def read(self, app: str, path: str) -> Dict[str, Any]:
130
+ return self._c.request("GET", f"/apps/{_id(app)}/files/content{_q(path=path)}")
131
+
132
+ def write(self, app: str, path: str, content: str) -> Dict[str, Any]:
133
+ return self._c.request("PUT", f"/apps/{_id(app)}/files", json_body={"path": path, "content": content})
134
+
135
+ def edit(self, app: str, path: str, edits: Iterable[Dict[str, str]]) -> Dict[str, Any]:
136
+ """Troca trechos: ``edits=[{"old": "...", "new": "..."}]`` (cada old aparece uma vez)."""
137
+ return self._c.request("PATCH", f"/apps/{_id(app)}/files", json_body={"path": path, "edits": list(edits)})
138
+
139
+ def move(self, app: str, from_path: str, to_path: str) -> Dict[str, Any]:
140
+ return self._c.request("PATCH", f"/apps/{_id(app)}/files", json_body={"from": from_path, "to": to_path})
141
+
142
+ def delete(self, app: str, path: str) -> Dict[str, Any]:
143
+ return self._c.request("DELETE", f"/apps/{_id(app)}/files{_q(path=path)}")
144
+
145
+ def search(
146
+ self,
147
+ app: str,
148
+ q: str,
149
+ case_sensitive: bool = False,
150
+ whole_word: bool = False,
151
+ path: str = "",
152
+ ext: str = "",
153
+ ) -> Dict[str, Any]:
154
+ """Busca um texto em todos os arquivos da aplicação."""
155
+ return self._c.request("GET", f"/apps/{_id(app)}/files/search{_q(q=q, case=case_sensitive, word=whole_word, path=path, ext=ext)}")
156
+
157
+
158
+ class _Variaveis(_Area):
159
+ def list(self, app: str) -> Dict[str, str]:
160
+ return self._c.request("GET", f"/apps/{_id(app)}/envs")
161
+
162
+ def set(self, app: str, envs: Dict[str, str], restart: Optional[bool] = None) -> Dict[str, Any]:
163
+ """Grava só as chaves enviadas (as outras ficam como estão)."""
164
+ return self._c.request("POST", f"/apps/{_id(app)}/envs", json_body=_sem_none({"envs": envs, "restart": restart}))
165
+
166
+ def replace(self, app: str, envs: Dict[str, str], restart: Optional[bool] = None) -> Dict[str, Any]:
167
+ """Substitui TODAS — as que ficarem de fora são apagadas."""
168
+ return self._c.request("PUT", f"/apps/{_id(app)}/envs", json_body=_sem_none({"envs": envs, "restart": restart}))
169
+
170
+ def remove(self, app: str, keys: Iterable[str], restart: Optional[bool] = None) -> Dict[str, Any]:
171
+ return self._c.request("DELETE", f"/apps/{_id(app)}/envs", json_body=_sem_none({"keys": list(keys), "restart": restart}))
172
+
173
+
174
+ class _Snapshots(_Area):
175
+ def list(self, app: str) -> List[Dict[str, Any]]:
176
+ return self._c.request("GET", f"/apps/{_id(app)}/snapshots")
177
+
178
+ def create(self, app: str) -> Dict[str, Any]:
179
+ return self._c.request("POST", f"/apps/{_id(app)}/snapshots")
180
+
181
+ def restore(self, app: str, version: str) -> Dict[str, Any]:
182
+ return self._c.request("POST", f"/apps/{_id(app)}/snapshots/restore", json_body={"version": version})
183
+
184
+ def restore_status(self, app: str) -> Dict[str, Any]:
185
+ return self._c.request("GET", f"/apps/{_id(app)}/snapshots/restore")
186
+
187
+ def restore_and_wait(self, app: str, version: str, interval: float = 5.0, timeout: float = 900.0) -> Dict[str, Any]:
188
+ """Restaura e espera terminar, consultando o andamento."""
189
+ inicio = self.restore(app, version)
190
+ if not inicio.get("pending"):
191
+ return inicio
192
+ limite = time.monotonic() + timeout
193
+ while time.monotonic() < limite:
194
+ time.sleep(max(2.0, interval))
195
+ s = self.restore_status(app)
196
+ if s.get("state") == "success":
197
+ return s
198
+ if s.get("state") == "error":
199
+ raise RTCloudError(s.get("message") or "A restauração falhou.", 200, "RESTORE_FAILED", s)
200
+ raise RTCloudError("A restauração passou do tempo de espera; ela continua rodando.", 0, "RESTORE_TIMEOUT")
201
+
202
+
203
+ class _Monitor(_Area):
204
+ def get(self, app: str) -> Dict[str, Any]:
205
+ return self._c.request("GET", f"/apps/{_id(app)}/monitor")
206
+
207
+ def check(self, app: str) -> Dict[str, Any]:
208
+ return self._c.request("POST", f"/apps/{_id(app)}/monitor/check")
209
+
210
+
211
+ class _Rede(_Area):
212
+ def analytics(self, app: str, days: int = 1) -> Dict[str, Any]:
213
+ return self._c.request("GET", f"/apps/{_id(app)}/network/analytics{_q(days=days)}")
214
+
215
+ def errors(self, app: str, days: int = 1, include_4xx: bool = False) -> Dict[str, Any]:
216
+ return self._c.request("GET", f"/apps/{_id(app)}/network/errors{_q(days=days, include4xx=include_4xx)}")
217
+
218
+ def performance(self, app: str, days: int = 1) -> Dict[str, Any]:
219
+ return self._c.request("GET", f"/apps/{_id(app)}/network/performance{_q(days=days)}")
220
+
221
+ def purge_cache(self, app: str) -> Dict[str, Any]:
222
+ return self._c.request("POST", f"/apps/{_id(app)}/purge-cache")
223
+
224
+ def domain(self, app: str) -> Dict[str, Any]:
225
+ """O domínio próprio e os registros de DNS."""
226
+ return self._c.request("GET", f"/apps/{_id(app)}/domain")
227
+
228
+
229
+ class _Bancos(_Area):
230
+ def list(self) -> List[Dict[str, Any]]:
231
+ return self._c.request("GET", "/databases")
232
+
233
+ def get(self, db: str) -> Dict[str, Any]:
234
+ return self._c.request("GET", f"/databases/{_id(db)}")
235
+
236
+ def metrics(self, db: str) -> Dict[str, Any]:
237
+ return self._c.request("GET", f"/databases/{_id(db)}/metrics")
238
+
239
+ def start(self, db: str) -> Dict[str, Any]:
240
+ return self._c.request("POST", f"/databases/{_id(db)}/start")
241
+
242
+ def stop(self, db: str) -> Dict[str, Any]:
243
+ return self._c.request("POST", f"/databases/{_id(db)}/stop")
244
+
245
+ def restart(self, db: str) -> Dict[str, Any]:
246
+ return self._c.request("POST", f"/databases/{_id(db)}/restart")
247
+
248
+ def backups(self, db: str) -> List[Dict[str, Any]]:
249
+ return self._c.request("GET", f"/databases/{_id(db)}/backups")
250
+
251
+ def create_backup(self, db: str) -> Dict[str, Any]:
252
+ return self._c.request("POST", f"/databases/{_id(db)}/backups")
253
+
254
+ def certificate(self, db: str) -> Dict[str, Any]:
255
+ """O .pem do banco (precisa de chave de acesso total)."""
256
+ return self._c.request("GET", f"/databases/{_id(db)}/certificate")
257
+
258
+ def reset_credentials(self, db: str, type: str) -> Dict[str, Any]: # noqa: A002 - nome da API
259
+ """``type`` = "password" ou "certificate"."""
260
+ return self._c.request("POST", f"/databases/{_id(db)}/credentials/reset", json_body={"type": type})
261
+
262
+
263
+ def _sem_none(d: Dict[str, Any]) -> Dict[str, Any]:
264
+ return {k: v for k, v in d.items() if v is not None}
265
+
266
+
267
+ class RTCloud:
268
+ """Cliente da API pública da RTCloud."""
269
+
270
+ def __init__(
271
+ self,
272
+ api_key: Optional[str] = None,
273
+ base_url: Optional[str] = None,
274
+ timeout: float = 60.0,
275
+ user_agent: Optional[str] = None,
276
+ ):
277
+ chave = (api_key or os.environ.get("RTCLOUD_API_KEY") or "").strip()
278
+ if not chave:
279
+ raise RTCloudError(
280
+ "Informe a chave da API (api_key) ou defina RTCLOUD_API_KEY. Gere uma no painel: menu da conta → Chaves de API.",
281
+ code="MISSING_API_KEY",
282
+ )
283
+ if chave.startswith("rtm_"):
284
+ raise RTCloudError(
285
+ "Essa é uma chave do servidor MCP (rtm_). A biblioteca usa uma chave da API (rtc_), criada em Chaves de API.",
286
+ code="WRONG_KEY_TYPE",
287
+ )
288
+ self.api_key = chave
289
+ self.base_url = (base_url or os.environ.get("RTCLOUD_API_URL") or _BASE_PADRAO).rstrip("/")
290
+ self.timeout = float(timeout)
291
+ self.user_agent = user_agent or f"rtcloud-python/{__version__}"
292
+
293
+ self.account = _Conta(self)
294
+ self.platform = _Plataforma(self)
295
+ self.apps = _Apps(self)
296
+ self.files = _Arquivos(self)
297
+ self.envs = _Variaveis(self)
298
+ self.snapshots = _Snapshots(self)
299
+ self.monitor = _Monitor(self)
300
+ self.network = _Rede(self)
301
+ self.databases = _Bancos(self)
302
+
303
+ def request(
304
+ self,
305
+ method: str,
306
+ path: str,
307
+ json_body: Any = None,
308
+ arquivo: Optional[tuple] = None,
309
+ timeout: Optional[float] = None,
310
+ ) -> Any:
311
+ """Pedido cru à API (``path`` depois de /api/v1, começando com "/")."""
312
+ url = f"{self.base_url}{path}"
313
+ cabecalhos = {"Authorization": self.api_key, "Accept": "application/json", "User-Agent": self.user_agent}
314
+ corpo: Optional[bytes] = None
315
+ if arquivo is not None:
316
+ campo, nome, dados = arquivo
317
+ fronteira = f"----rtcloud{uuid.uuid4().hex}"
318
+ corpo = (
319
+ f"--{fronteira}\r\nContent-Disposition: form-data; name=\"{campo}\"; filename=\"{nome}\"\r\n"
320
+ f"Content-Type: application/zip\r\n\r\n"
321
+ ).encode() + bytes(dados) + f"\r\n--{fronteira}--\r\n".encode()
322
+ cabecalhos["Content-Type"] = f"multipart/form-data; boundary={fronteira}"
323
+ elif json_body is not None:
324
+ corpo = json.dumps(json_body, ensure_ascii=False).encode("utf-8")
325
+ cabecalhos["Content-Type"] = "application/json"
326
+
327
+ inicio = time.monotonic()
328
+ repeticoes_429 = 0
329
+ tentativa = 0
330
+ while True:
331
+ pedido = urllib.request.Request(url, data=corpo, method=method.upper(), headers=cabecalhos)
332
+ try:
333
+ with urllib.request.urlopen(pedido, timeout=timeout or self.timeout) as r:
334
+ status, texto, h = r.status, r.read().decode("utf-8", "replace"), r.headers
335
+ except urllib.error.HTTPError as e:
336
+ status, texto, h = e.code, e.read().decode("utf-8", "replace"), e.headers
337
+ e.close()
338
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
339
+ motivo = getattr(e, "reason", e)
340
+ raise RTCloudError(f"Sem conexão com a RTCloud: {motivo}", 0, "NETWORK_ERROR") from None
341
+
342
+ try:
343
+ dados = json.loads(texto) if texto else None
344
+ except ValueError:
345
+ dados = None
346
+
347
+ if 200 <= status < 300:
348
+ if isinstance(dados, dict) and dados.get("status") == "success":
349
+ return dados.get("response")
350
+ return dados if dados is not None else texto
351
+
352
+ mensagem = (dados or {}).get("message") if isinstance(dados, dict) else None
353
+ atualizando = status == 503 and (h.get("x-rtcloud-atualizando") or "atualiza" in (mensagem or texto).lower())
354
+ if atualizando and time.monotonic() - inicio < _ATUALIZACAO_MAX_S:
355
+ tentativa += 1
356
+ time.sleep(min(15.0, 3.0 * tentativa))
357
+ continue
358
+ if status == 429 and method.upper() == "GET" and repeticoes_429 < 2:
359
+ repeticoes_429 += 1
360
+ try:
361
+ espera = float(h.get("retry-after") or 5)
362
+ except ValueError:
363
+ espera = 5.0
364
+ time.sleep(min(30.0, max(1.0, espera)))
365
+ continue
366
+ codigo = (dados or {}).get("code") if isinstance(dados, dict) else None
367
+ raise RTCloudError(
368
+ mensagem or f"A API respondeu {status}.",
369
+ status,
370
+ codigo or ("UNAVAILABLE" if status >= 500 else "BAD_REQUEST"),
371
+ dados if dados is not None else texto,
372
+ )
File without changes
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: rtcloud
3
+ Version: 1.0.0
4
+ Summary: Biblioteca oficial da RTCloud para Python: aplicações, arquivos, variáveis, snapshots, bancos e equipes pela API pública.
5
+ Author: RT Cloud
6
+ License: MIT
7
+ Project-URL: Homepage, https://rtcloud.com.br
8
+ Project-URL: Documentation, https://docs.rtcloud.com.br/sdk-python
9
+ Keywords: rtcloud,hospedagem,api,sdk,deploy,bot,discord
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Natural Language :: Portuguese (Brazilian)
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # rtcloud (Python)
21
+
22
+ Biblioteca oficial da **RTCloud** para Python. Controle aplicações, arquivos, variáveis, snapshots, bancos de dados e equipes pelo seu código — a mesma API pública que a CLI e a extensão do VS Code usam.
23
+
24
+ - Só biblioteca padrão: nenhuma dependência.
25
+ - Python 3.8 ou mais novo, com tipos.
26
+ - Repete sozinha quando a RTCloud está publicando uma atualização (503) e quando uma leitura bate no limite (429).
27
+
28
+ ## Instalação
29
+
30
+ ```bash
31
+ pip install rtcloud
32
+ ```
33
+
34
+ ## Primeiros passos
35
+
36
+ Gere uma chave no painel (**menu da conta → Chaves de API**) e guarde em `RTCLOUD_API_KEY`.
37
+
38
+ ```python
39
+ from rtcloud import RTCloud
40
+
41
+ rt = RTCloud() # lê RTCLOUD_API_KEY
42
+
43
+ for app in rt.apps.list():
44
+ print(app["name"], "no ar" if app["online"] else "parada")
45
+
46
+ rt.apps.restart("meu-bot") # aceita o id ou o nome exato
47
+ ```
48
+
49
+ ## Exemplos
50
+
51
+ ```python
52
+ # publicar uma versão nova
53
+ with open("projeto.zip", "rb") as f:
54
+ rt.apps.commit("minha-api", f.read())
55
+
56
+ # buscar texto em todos os arquivos
57
+ r = rt.files.search("meu-bot", "DISCORD_TOKEN", ext="py")
58
+ for f in r["files"]:
59
+ print(f["path"], f["matches"])
60
+
61
+ # trocar um trecho de arquivo e reiniciar
62
+ rt.files.edit("meu-bot", "config.py", [{"old": 'PREFIXO = "!"', "new": 'PREFIXO = "?"'}])
63
+ rt.apps.restart("meu-bot")
64
+
65
+ # variáveis: grava só as enviadas
66
+ rt.envs.set("minha-api", {"LOG_LEVEL": "debug"})
67
+
68
+ # restaurar o snapshot mais novo e esperar terminar
69
+ ultimo = rt.snapshots.list("minha-api")[0]
70
+ rt.snapshots.restore_and_wait("minha-api", ultimo["version"])
71
+ ```
72
+
73
+ ## Erros
74
+
75
+ ```python
76
+ from rtcloud import RTCloudError
77
+
78
+ try:
79
+ rt.apps.get("nao-existe")
80
+ except RTCloudError as e:
81
+ print(e.status, e.code, e.message) # 404 NOT_FOUND Aplicação não encontrada.
82
+ ```
83
+
84
+ ## Segurança
85
+
86
+ - A chave age como você: guarde em variável de ambiente, nunca no código.
87
+ - Arquivos de credenciais (`.env`, chaves, certificados) não passam pela API de arquivos — use `rt.envs`.
88
+
89
+ Documentação: <https://docs.rtcloud.com.br/sdk-python> · Licença MIT.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ rtcloud/__init__.py
5
+ rtcloud/py.typed
6
+ rtcloud.egg-info/PKG-INFO
7
+ rtcloud.egg-info/SOURCES.txt
8
+ rtcloud.egg-info/dependency_links.txt
9
+ rtcloud.egg-info/top_level.txt
10
+ tests/test_rtcloud.py
@@ -0,0 +1 @@
1
+ rtcloud
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,146 @@
1
+ """Testes da biblioteca contra um servidor falso que imita a API v1.
2
+
3
+ python -m unittest discover -s tests
4
+ """
5
+ import json
6
+ import os
7
+ import sys
8
+ import threading
9
+ import unittest
10
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
11
+
12
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
13
+ from rtcloud import RTCloud, RTCloudError # noqa: E402
14
+
15
+ CHAVE = "rtc_teste_0123456789abcdefghij"
16
+ ESTADO = {"atualizando": 0, "limite": 0, "pedidos": []}
17
+
18
+
19
+ class Falso(BaseHTTPRequestHandler):
20
+ def log_message(self, *a): # silencioso
21
+ pass
22
+
23
+ def _responder(self, status, corpo, extra=None):
24
+ dados = json.dumps(corpo).encode()
25
+ self.send_response(status)
26
+ self.send_header("content-type", "application/json")
27
+ for k, v in (extra or {}).items():
28
+ self.send_header(k, v)
29
+ self.send_header("content-length", str(len(dados)))
30
+ self.end_headers()
31
+ self.wfile.write(dados)
32
+
33
+ def _ok(self, r):
34
+ self._responder(200, {"status": "success", "response": r})
35
+
36
+ def _erro(self, status, code, msg, extra=None):
37
+ self._responder(status, {"status": "error", "code": code, "message": msg}, extra)
38
+
39
+ def _tratar(self):
40
+ tamanho = int(self.headers.get("content-length") or 0)
41
+ corpo = self.rfile.read(tamanho) if tamanho else b""
42
+ caminho, _, busca = self.path.partition("?")
43
+ ESTADO["pedidos"].append((self.command, caminho, busca, corpo, self.headers.get("content-type", "")))
44
+ if self.headers.get("authorization") != CHAVE:
45
+ return self._erro(401, "ACCESS_DENIED", "Chave inválida.")
46
+ if caminho == "/api/v1/apps/atualizando/status" and ESTADO["atualizando"] > 0:
47
+ ESTADO["atualizando"] -= 1
48
+ return self._erro(503, "UNAVAILABLE", "A RTCloud está publicando uma atualização.", {"x-rtcloud-atualizando": "1"})
49
+ if caminho == "/api/v1/apps/limite/logs" and ESTADO["limite"] > 0:
50
+ ESTADO["limite"] -= 1
51
+ return self._erro(429, "RATE_LIMIT", "Muitas chamadas.", {"retry-after": "1"})
52
+ if caminho == "/api/v1/apps":
53
+ return self._ok([{"id": "a1", "name": "bot"}])
54
+ if caminho == "/api/v1/apps/a1/files/search":
55
+ return self._ok({"query": "TOKEN", "total": 1, "files": [], "busca": busca})
56
+ if caminho == "/api/v1/apps/a1/files" and self.command == "PATCH":
57
+ return self._ok({"recebido": json.loads(corpo)})
58
+ if caminho == "/api/v1/apps/a1" and self.command == "DELETE":
59
+ if json.loads(corpo or b"{}").get("confirm") == "bot":
60
+ return self._ok({"id": "a1", "deleted": True, "finishing": False})
61
+ return self._erro(400, "CONFIRMATION_REQUIRED", "Confirme.")
62
+ if caminho == "/api/v1/apps/a1/commit":
63
+ return self._ok({"multipart": "multipart/form-data" in self.headers.get("content-type", ""), "zip": b"PK" in corpo})
64
+ if caminho == "/api/v1/apps/a1/envs" and self.command == "POST":
65
+ return self._ok({"recebido": json.loads(corpo)})
66
+ if caminho == "/api/v1/apps/atualizando/status":
67
+ return self._ok({"online": True})
68
+ if caminho == "/api/v1/apps/limite/logs":
69
+ return self._ok({"logs": "ok"})
70
+ return self._erro(404, "NOT_FOUND", "Aplicação não encontrada.")
71
+
72
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = _tratar
73
+
74
+
75
+ class TestesDaBiblioteca(unittest.TestCase):
76
+ @classmethod
77
+ def setUpClass(cls):
78
+ cls.servidor = ThreadingHTTPServer(("127.0.0.1", 0), Falso)
79
+ threading.Thread(target=cls.servidor.serve_forever, daemon=True).start()
80
+ cls.base = f"http://127.0.0.1:{cls.servidor.server_address[1]}/api/v1"
81
+
82
+ @classmethod
83
+ def tearDownClass(cls):
84
+ cls.servidor.shutdown()
85
+
86
+ def cliente(self):
87
+ return RTCloud(api_key=CHAVE, base_url=self.base)
88
+
89
+ def test_sem_chave(self):
90
+ antes = os.environ.pop("RTCLOUD_API_KEY", None)
91
+ with self.assertRaises(RTCloudError) as c:
92
+ RTCloud(base_url=self.base)
93
+ self.assertEqual(c.exception.code, "MISSING_API_KEY")
94
+ if antes:
95
+ os.environ["RTCLOUD_API_KEY"] = antes
96
+
97
+ def test_chave_do_mcp(self):
98
+ with self.assertRaises(RTCloudError) as c:
99
+ RTCloud(api_key="rtm_x", base_url=self.base)
100
+ self.assertEqual(c.exception.code, "WRONG_KEY_TYPE")
101
+
102
+ def test_envelope(self):
103
+ self.assertEqual(self.cliente().apps.list(), [{"id": "a1", "name": "bot"}])
104
+
105
+ def test_erro_com_codigo(self):
106
+ with self.assertRaises(RTCloudError) as c:
107
+ self.cliente().apps.get("nao-existe")
108
+ self.assertEqual((c.exception.status, c.exception.code), (404, "NOT_FOUND"))
109
+
110
+ def test_busca(self):
111
+ r = self.cliente().files.search("a1", "TOKEN", case_sensitive=True, ext="js")
112
+ self.assertIn("q=TOKEN", r["busca"])
113
+ self.assertIn("case=1", r["busca"])
114
+ self.assertIn("ext=js", r["busca"])
115
+ self.assertNotIn("word=", r["busca"])
116
+
117
+ def test_editar_e_mover(self):
118
+ e = self.cliente().files.edit("a1", "a.py", [{"old": "x = 1", "new": "x = 2"}])
119
+ self.assertEqual(e["recebido"], {"path": "a.py", "edits": [{"old": "x = 1", "new": "x = 2"}]})
120
+ m = self.cliente().files.move("a1", "a.py", "b.py")
121
+ self.assertEqual(m["recebido"], {"from": "a.py", "to": "b.py"})
122
+
123
+ def test_excluir_confirma(self):
124
+ with self.assertRaises(RTCloudError):
125
+ self.cliente().apps.delete("a1", "errado")
126
+ self.assertTrue(self.cliente().apps.delete("a1", "bot")["deleted"])
127
+
128
+ def test_commit_multipart(self):
129
+ r = self.cliente().apps.commit("a1", b"PK\x03\x04conteudo")
130
+ self.assertEqual(r, {"multipart": True, "zip": True})
131
+
132
+ def test_variaveis_sem_restart_nulo(self):
133
+ r = self.cliente().envs.set("a1", {"LOG": "debug"})
134
+ self.assertEqual(r["recebido"], {"envs": {"LOG": "debug"}})
135
+
136
+ def test_503_de_atualizacao(self):
137
+ ESTADO["atualizando"] = 1
138
+ self.assertEqual(self.cliente().apps.status("atualizando"), {"online": True})
139
+
140
+ def test_429_em_leitura(self):
141
+ ESTADO["limite"] = 1
142
+ self.assertEqual(self.cliente().apps.logs("limite"), {"logs": "ok"})
143
+
144
+
145
+ if __name__ == "__main__":
146
+ unittest.main()