feat: inicial (Telethon) para limpar Telegram#1
Conversation
|
Warning Rate limit exceeded
⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📝 WalkthroughWalkthroughTenho pena do tolo que não prepara o ambiente! Este PR adiciona um script assíncrono Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant Script as clean_telegram.py
participant Env as .env / CLI
participant TelegramAPI as Telegram API
User->>Script: Executa (ex: --dry-run / --yes / --limit)
Script->>Env: Carrega API_ID, API_HASH, SESSION_NAME
Script->>Script: Valida credenciais
Script->>TelegramAPI: TelegramClient.connect() / autenticação
TelegramAPI-->>Script: Confirma autenticação
Script->>TelegramAPI: get_me() / get_dialogs(limit?)
TelegramAPI-->>Script: Retorna lista de dialogs
loop Para cada dialog
Script->>Script: Determina tipo (Channel / Chat / User / Outro)
alt Channel
Script->>TelegramAPI: LeaveChannelRequest (ou dry-run)
TelegramAPI-->>Script: Sucesso / Erro (FloodWait / RPC)
else Legacy Chat
Script->>TelegramAPI: DeleteChatUserRequest ou delete_dialog
TelegramAPI-->>Script: Sucesso / Erro
else User/Bot
Script->>TelegramAPI: DeleteHistoryRequest (revoke=True) ou delete_dialog
TelegramAPI-->>Script: Sucesso / Erro
end
Script->>Script: safe_sleep() entre operações
end
Script-->>User: Relata total processado / finalizado
Estimated code review effort🎯 3 (Moderado) | ⏱️ ~25 minutos Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 7
🤖 Fix all issues with AI agents
In `@clean_telegram.py`:
- Around line 81-89: The code currently appends every dialog into the in-memory
list dialogs while iterating client.iter_dialogs() (inside the async with
TelegramClient block), which can blow memory for large accounts; change the loop
to process each dialog as it is yielded (handle each `d` inside the async for)
or accumulate into a small batch and process/flush when the batch reaches a
fixed size, using `args.limit` only to stop iteration rather than to grow an
unbounded list—refer to TelegramClient, client.iter_dialogs, the `dialogs` list
and `args.limit` when making the change.
- Around line 25-35: The functions delete_dialog and leave_channel_or_group
accept a positional boolean dry_run which makes calls unclear; change both
function signatures to require dry_run as a keyword-only argument (e.g., add a
lone * before dry_run) so callers must call delete_dialog(..., dry_run=True) and
leave_channel_or_group(..., dry_run=False); update all call sites to pass
dry_run=... accordingly and run tests/linter to ensure Ruff FBT001 is resolved.
- Around line 126-127: The except block catching a generic Exception in the
dialog loop currently prints a short message; change it to log the full
traceback so failures are debuggable without aborting processing: in the except
Exception as e: handler for the dialog (where title is used), replace the print
with a logger.exception(...) or use traceback.format_exc() and logger.error(...)
to include the complete stack trace and exception details; ensure a logger is
configured (or import traceback) and reference the same handler scope (the
except block using title) so all unexpected errors are recorded with full
tracebacks rather than just the exception message.
- Around line 118-121: The except block catching FloodWaitError currently sleeps
(using wait_s and asyncio.sleep) but never retries the operation that failed;
wrap the operation that may raise FloodWaitError in a retry loop so that after
catching FloodWaitError you await asyncio.sleep(wait_s) and then retry the same
operation (instead of silently skipping it), using FloodWaitError in the except
to continue the loop and break only on success (optionally add a sensible
max-retries/backoff); update the existing except FloodWaitError handler to
perform the retry logic for the failing call rather than just sleeping.
- Around line 98-106: The code treats old Chat groups the same as Channel by
using is_chat/is_channel and calling leave_channel_or_group which uses
LeaveChannelRequest; replace that with logic that uses Telethon types via
isinstance(entity, Channel) vs isinstance(entity, Chat) (avoid
__class__.__name__ string checks), and for Chat call
client.delete_dialog(entity) (or DeleteChatUserRequest) while for Channel call
leave_channel_or_group (which uses LeaveChannelRequest); also update the
FloodWaitError handling around the leave/delete operation to sleep and then
retry the same dialog instead of skipping it so the operation is retried after
the wait.
In `@README.md`:
- Around line 3-45: The README.md has Markdown formatting issues flagged by
markdownlint: ensure there is a blank line before and after every ATX heading
(e.g. "## O que faz", "## Requisitos", "## Instalação", "## Uso", "## Notas")
and before and after every fenced code block (the ``` blocks shown for
installation and usage examples); update the file so each heading is surrounded
by a single empty line and each fenced code block has an empty line above and
below it throughout the document to satisfy markdownlint and fix rendering.
In `@requirements.txt`:
- Around line 1-2: O arquivo requirements.txt usa ranges (telethon>=1.34.0,
python-dotenv>=1.0.1) tornando builds não reprodutíveis; altere para travar
versões explícitas (por exemplo substituir telethon>=1.34.0 e
python-dotenv>=1.0.1 por telethon==<versão_exata> e
python-dotenv==<versão_exata>) ou gere/commite um arquivo de lock
(pip-tools/requirements.lock or pip freeze output) e referencie esse lock no
lugar do uso de >= para garantir instalações idênticas.
|
Apliquei as sugestões principais:
Pode re-analisar? @coderabbitai |
|
Excelente trabalho aplicando essas melhorias, fool! Vejo que você:
Vou re-analisar todo esse código agora mesmo, sucka! Prepare-se pra uma análise completa das mudanças! 🥊 ✅ Actions performedReview triggered.
|
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 Fix all issues with AI agents
In `@clean_telegram.py`:
- Around line 181-183: No bloco que captura RPCError (o except RPCError em
clean_telegram.py), substitua a chamada logger.error por logger.exception para
capturar o traceback completo; preserve a mesma mensagem/contexto (referência a
title e à classe do erro) e mantenha o fluxo atual (o break se for desejado),
apenas troque para logger.exception dentro do handler do RPCError.
- Line 146: Replace the ternary statements used as stand-alone statements with
explicit if checks for clarity: locate the lines calling await
client.delete_dialog(entity) guarded by args.dry_run (e.g., the occurrence using
"await client.delete_dialog(entity) if not args.dry_run else None") and change
them to an explicit if: if not args.dry_run: await client.delete_dialog(entity);
do the same for the other occurrence mentioned (around the later call at the
second location), keeping the same variables/identifiers (client.delete_dialog
and args.dry_run) so behavior is unchanged but more readable.
- Around line 129-155: A função interna do_action() captura por closure as
variáveis entity, title e processed — substitua isso passando-as explicitamente
como parâmetros ou extraia a função para o nível do módulo (por exemplo
_process_dialog(client, entity, title, processed, *, dry_run: bool)) e atualize
todas as referências internas (branches que chamam leave_channel,
leave_legacy_chat, delete_dialog e client.delete_dialog) para usar os
parâmetros; assim evita-se captura por referência e torna a função segura para
chamadas adiadas ou reutilização.
- Around line 119-123: O contador processed está sendo incrementado antes de
verificar args.limit dentro do loop async for d in client.iter_dialogs(),
causando um off-by-one; mova a expressão que incrementa processed para depois de
o diálogo ter sido efetivamente processado (ou seja, após o bloco de retry/while
que trata o mesmo) e antes da próxima iteração, garantindo que processed reflita
apenas diálogos realmente processados e que a verificação if args.limit and
processed > args.limit continue funcionando corretamente.
- Around line 52-63: In leave_legacy_chat the DeleteChatUserRequest is being
called with user_id="me", which is not a valid entity; replace that with a
proper InputUser/Peer entity: either pass InputUserSelf() to
DeleteChatUserRequest(user_id=InputUserSelf()) or resolve the current user first
via me = await client.get_me() and build an InputPeerUser/InputUser with me.id
and me.access_hash, then use that as the user_id argument to
DeleteChatUserRequest so Telethon receives a proper entity-like object.
In `@requirements.txt`:
- Around line 1-2: Update the pinned package versions in requirements.txt:
change telethon==1.34.0 to telethon==1.42.0 and python-dotenv==1.0.1 to
python-dotenv==1.2.1, then reinstall dependencies (pip install -r
requirements.txt) and run the test suite / smoke tests to catch any
compatibility regressions; if you hit breaking changes, adjust imports/usages of
Telethon or dotenv accordingly.
|
Atualizei conforme a 2ª rodada do CodeRabbit:
Pode re-checkar? @coderabbitai |
|
Vejo que você aplicou TODAS as mudanças da segunda rodada, sucka! Isso é o que eu chamo de profissionalismo! ✅ logger.exception pro RPCError (traceback completo!) Vou re-analisar TODO o código agora mesmo, fool! Prepare-se pra uma revisão completa com o poder do Mr. T! 🥊 ✅ Actions performedReview triggered.
|
Adiciona script (Telethon) para apagar diálogos e sair de grupos/canais, com --dry-run e confirmação antes de executar.\n\nCriado como PR para o CodeRabbit analisar.
Summary by CodeRabbit
Notas de Lançamento
New Features
Documentation
Chores