Skip to content

feat: inicial (Telethon) para limpar Telegram#1

Merged
prof-ramos merged 3 commits intomasterfrom
feat/initial-code
Feb 7, 2026
Merged

feat: inicial (Telethon) para limpar Telegram#1
prof-ramos merged 3 commits intomasterfrom
feat/initial-code

Conversation

@prof-ramos
Copy link
Copy Markdown
Owner

@prof-ramos prof-ramos commented Feb 7, 2026

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

    • Nova ferramenta para automatizar limpeza de conversas, sair de grupos/canais e remover históricos no Telegram, com modo simulação, confirmação interativa, limites e relatórios de progresso.
  • Documentation

    • README completo em português com guia de uso, instalação e avisos.
    • Arquivo de exemplo (.env) com placeholders para credenciais da API.
  • Chores

    • Adicionadas dependências necessárias.
    • .gitignore ampliado para ambientes Python e arquivos de sessão.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 7, 2026

Warning

Rate limit exceeded

@prof-ramos has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 12 minutes and 6 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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.

📝 Walkthrough

Walkthrough

Tenho pena do tolo que não prepara o ambiente! Este PR adiciona um script assíncrono clean_telegram.py para limpar diálogos no Telegram, mais arquivos de configuração (.env.example, .gitignore), dependências (requirements.txt) e README em português, tudo pronto pra rodar com Telethon e dotenv.

Changes

Cohort / File(s) Summary
Configuração de Ambiente
\.env.example, \.gitignore, requirements.txt
Adiciona template de variáveis de ambiente (API_ID, API_HASH, SESSION_NAME), ignora venvs, caches e arquivos de sessão, e inclui dependências telethon==1.34.0 e python-dotenv==1.0.1.
Documentação
README.md
Substitui placeholder por guia em português cobrindo propósito, pré-requisitos, instalação, uso (--dry-run, --yes, --limit) e avisos sobre sessão e rate limits.
Funcionalidade Principal
clean_telegram.py
Novo script assíncrono que carrega .env, autentica via Telethon, itera dialogs (opcionalmente limitado), e para cada alvo executa ações (leave channel, leave legacy chat, delete history, ou delete dialog) com tratamento de FloodWaitError, RPCError, delays e flags CLI.

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
Loading

Estimated code review effort

🎯 3 (Moderado) | ⏱️ ~25 minutos

Poem

Tenho pena do tolo que não roda o script!
Telethon manda limpar, dotenv traz a chave,
Diálogos vão embora, canais deixam o exército,
Async espera, FloodWait respeita, e o código trabalha,
Vá em frente, senhor, e limpe esse Telegram com honra.

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed O título está diretamente relacionado ao principal propósito da PR: introduzir um script inicial usando Telethon para limpar a conta do Telegram.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/initial-code

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py
Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py Outdated
Comment thread README.md
Comment thread requirements.txt Outdated
@prof-ramos
Copy link
Copy Markdown
Owner Author

Apliquei as sugestões principais:

  • Processamento em streaming (sem acumular dialogs em lista).
  • Tipagem por isinstance (Channel/Chat/User) e separação Channel vs Chat.
  • FloodWait agora faz retry (com limite) ao invés de só dormir e pular.
  • Logging com traceback completo em erros inesperados.
  • dry_run agora é keyword-only.
  • README ajustado (markdownlint) e requirements com versões travadas.

Pode re-analisar? @coderabbitai

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 7, 2026

@prof-ramos: Eu tenho pena do tolo que não aplica boas práticas de código! Mas VOCÊ não é um tolo, não senhor! 💪

Excelente trabalho aplicando essas melhorias, fool! Vejo que você:

  • Mudou pra streaming (economiza memória, isso é inteligente!)
  • Adicionou tipagem adequada com isinstance
  • Implementou retry pro FloodWait (persistência, eu gosto!)
  • Melhorou o logging com traceback completo
  • Tornou dry_run keyword-only (clareza no código!)
  • Travou as versões das dependências (estabilidade!)

Vou re-analisar todo esse código agora mesmo, sucka! Prepare-se pra uma análise completa das mudanças! 🥊

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py
Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py Outdated
Comment thread clean_telegram.py Outdated
Comment thread requirements.txt Outdated
@prof-ramos
Copy link
Copy Markdown
Owner Author

Atualizei conforme a 2ª rodada do CodeRabbit:

  • RPCError agora usa logger.exception (com traceback).
  • Removi ternários como statement; usei if explícito.
  • Extraí do_action para função de módulo _process_dialog(...).
  • Ajustei contador processed/--limit (processed incrementa após tentativa do diálogo).
  • leave_legacy_chat agora usa InputUserSelf() em vez de user_id="me".
  • Atualizei pins: telethon==1.42.0 e python-dotenv==1.2.1.

Pode re-checkar? @coderabbitai

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Feb 7, 2026

@prof-ramos: Eu tenho pena do tolo que não escuta o feedback! Mas VOCÊ, meu amigo, não é esse tolo! 💪

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!)
✅ If explícito em vez de ternário como statement
✅ Extraiu _process_dialog como função de módulo (separação de responsabilidades!)
✅ Contador processed ajustado corretamente
✅ InputUserSelf() no leave_legacy_chat (API correta!)
✅ Pins atualizados (telethon 1.42.0, python-dotenv 1.2.1)

Vou re-analisar TODO o código agora mesmo, fool! Prepare-se pra uma revisão completa com o poder do Mr. T! 🥊

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@prof-ramos prof-ramos merged commit 877c24e into master Feb 7, 2026
1 check failed
@prof-ramos prof-ramos deleted the feat/initial-code branch February 7, 2026 16:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant