shade-plugins-telegram 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,276 @@
1
+ """O plugin ``telegram``: enviar mensagem e documento pela Bot API do Telegram, sob o contrato de
2
+ plugin do shade-sdk.
3
+
4
+ ```toml
5
+ [hosts]
6
+ permitidos = ["api.telegram.org"]
7
+
8
+ [credenciais]
9
+ nomes = ["TELEGRAM_BOT_TOKEN"]
10
+
11
+ [plugins]
12
+ telegram = "0.1.0"
13
+ ```
14
+
15
+ ```python
16
+ import shade_plugins_telegram as telegram
17
+
18
+ with item.efetivar("avisar o time"):
19
+ telegram.enviar_mensagem(config["telegram_chat"], f"Pedido {item['pedido']} conferido.")
20
+
21
+ with item.efetivar("mandar o comprovante"):
22
+ telegram.enviar_documento(config["telegram_chat"], "saida/comprovante.pdf", legenda="Pronto.")
23
+ ```
24
+
25
+ - **A API não reconhece repetição.** Não há chave de idempotência: um segundo ``POST`` é uma
26
+ segunda mensagem no chat. Por isso o plugin **nunca repete depois do despacho**, em nenhum
27
+ erro. Só a falha que prova que nada saiu (conexão recusada, nome que não resolve, rede
28
+ inalcançável) é tentada de novo, dentro do ``timeout=``. O ``timeout``, a conexão que cai, o
29
+ ``5xx`` e a resposta sem o identificador da mensagem são ``TelegramIncerto``: o item fica retido
30
+ para uma pessoa conferir no chat, e o "refazer" só depois de ela ver que a mensagem não chegou.
31
+ O 4xx é ``TelegramNaoSaiu``: a API recusou, nenhuma mensagem saiu.
32
+ - **Token só por** ``segredo()``: ``TELEGRAM_BOT_TOKEN`` (o do @BotFather). A Bot API o põe no
33
+ **caminho da URL**, então a URL é um segredo: ela só existe dentro do envio, e toda mensagem de
34
+ erro mostra o endpoint como ``/bot<token>/sendMessage``. Nunca vai a evento, log nem erro.
35
+ - **Enviar só dentro de** ``item.efetivar()`` (no ensaio não roda).
36
+ - **O que sai do evento e do erro:** a operação, o host, a duração e o status. Nunca o texto, o
37
+ ``chat_id`` (dado pessoal), o nome do arquivo nem o corpo da resposta; o erro da API chega só
38
+ pelo código numérico e por uma explicação escrita aqui.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import mimetypes
45
+ import os
46
+ import re
47
+ from pathlib import Path
48
+ from typing import Any
49
+
50
+ from shade_sdk.plugins import Plugin
51
+
52
+ from shade_plugins_telegram import _cliente
53
+ from shade_plugins_telegram._cliente import HOST, Prazo
54
+ from shade_plugins_telegram.erros import TelegramIncerto, TelegramNaoSaiu
55
+
56
+ __version__ = "0.1.0"
57
+
58
+ #: A credencial que o plugin lê (``[credenciais] nomes``).
59
+ TOKEN = "TELEGRAM_BOT_TOKEN"
60
+ #: O teto do texto de uma mensagem (a API recusa acima disto).
61
+ TEXTO_MAX = 4096
62
+ #: O teto da legenda de um documento.
63
+ LEGENDA_MAX = 1024
64
+ #: O teto de um documento enviado por bot.
65
+ DOCUMENTO_MAX = 50 * 1024 * 1024
66
+ _CONTROLE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
67
+ _CONTROLE_E_BARRAS = re.compile(r"[\x00-\x1f\x7f\"\\/]")
68
+ # O token vai no caminho da URL: só o que o BotFather emite (dígitos, ``:``, letras, ``_``, ``-``).
69
+ _TOKEN = re.compile(r"[A-Za-z0-9:_-]{8,200}")
70
+ _CHAT_NUMERICO = re.compile(r"-?[0-9]{1,20}")
71
+ _CHAT_PUBLICO = re.compile(r"@[A-Za-z][A-Za-z0-9_]{4,31}")
72
+
73
+ PLUGIN = Plugin(
74
+ "telegram",
75
+ __version__,
76
+ shade_sdk=">=0.22.1,<0.23",
77
+ dono="Equipe de integrações da ShadeOne",
78
+ hosts=[HOST],
79
+ credenciais=[TOKEN],
80
+ )
81
+
82
+ __all__ = [
83
+ "PLUGIN",
84
+ "TelegramIncerto",
85
+ "TelegramNaoSaiu",
86
+ "enviar_documento",
87
+ "enviar_mensagem",
88
+ ]
89
+
90
+
91
+ def _chat(chat_id: Any) -> int | str:
92
+ """O destino: o número do chat (``-100...`` nos grupos e canais) ou ``@canal_publico``."""
93
+ if isinstance(chat_id, bool):
94
+ raise ValueError("chat_id é o número do chat ou @canal")
95
+ if isinstance(chat_id, int):
96
+ return chat_id
97
+ if isinstance(chat_id, str):
98
+ if _CHAT_NUMERICO.fullmatch(chat_id):
99
+ return int(chat_id)
100
+ if _CHAT_PUBLICO.fullmatch(chat_id):
101
+ return chat_id
102
+ raise ValueError("chat_id é o número do chat (ex.: 123456789 ou -1001234567890) ou @canal")
103
+
104
+
105
+ def _utf8(valor: str, campo: str) -> str:
106
+ """Recusa o surrogate solitário: o erro de codificação do Python guardaria o texto inteiro."""
107
+ try:
108
+ valor.encode("utf-8")
109
+ valido = True
110
+ except UnicodeEncodeError:
111
+ valido = False
112
+ if not valido: # fora do ``except``: o erro de codificação não vira ``__context__``
113
+ raise ValueError(f"{campo} tem um caractere que não existe em UTF-8")
114
+ return valor
115
+
116
+
117
+ def _porta(porta: Any) -> int | None:
118
+ if porta is not None and (
119
+ not isinstance(porta, int) or isinstance(porta, bool) or not 0 < porta < 65536
120
+ ):
121
+ raise ValueError(f"porta é um número de 1 a 65535, não {porta!r}")
122
+ return porta
123
+
124
+
125
+ def _token(chamada: Any) -> str:
126
+ token = chamada.segredo(TOKEN)
127
+ if not isinstance(token, str) or not _TOKEN.fullmatch(token):
128
+ # Sem o valor na mensagem: ele vai no caminho da URL.
129
+ raise ValueError(f"{TOKEN} é o token do BotFather (letras, dígitos, ':', '_' e '-')")
130
+ return token
131
+
132
+
133
+ def _legenda(legenda: Any) -> str | None:
134
+ if legenda is None:
135
+ return None
136
+ if not isinstance(legenda, str) or not legenda.strip():
137
+ raise ValueError("legenda é um texto não vazio")
138
+ if len(legenda) > LEGENDA_MAX:
139
+ raise ValueError(f"legenda passa de {LEGENDA_MAX} caracteres")
140
+ if _CONTROLE.search(legenda):
141
+ raise ValueError("legenda não pode ter caractere de controle (fora quebra de linha e tab)")
142
+ return _utf8(legenda, "legenda")
143
+
144
+
145
+ def _arquivo_do_workdir(caminho: Any) -> Path:
146
+ if not isinstance(caminho, str | os.PathLike):
147
+ raise TypeError("documento é o caminho de um arquivo do diretório de trabalho")
148
+ relativo = Path(caminho)
149
+ raiz = Path.cwd().resolve()
150
+ completo = (raiz / relativo).resolve()
151
+ if relativo.is_absolute() or completo != raiz and raiz not in completo.parents:
152
+ raise ValueError("documento é um caminho dentro do diretório de trabalho")
153
+ if not completo.is_file():
154
+ raise FileNotFoundError("documento: não existe no diretório de trabalho")
155
+ return completo
156
+
157
+
158
+ def _nome_do_documento(nome: Any, padrao: str) -> str:
159
+ """O ``filename`` do multipart. Aspas, barra, barra invertida e controle são recusados, não
160
+ escapados à mão: o nome vai dentro de um cabeçalho entre aspas."""
161
+ escolhido = padrao if nome is None else nome
162
+ if not isinstance(escolhido, str) or not escolhido.strip():
163
+ raise ValueError("nome é o nome do arquivo no chat, não vazio")
164
+ if len(_utf8(escolhido, "nome").encode("utf-8")) > 200:
165
+ raise ValueError("nome passa de 200 bytes")
166
+ if _CONTROLE_E_BARRAS.search(escolhido):
167
+ raise ValueError("nome não pode ter aspas, barra, barra invertida nem controle")
168
+ return escolhido
169
+
170
+
171
+ @PLUGIN.efeito
172
+ def enviar_mensagem(
173
+ chamada: Any,
174
+ chat_id: int | str,
175
+ texto: str,
176
+ *,
177
+ previa_de_link: bool = False,
178
+ porta: int | None = None,
179
+ ) -> dict[str, int]:
180
+ """Envia uma mensagem de texto (até 4096 caracteres) ao chat ``chat_id`` (só dentro de
181
+ ``item.efetivar()``). O texto vai como texto puro, sem ``parse_mode``: ``*``, ``_`` e ``<``
182
+ não viram formatação. ``previa_de_link`` mostra a prévia do primeiro link. ``porta`` só serve
183
+ para apontar a um servidor de teste. Devolve ``mensagem_id``.
184
+
185
+ Nunca repete depois do despacho. ``TelegramNaoSaiu`` (um ``http.NadaSaiu``): a conexão não
186
+ abriu ou a API recusou. ``TelegramIncerto``: a mensagem pode ter saído; o item fica retido."""
187
+ destino = _chat(chat_id)
188
+ if not isinstance(texto, str) or not texto.strip():
189
+ raise ValueError("texto é o texto da mensagem, não vazio")
190
+ if len(texto) > TEXTO_MAX:
191
+ raise ValueError(f"texto passa de {TEXTO_MAX} caracteres")
192
+ if _CONTROLE.search(texto):
193
+ raise ValueError("texto não pode ter caractere de controle (fora quebra de linha e tab)")
194
+ _utf8(texto, "texto")
195
+ if not isinstance(previa_de_link, bool):
196
+ raise ValueError("previa_de_link é verdadeiro ou falso")
197
+ _porta(porta)
198
+ corpo = {
199
+ "chat_id": destino,
200
+ "text": texto,
201
+ "link_preview_options": {"is_disabled": not previa_de_link},
202
+ }
203
+ token = _token(chamada)
204
+ dados = json.dumps(corpo, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
205
+ identificador = _cliente.enviar(
206
+ "enviar_mensagem",
207
+ chamada,
208
+ "sendMessage",
209
+ token,
210
+ dados,
211
+ "application/json",
212
+ Prazo(chamada.timeout),
213
+ porta,
214
+ )
215
+ return {"mensagem_id": identificador}
216
+
217
+
218
+ @PLUGIN.efeito
219
+ def enviar_documento(
220
+ chamada: Any,
221
+ chat_id: int | str,
222
+ documento: str | os.PathLike[str],
223
+ *,
224
+ nome: str | None = None,
225
+ legenda: str | None = None,
226
+ tipo: str | None = None,
227
+ porta: int | None = None,
228
+ ) -> dict[str, int]:
229
+ """Envia um arquivo do diretório de trabalho (até 50 MB) como documento ao chat ``chat_id``
230
+ (só dentro de ``item.efetivar()``). ``nome`` é o nome que aparece no chat (o do arquivo, se
231
+ omitido), ``legenda`` o texto de até 1024 caracteres sob ele, ``tipo`` o ``Content-Type``
232
+ (adivinhado pelo nome). A legenda também vai como texto puro. Devolve ``mensagem_id``.
233
+
234
+ Nunca repete depois do despacho. ``TelegramNaoSaiu``: a conexão não abriu ou a API recusou.
235
+ ``TelegramIncerto``: o documento pode ter saído; o item fica retido."""
236
+ destino = _chat(chat_id)
237
+ caminho = _arquivo_do_workdir(documento)
238
+ nome_no_chat = _nome_do_documento(nome, caminho.name)
239
+ texto_da_legenda = _legenda(legenda)
240
+ if tipo is not None and (
241
+ not isinstance(tipo, str) or not re.fullmatch(r"[a-z0-9.+-]+/[a-z0-9.+-]+", tipo)
242
+ ):
243
+ raise ValueError("tipo é o Content-Type, como 'application/pdf'")
244
+ tipo = tipo or mimetypes.guess_type(nome_no_chat)[0] or "application/octet-stream"
245
+ _porta(porta)
246
+ try:
247
+ tamanho = caminho.stat().st_size
248
+ conteudo = caminho.read_bytes() if tamanho <= DOCUMENTO_MAX else b""
249
+ lido = True
250
+ except OSError:
251
+ lido = False
252
+ if not lido:
253
+ # Fora do ``except``: o erro do SO traria o caminho absoluto e o nome do arquivo.
254
+ raise FileNotFoundError("documento: não pôde ser lido")
255
+ if tamanho > DOCUMENTO_MAX:
256
+ raise ValueError("documento passa de 50 MB, o limite dos bots")
257
+ if tamanho == 0:
258
+ raise ValueError("documento está vazio")
259
+ token = _token(chamada)
260
+ campos = {"chat_id": str(destino)}
261
+ if texto_da_legenda is not None:
262
+ campos["caption"] = texto_da_legenda
263
+ corpo, tipo_do_corpo = _cliente.corpo_multipart(
264
+ campos, ("document", nome_no_chat, conteudo, tipo)
265
+ )
266
+ identificador = _cliente.enviar(
267
+ "enviar_documento",
268
+ chamada,
269
+ "sendDocument",
270
+ token,
271
+ corpo,
272
+ tipo_do_corpo,
273
+ Prazo(chamada.timeout),
274
+ porta,
275
+ )
276
+ return {"mensagem_id": identificador}
@@ -0,0 +1,277 @@
1
+ """O cliente HTTP da Bot API do Telegram: um despacho, no máximo.
2
+
3
+ Fala com ``https://api.telegram.org/bot<token>/<método>`` (o host que o plugin declara), com
4
+ ``chamada.destino()`` antes de conectar. O certificado é verificado; o ``HTTPS_PROXY`` do ambiente
5
+ é respeitado (no sandbox, o proxy da allowlist). Não segue redirecionamento: o token não vai a
6
+ outro host.
7
+
8
+ **O token está no caminho da URL.** A Bot API não tem cabeçalho de autenticação, então a URL é um
9
+ segredo. Ela só existe dentro de ``enviar``: nenhuma mensagem de erro, evento ou ``__cause__`` a
10
+ leva. Toda menção ao endpoint passa por ``redigir``, e o erro do ``urllib`` (cujo
11
+ ``filename``/``url`` carrega a URL inteira) nunca vira a causa de um erro nosso: a decisão é
12
+ tomada fora do ``except``.
13
+
14
+ **Só se repete o que certamente não saiu.** A API não reconhece repetição, então a regra é uma só:
15
+ a falha que prova que nenhum byte do pedido chegou ao servidor (conexão recusada, nome que não
16
+ resolve, rede inalcançável) é tentada de novo dentro do prazo; qualquer outra coisa, depois de o
17
+ pedido ter podido sair (timeout, conexão que cai, ``5xx``, resposta que não se lê), encerra a
18
+ chamada. Resposta HTTP nunca é repetida: o 4xx diz que a API recusou, e quem quiser enviar de novo
19
+ é o robô, com uma nova decisão.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import http.client
25
+ import json
26
+ import secrets
27
+ import ssl
28
+ import time
29
+ import urllib.error
30
+ import urllib.request
31
+ from collections.abc import Callable
32
+ from dataclasses import dataclass
33
+ from typing import Any
34
+
35
+ from shade_sdk import http
36
+
37
+ from shade_plugins_telegram.erros import TelegramIncerto, TelegramNaoSaiu
38
+
39
+ HOST = "api.telegram.org"
40
+ #: Quantas vezes o pedido é tentado quando a conexão **não chegou a abrir**.
41
+ TENTATIVAS = 3
42
+ #: A espera antes da 2ª e da 3ª tentativa (a régua do ``shade_sdk.http``).
43
+ ESPERAS = (0.5, 1.0)
44
+ #: O teto do corpo da resposta que o plugin lê (a resposta de sucesso é uma mensagem em JSON).
45
+ RESPOSTA_MAX = 1024 * 1024
46
+ #: O que a ``description`` da Bot API quer dizer, escrito aqui para a mensagem de erro, nunca copiado
47
+ #: do corpo da resposta (que pode repetir o pedido). A chave é um trecho fixo da descrição.
48
+ DICAS: dict[str, str] = {
49
+ "chat not found": "chat_id desconhecido, ou o bot nunca entrou nesse chat",
50
+ "bot was blocked by the user": "a pessoa bloqueou o bot",
51
+ "user is deactivated": "a conta da pessoa foi desativada",
52
+ "can't initiate conversation": "o bot não pode abrir conversa: a pessoa precisa escrever "
53
+ "para ele antes (/start)",
54
+ "not enough rights": "o bot não tem permissão para escrever nesse chat",
55
+ "have no rights to send": "o bot não tem permissão para escrever nesse chat",
56
+ "message is too long": "a mensagem passa do limite de 4096 caracteres",
57
+ "message text is empty": "o texto da mensagem está vazio",
58
+ "file is too big": "o arquivo passa do limite de 50 MB dos bots",
59
+ "too many requests": "limite de mensagens do bot: espere o retry_apos",
60
+ "unauthorized": "token do bot inválido ou revogado",
61
+ }
62
+
63
+
64
+ class Prazo:
65
+ """O ``timeout`` da chamada como um prazo só: cada etapa usa o que sobrou."""
66
+
67
+ def __init__(self, segundos: float) -> None:
68
+ self.fim = time.monotonic() + segundos
69
+
70
+ def restante(self) -> float:
71
+ sobra = self.fim - time.monotonic()
72
+ if sobra <= 0:
73
+ raise TimeoutError("o prazo da chamada acabou")
74
+ return sobra
75
+
76
+ def cabe(self, espera: float) -> bool:
77
+ return self.fim - time.monotonic() > espera
78
+
79
+
80
+ def redigir(texto: str, token: str) -> str:
81
+ """``texto`` sem o token do caminho ``/bot<token>/``: é o que entra em mensagem de erro e em
82
+ qualquer registro. Só o caminho é trocado, para um token curto não casar com o host."""
83
+ return texto.replace(f"/bot{token}/", "/bot<token>/")
84
+
85
+
86
+ def corpo_multipart(
87
+ campos: dict[str, str], arquivo: tuple[str, str, bytes, str]
88
+ ) -> tuple[bytes, str]:
89
+ """O ``multipart/form-data`` de um envio de documento: (corpo, ``Content-Type``).
90
+
91
+ ``arquivo`` é (campo, nome, conteúdo, tipo). Nome e campos já chegam validados (sem aspas,
92
+ barra invertida nem controle); a fronteira é sorteada até não aparecer no conteúdo."""
93
+ while True:
94
+ fronteira = "shade" + secrets.token_hex(16)
95
+ marca = fronteira.encode()
96
+ campo, nome, conteudo, tipo = arquivo
97
+ partes: list[bytes] = []
98
+ for chave, valor in campos.items():
99
+ partes.append(
100
+ f'--{fronteira}\r\nContent-Disposition: form-data; name="{chave}"\r\n\r\n'.encode()
101
+ + valor.encode("utf-8")
102
+ + b"\r\n"
103
+ )
104
+ partes.append(
105
+ f'--{fronteira}\r\nContent-Disposition: form-data; name="{campo}"; '
106
+ f'filename="{nome}"\r\nContent-Type: {tipo}\r\n\r\n'.encode()
107
+ + conteudo
108
+ + b"\r\n"
109
+ )
110
+ partes.append(f"--{fronteira}--\r\n".encode())
111
+ corpo = b"".join(partes)
112
+ if corpo.count(marca) == len(campos) + 2: # só as fronteiras que nós pusemos
113
+ return corpo, f"multipart/form-data; boundary={fronteira}"
114
+
115
+
116
+ class _SemRedirecionamento(urllib.request.HTTPRedirectHandler):
117
+ def redirect_request(self, *args: Any, **kwargs: Any) -> None:
118
+ return None
119
+
120
+
121
+ def _abridor() -> Callable[..., Any]:
122
+ contexto = ssl.create_default_context()
123
+ contexto.minimum_version = ssl.TLSVersion.TLSv1_2
124
+ return urllib.request.build_opener(
125
+ urllib.request.ProxyHandler(),
126
+ urllib.request.HTTPSHandler(context=contexto),
127
+ _SemRedirecionamento(),
128
+ ).open
129
+
130
+
131
+ @dataclass
132
+ class Resposta:
133
+ status: int
134
+ corpo: bytes
135
+
136
+
137
+ def _json_do_corpo(corpo: bytes) -> dict[str, Any]:
138
+ try:
139
+ dados = json.loads(corpo[:65536])
140
+ except (ValueError, RecursionError): # o corpo de um intermediário pode ser um `[[[[...`
141
+ return {}
142
+ return dados if isinstance(dados, dict) else {}
143
+
144
+
145
+ def _inteiro(valor: Any) -> int | None:
146
+ return valor if isinstance(valor, int) and not isinstance(valor, bool) else None
147
+
148
+
149
+ def _pode_repetir(motivo: Any) -> bool:
150
+ """A falha que **prova** que nada chegou ao servidor e em que repetir pode dar certo. O
151
+ certificado inválido e o túnel recusado pelo proxy não melhoram com o tempo."""
152
+ if isinstance(motivo, ssl.SSLCertVerificationError):
153
+ return False
154
+ return not str(motivo).startswith("Tunnel connection failed")
155
+
156
+
157
+ def _despachar(abrir: Callable[..., Any], pedido: Any, tempo: float) -> Resposta:
158
+ try:
159
+ with abrir(pedido, timeout=tempo) as resposta:
160
+ return Resposta(resposta.status, resposta.read(RESPOSTA_MAX))
161
+ except urllib.error.HTTPError as exc:
162
+ try:
163
+ corpo = exc.read(65536) if exc.fp else b""
164
+ except (OSError, http.client.HTTPException):
165
+ corpo = b"" # o status já diz que a API recusou; o corpo só traria o código
166
+ return Resposta(exc.code, corpo)
167
+
168
+
169
+ def enviar(
170
+ operacao: str,
171
+ chamada: Any,
172
+ metodo: str,
173
+ token: str,
174
+ conteudo: bytes,
175
+ tipo: str,
176
+ prazo: Prazo,
177
+ porta: int | None,
178
+ ) -> int:
179
+ """Despacha ``conteudo`` em ``/bot<token>/<metodo>`` e devolve o ``message_id``.
180
+
181
+ ``TelegramNaoSaiu`` se nada saiu; ``TelegramIncerto`` se pode ter saído. Nenhum dos dois
182
+ carrega o token, a URL com ele nem o erro do ``urllib`` como causa."""
183
+ chamada.destino(HOST)
184
+ autoridade = HOST if porta in (None, 443) else f"{HOST}:{porta}"
185
+ url = f"https://{autoridade}/bot{token}/{metodo}"
186
+ endpoint = redigir(url, token)
187
+ cabecalhos = {
188
+ "Content-Type": tipo,
189
+ "Accept": "application/json",
190
+ # A Bot API ignora a chave (não há idempotência nela); quem observa o tráfego, o proxy e o
191
+ # servidor falso dos testes, distingue a execução.
192
+ "Idempotency-Key": chamada.idempotencia,
193
+ }
194
+ abrir = _abridor()
195
+ for tentativa in range(1, TENTATIVAS + 1):
196
+ try:
197
+ tempo = prazo.restante()
198
+ except TimeoutError:
199
+ tempo = None
200
+ if tempo is None:
201
+ raise TelegramNaoSaiu(
202
+ f"Telegram {operacao}: o prazo acabou antes de a conexão abrir ({endpoint})"
203
+ )
204
+ pedido = urllib.request.Request(url, data=conteudo, headers=cabecalhos, method="POST")
205
+ resposta: Resposta | None = None
206
+ falha: BaseException | None = None
207
+ try:
208
+ resposta = _despachar(abrir, pedido, tempo)
209
+ except Exception as exc:
210
+ falha = exc
211
+ if falha is None and resposta is not None:
212
+ return _identificador(operacao, endpoint, resposta)
213
+ # A decisão fica fora do ``except``: nenhum erro nosso nasce com o do ``urllib`` (e a URL
214
+ # com o token que ele guarda) como ``__context__``.
215
+ assert falha is not None
216
+ if not http.nada_saiu(falha):
217
+ tipo_da_falha = type(falha).__name__
218
+ falha = None
219
+ raise TelegramIncerto(
220
+ f"Telegram {operacao}: a conexão falhou depois do envio ({tipo_da_falha}); "
221
+ f"a mensagem pode ter saído ({endpoint})"
222
+ )
223
+ motivo = getattr(falha, "reason", falha)
224
+ espera = ESPERAS[min(tentativa - 1, len(ESPERAS) - 1)]
225
+ repetir = tentativa < TENTATIVAS and _pode_repetir(motivo) and prazo.cabe(espera)
226
+ nome_do_motivo = type(motivo).__name__
227
+ falha = None
228
+ if repetir:
229
+ time.sleep(espera)
230
+ continue
231
+ raise TelegramNaoSaiu(
232
+ f"Telegram {operacao}: a conexão não abriu ({nome_do_motivo}; {endpoint})"
233
+ )
234
+ raise AssertionError("o laço de tentativas sempre retorna ou levanta") # pragma: no cover
235
+
236
+
237
+ def _dica(descricao: Any) -> str:
238
+ if not isinstance(descricao, str):
239
+ return ""
240
+ minuscula = descricao.lower()
241
+ for trecho, dica in DICAS.items():
242
+ if trecho in minuscula:
243
+ return f": {dica}"
244
+ return ""
245
+
246
+
247
+ def _identificador(operacao: str, endpoint: str, resposta: Resposta) -> int:
248
+ """O ``result.message_id`` de uma resposta 2xx; o resto é recusa (4xx) ou dúvida."""
249
+ dados = _json_do_corpo(resposta.corpo)
250
+ if 200 <= resposta.status < 300:
251
+ resultado = dados.get("result")
252
+ achado = _inteiro(resultado.get("message_id")) if isinstance(resultado, dict) else None
253
+ if dados.get("ok") is True and achado is not None:
254
+ return achado
255
+ raise TelegramIncerto(
256
+ f"Telegram {operacao}: a API respondeu {resposta.status} sem o identificador da "
257
+ f"mensagem; ela pode ter saído ({endpoint})"
258
+ )
259
+ codigo = _inteiro(dados.get("error_code"))
260
+ parametros = dados.get("parameters")
261
+ retry_apos = _inteiro(parametros.get("retry_after")) if isinstance(parametros, dict) else None
262
+ sufixo = f", código {codigo}" if codigo is not None else ""
263
+ sufixo += _dica(dados.get("description"))
264
+ if retry_apos is not None:
265
+ sufixo += f", retry_apos {retry_apos} s"
266
+ if 400 <= resposta.status < 500:
267
+ raise TelegramNaoSaiu(
268
+ f"Telegram {operacao}: a API recusou o pedido ({resposta.status}{sufixo}; {endpoint})",
269
+ status=resposta.status,
270
+ codigo=codigo,
271
+ retry_apos=retry_apos,
272
+ )
273
+ raise TelegramIncerto(
274
+ f"Telegram {operacao}: a API devolveu {resposta.status}{sufixo}; a mensagem pode ter "
275
+ f"saído ({endpoint})",
276
+ status=resposta.status,
277
+ )
@@ -0,0 +1,44 @@
1
+ """Os erros do plugin ``telegram``.
2
+
3
+ A Bot API do Telegram **não reconhece repetição**: não há chave de idempotência, e um segundo
4
+ ``POST`` com o mesmo conteúdo é uma segunda mensagem no chat. Por isso os erros separam só duas
5
+ coisas, e o plugin nunca repete o que passou da primeira:
6
+
7
+ - ``TelegramNaoSaiu`` (um ``http.NadaSaiu``): **certamente** nenhuma mensagem saiu. A conexão não
8
+ chegou a abrir, ou a API recusou o pedido (4xx) antes de aceitá-lo.
9
+ - ``TelegramIncerto`` (um ``http.ResultadoIncerto``): o pedido pode ter chegado e a confirmação
10
+ não veio (timeout, conexão que caiu, ``5xx``, resposta sem o identificador da mensagem). A
11
+ mensagem pode estar no chat. O item fica retido para uma pessoa conferir; reenviar sozinho é a
12
+ duplicata que este plugin existe para não fazer.
13
+
14
+ As mensagens dizem a operação, o endpoint **sem o token** (a Bot API o põe no caminho da URL), o
15
+ status HTTP e o código da API, nunca o corpo, o texto, o ``chat_id`` nem o token.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from shade_sdk import http
21
+
22
+
23
+ class TelegramNaoSaiu(http.NadaSaiu):
24
+ """Certamente sem mensagem: a conexão não abriu ou a API recusou o pedido (4xx).
25
+
26
+ ``codigo`` é o ``error_code`` da Bot API e ``retry_apos`` os segundos que ela pede de espera
27
+ (429), quando vieram."""
28
+
29
+ def __init__(
30
+ self,
31
+ mensagem: str,
32
+ *,
33
+ status: int | None = None,
34
+ codigo: int | None = None,
35
+ retry_apos: int | None = None,
36
+ ):
37
+ super().__init__(mensagem, status=status)
38
+ self.codigo = codigo
39
+ self.retry_apos = retry_apos
40
+
41
+
42
+ class TelegramIncerto(http.ResultadoIncerto):
43
+ """Pode ter saído: o pedido foi despachado e a confirmação não veio. Conferir no chat antes de
44
+ reenviar."""
@@ -0,0 +1,102 @@
1
+ Metadata-Version: 2.5
2
+ Name: shade-plugins-telegram
3
+ Version: 0.1.0
4
+ Summary: Enviar mensagem e documento pela Bot API do Telegram, sem nunca repetir um envio depois de despachado.
5
+ Author: ShadeOne
6
+ License-Expression: Apache-2.0
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.11
9
+ Requires-Dist: shade-sdk<0.23,>=0.22.1
10
+ Description-Content-Type: text/markdown
11
+
12
+ # shade-plugins-telegram
13
+
14
+ Envia mensagem e documento pela [Bot API do Telegram](https://core.telegram.org/bots/api), de
15
+ dentro de um robô do [`shade-sdk`](https://pypi.org/project/shade-sdk/). Só a biblioteca padrão do
16
+ Python: nenhuma dependência além do `shade-sdk`.
17
+
18
+ No `shade.toml` do robô, o host da API vai em `[hosts] permitidos` e o token do bot em
19
+ `[credenciais]`:
20
+
21
+ ```toml
22
+ [hosts]
23
+ permitidos = ["api.telegram.org"]
24
+
25
+ [credenciais]
26
+ nomes = ["TELEGRAM_BOT_TOKEN"]
27
+
28
+ [plugins]
29
+ telegram = "0.1.0"
30
+ ```
31
+
32
+ ```python
33
+ import shade_plugins_telegram as telegram
34
+
35
+ # Escrita: só dentro de item.efetivar() (no ensaio não roda).
36
+ with item.efetivar("avisar o time"):
37
+ telegram.enviar_mensagem(config["telegram_chat"], f"Pedido {item['pedido']} conferido.")
38
+
39
+ with item.efetivar("mandar o comprovante"):
40
+ telegram.enviar_documento(
41
+ config["telegram_chat"], # o número do chat, ou @canal
42
+ "saida/comprovante.pdf", # um arquivo do diretório de trabalho do robô
43
+ legenda="Segue o comprovante.",
44
+ )
45
+ ```
46
+
47
+ ## A conta
48
+
49
+ - **Token:** o token que o [@BotFather](https://t.me/BotFather) entrega ao criar o bot. Guarde-o
50
+ como a credencial `TELEGRAM_BOT_TOKEN`; o plugin o lê só por `segredo()`.
51
+ - **`chat_id`:** o número do chat (positivo para conversa com uma pessoa, `-100...` para grupo e
52
+ canal) ou `@canal_publico`. Não é segredo, mas identifica uma pessoa: guarde-o no `[config]` do
53
+ robô e não o ponha em log. O bot só escreve a quem já falou com ele (`/start`) e nos grupos e
54
+ canais em que foi adicionado.
55
+ - **Texto puro:** a mensagem e a legenda vão sem `parse_mode`, então `*`, `_` e `<` aparecem como
56
+ são. Formatação (Markdown, HTML) não é suportada nesta versão, nem botão, foto, áudio ou
57
+ resposta a outra mensagem.
58
+ - **Documento:** até 50 MB, do diretório de trabalho do robô (caminho relativo). `nome` troca o
59
+ nome que aparece no chat (sem aspas, barras nem controle: o que não serve é recusado, não
60
+ escapado), `legenda` leva até 1024 caracteres.
61
+
62
+ ## O que o plugin garante
63
+
64
+ - **Nunca envia duas vezes.** A Bot API não reconhece repetição: não há chave de idempotência, e
65
+ um segundo pedido é uma segunda mensagem no chat. Por isso o plugin **não repete depois do
66
+ despacho, em nenhum erro**:
67
+ - A conexão que não chegou a abrir (recusada, nome que não resolve, rede inalcançável) é tentada
68
+ de novo, dentro do `timeout=`, porque nada saiu.
69
+ - A API que recusou (4xx) é `TelegramNaoSaiu`: nenhuma mensagem saiu. O `codigo` vem em
70
+ `erro.codigo` e, no limite de envio (429), o `retry_apos` em segundos. O plugin não espera
71
+ nem repete sozinho: a espera é decisão do robô.
72
+ - O que sobra é `TelegramIncerto`: o `timeout`, a conexão que cai depois do envio, o `5xx` e a
73
+ resposta de sucesso sem o `message_id`. A mensagem **pode** estar no chat. O item fica
74
+ retido para uma pessoa conferir no chat e, só se a mensagem não chegou, mandar refazer. O
75
+ plugin não reenvia sozinho, e uma nova execução do robô também não.
76
+ - **O token não aparece em lugar nenhum.** A Bot API o põe no **caminho da URL**
77
+ (`/bot<token>/sendMessage`), então a URL é um segredo: ela só existe dentro do envio. Mensagem
78
+ de erro, evento e relatório mostram o endpoint como `/bot<token>/sendMessage`, e o erro do
79
+ `urllib` (que guarda a URL inteira) nunca é a causa de um erro do plugin.
80
+ - **Só dentro de `item.efetivar()`.** Fora dele, a operação é um erro de contrato antes de qualquer
81
+ byte; no ensaio, o bloco é pulado e nada é enviado.
82
+ - **Host e prazo:** só `api.telegram.org`, com o certificado verificado, sem seguir
83
+ redirecionamento; toda chamada aceita `timeout=` (30 s por padrão), que vale para a chamada
84
+ inteira.
85
+ - **Sem dado pessoal em evento nem em erro:** cada chamada emite um evento com a operação, o host,
86
+ a duração e o status. Nunca o texto, o `chat_id`, o nome do arquivo nem o corpo da resposta; o
87
+ erro da API chega só pelo código numérico e por uma explicação escrita no plugin.
88
+
89
+ ## Operações
90
+
91
+ | Operação | Efeito | O que faz |
92
+ |---|---|---|
93
+ | `enviar_mensagem(chat_id, texto, *, previa_de_link=False)` | sim | Mensagem de texto de até 4096 caracteres. |
94
+ | `enviar_documento(chat_id, documento, *, nome=None, legenda=None, tipo=None)` | sim | Arquivo do diretório de trabalho como documento. |
95
+
96
+ As duas devolvem `{"mensagem_id": 1234}`.
97
+
98
+ ## Testes
99
+
100
+ A suíte de contrato do `shade_sdk.testing.plugins` e um servidor falso da Bot API (TLS de uma CA de
101
+ teste, com o token no caminho como na de verdade) acompanham o código-fonte em `tests/`. O servidor
102
+ falso não reconhece repetição, como a API de verdade.
@@ -0,0 +1,8 @@
1
+ shade_plugins_telegram/__init__.py,sha256=neNpQIEfQY6N8YpfUrfw9K4pbG5bzamKHJsU5TdP7vs,10723
2
+ shade_plugins_telegram/_cliente.py,sha256=P7rLFZdCacPk6iJXKeMmYoTN9aj2iTaHcJTX8zuYEfk,11468
3
+ shade_plugins_telegram/erros.py,sha256=FhQCvxRc91GBwTbhO5ObSNZA0oOnSYd7XIhIz2ZEJqM,1783
4
+ shade_plugins_telegram-0.1.0.dist-info/METADATA,sha256=BfA2f3UHxDmWoJax5we0XOzgNV0J1uXMRe_0BalieVA,5022
5
+ shade_plugins_telegram-0.1.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ shade_plugins_telegram-0.1.0.dist-info/entry_points.txt,sha256=yLNbMh82iCTb3QWOQrpsbpzWuS6yCyrvYZcTRP3bUiQ,61
7
+ shade_plugins_telegram-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ shade_plugins_telegram-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [shade_sdk.plugins]
2
+ telegram = shade_plugins_telegram:PLUGIN
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.