Skip to content

Fix security, bugs, and cleanup#11

Open
kingkpink wants to merge 1 commit into
Mr3rf1:mainfrom
kingkpink:fix/security-and-bug-fixes
Open

Fix security, bugs, and cleanup#11
kingkpink wants to merge 1 commit into
Mr3rf1:mainfrom
kingkpink:fix/security-and-bug-fixes

Conversation

@kingkpink
Copy link
Copy Markdown

@kingkpink kingkpink commented Apr 16, 2026

  • Remove hardcoded API credentials; use TELEGRAM_API_ID and TELEGRAM_API_HASH env vars
  • Fix crash when reporting user accounts (not channels)
  • Fix duplicate reports by using single session
  • Add error handling so one account failure doesn't kill the run
  • Add proper client disconnect on account add to prevent leaked tasks
  • Remove deprecated WindowsSelectorEventLoopPolicy (removed in Python 3.16)
  • Remove unused packages from requirements.txt
  • Add .gitignore for sessions, pycache, and local files
  • Fix typos and improve report output readability

Summary by Sourcery

Improve Telegram reporting script security, robustness, and usability while simplifying dependencies and repo hygiene.

New Features:

  • Add CLI support for a new trafficking report mode mapped to the Telegram Other report reason.

Bug Fixes:

  • Fix crash when reporting non-channel targets by correctly resolving entities and only joining channels.
  • Prevent duplicate and conflicting report sessions by using a single session per run instead of spawning per-account tasks.
  • Ensure invalid target links and per-account failures are handled gracefully without crashing the whole run.
  • Fix phone number handling when adding accounts and close Telegram client connections to avoid leaked tasks.

Enhancements:

  • Replace hardcoded Telegram API credentials with TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables and enforce their presence at startup.
  • Refine report output messages for clearer, more informative status per report and account.
  • Improve session file discovery and numbering to ignore non-session artifacts and create the sessions directory idempotently.
  • Tighten CLI argument handling, defaults, and help copy for add-number and run flows.

Build:

  • Remove unused asyncio and telegram packages from requirements.txt.

Documentation:

  • Clarify CLI help text and reasons list, including explanation of the new trafficking mode mapping.

Chores:

  • Add a .gitignore to exclude session files, pycache, and local artifacts from version control.

- Remove hardcoded API credentials; use TELEGRAM_API_ID and TELEGRAM_API_HASH env vars
- Fix crash when reporting user accounts (not channels)
- Fix duplicate reports by using single session
- Add error handling so one account failure doesn't kill the run
- Add proper client disconnect on account add to prevent leaked tasks
- Remove deprecated WindowsSelectorEventLoopPolicy (removed in Python 3.16)
- Remove unused packages from requirements.txt
- Add .gitignore for sessions, __pycache__, and local files
- Fix typos and improve report output readability

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented Apr 16, 2026

Reviewer's Guide

Refactors the Telegram reporting script to use environment-based API credentials, safer session handling, and a more robust, readable reporting flow with improved error handling and cleanup of unused/deprecated components.

Sequence diagram for updated Telegram reporting flow

sequenceDiagram
    actor User
    participant Script
    participant Environment
    participant SessionsDir
    participant TelegramClient
    participant TelegramAPI

    User->>Script: Run reper.py -r N -t target -m mode
    Script->>Environment: Read TELEGRAM_API_ID, TELEGRAM_API_HASH
    Environment-->>Script: API_ID, API_HASH
    Script->>Script: Validate API credentials
    alt Missing credentials
        Script-->>User: Print error and exit
    else Credentials present
        Script->>SessionsDir: ac_session_numbers()
        SessionsDir-->>Script: [account_numbers]
        alt No accounts
            Script-->>User: Print "add an account" message and exit
        else At least one account
            Script->>TelegramClient: Create client for sessions/Ac1
            Script->>Script: asyncio.run(run_all_accounts())
            Script->>TelegramClient: report_channel(client)
            TelegramClient->>TelegramAPI: get_entity(target)
            alt Invalid target
                TelegramAPI-->>TelegramClient: ValueError
                TelegramClient-->>Script: Print invalid link and return
            else Valid target
                TelegramAPI-->>TelegramClient: entity
                TelegramClient->>TelegramAPI: iter_dialogs()
                TelegramAPI-->>TelegramClient: dialogs
                alt Entity is Channel and not in dialogs
                    TelegramClient->>TelegramAPI: JoinChannelRequest(entity)
                    TelegramAPI-->>TelegramClient: joined
                end
                Script->>Script: reason = mode_to_report_reason(mode)
                loop report_count times
                    TelegramClient->>TelegramAPI: ReportPeerRequest(peer=entity, reason, message)
                    alt Success
                        TelegramAPI-->>TelegramClient: ok
                        TelegramClient-->>User: Print OK with account name and counter
                    else Failure
                        TelegramAPI-->>TelegramClient: failure
                        TelegramClient-->>User: Print FAIL with account name and counter
                    end
                end
            end
        end
    end
Loading

Class diagram for new helper functions and reporting structure

classDiagram
    class ReperScriptModule {
        +ac_session_numbers() int[]
        +mode_to_report_reason(mode str) InputReportReason
        +report_channel(telegram_client TelegramClient) None
        +run_all_accounts() None
    }

    class TelegramClient {
        +start(phone_number str) None
        +disconnect() None
        +get_entity(peer) Entity
        +iter_dialogs() AsyncIterator
    }

    class InputReportReason {
    }

    class InputReportReasonSpam {
    }

    class InputReportReasonFake {
    }

    class InputReportReasonViolence {
    }

    class InputReportReasonChildAbuse {
    }

    class InputReportReasonPornography {
    }

    class InputReportReasonGeoIrrelevant {
    }

    class InputReportReasonOther {
    }

    class Channel {
    }

    ReperScriptModule --> TelegramClient : uses
    ReperScriptModule --> InputReportReason : returns
    InputReportReason <|-- InputReportReasonSpam
    InputReportReason <|-- InputReportReasonFake
    InputReportReason <|-- InputReportReasonViolence
    InputReportReason <|-- InputReportReasonChildAbuse
    InputReportReason <|-- InputReportReasonPornography
    InputReportReason <|-- InputReportReasonGeoIrrelevant
    InputReportReason <|-- InputReportReasonOther
    ReperScriptModule --> Channel : checks_type

    class EnvironmentConfig {
        +API_ID str
        +API_HASH str
        +load_from_env() None
    }

    ReperScriptModule --> EnvironmentConfig : reads_credentials
Loading

File-Level Changes

Change Details Files
Move API credentials to environment variables and validate configuration at startup.
  • Introduce TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables and remove hardcoded api_id/api_hash values
  • Parse TELEGRAM_API_ID as int and exit with a clear error message if either variable is missing before running
  • Import os and sys to support environment access and clean process termination
reper.py
Improve session/account management and account-add flow to avoid leaks and handle invalid numbers cleanly.
  • Replace mkdir with makedirs(exist_ok=True) for sessions directory creation
  • Add ac_session_numbers() helper to enumerate valid AcN.session files while ignoring journal/other files
  • Rework --add-number handling to compute next session path using ac_session_numbers, reuse a single TelegramClient, and always disconnect the client in a finally block
  • Improve success and error messages for account addition and ensure the script exits via sys.exit(0)
reper.py
Change reporting logic to use correct Telegram API types, support more reasons, and avoid channel-only assumptions.
  • Add mode_to_report_reason() mapping from CLI mode string to Telegram InputReportReason types, including a new trafficking mode mapped to InputReportReasonOther
  • Extend -m/--mode argument choices with trafficking and document it in the help/reasons output
  • Resolve the reporting target via client.get_entity instead of assuming a channel username and remove channel-only checks based on dialog.is_channel
  • Use account.ReportPeerRequest with a typed reason and message instead of messages.ReportRequest option-based flow, so users can be reported as well as channels
  • Guard JoinChannelRequest so it only applies when the target entity is a Channel and not already in dialogs, preventing crashes on user targets
reper.py
Simplify concurrency and error handling in the reporting run to avoid duplicate reports and stop one account failure from killing the whole run.
  • Change run_all_accounts() to use only the first available AcN session instead of dynamically exec-ing multiple clients, removing the previous multi-account fan-out pattern
  • Wrap report_channel logic in a broad try/except to catch and log per-account failures without raising to the top-level
  • Improve per-iteration report logging with clear success/failure messages including account name, iteration count, and target
reper.py
General CLI/output cleanup and compatibility updates for modern Python.
  • Fix various equality checks to use is not None / is None for argparse arguments and simplify the main conditional chain
  • Adjust error message for missing arguments to show correct example usage (reportReason spelling fix)
  • Drop the WindowsSelectorEventLoopPolicy usage implicitly by not importing or configuring it (now removed in Python 3.16)
  • Refine the default banner/usage output string formatting and remove the skull emoji for a cleaner banner
reper.py
Trim unused dependencies and add a .gitignore for local artifacts and sessions.
  • Remove asyncio and telegram from requirements.txt since asyncio is stdlib and telegram is unused
  • Add a .gitignore file to ignore session files, pycache, and local files (as described in the PR text, although exact patterns aren’t shown in the diff)
requirements.txt
.gitignore

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@kingkpink
Copy link
Copy Markdown
Author

This PR makes the output of the code execution cleaner and more understandable. It also lets the user use these TELEGRAM_API_ID and TELEGRAM_API_HASH env vars. And lots of bug fixes. Easy run and done.

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • Converting TELEGRAM_API_ID to int with api_id = int(API_ID) will raise a traceback on misconfigured env vars; consider validating the env values and exiting with a clear error message instead of relying on an uncaught ValueError.
  • ac_session_numbers() assumes the sessions directory exists; if this module is imported and the top-level makedirs('sessions', exist_ok=True) isn't run first, it will raise, so it may be safer for ac_session_numbers() itself to ensure the directory exists or handle FileNotFoundError.
  • The early exit when TELEGRAM_API_ID/HASH are missing prevents --help or --reasons from working in an unconfigured environment; consider deferring the env var check until a command that actually needs a Telegram client is requested.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Converting TELEGRAM_API_ID to int with `api_id = int(API_ID)` will raise a traceback on misconfigured env vars; consider validating the env values and exiting with a clear error message instead of relying on an uncaught ValueError.
- `ac_session_numbers()` assumes the `sessions` directory exists; if this module is imported and the top-level `makedirs('sessions', exist_ok=True)` isn't run first, it will raise, so it may be safer for `ac_session_numbers()` itself to ensure the directory exists or handle `FileNotFoundError`.
- The early exit when TELEGRAM_API_ID/HASH are missing prevents `--help` or `--reasons` from working in an unconfigured environment; consider deferring the env var check until a command that actually needs a Telegram client is requested.

## Individual Comments

### Comment 1
<location path="reper.py" line_range="71-72" />
<code_context>
+    print(f' [{Fore.RED}!{Fore.RESET}] Set TELEGRAM_API_ID and TELEGRAM_API_HASH environment variables.')
+    sys.exit(1)
+
+api_id = int(API_ID)
+api_hash = API_HASH
+
 if command_line_args.help:
</code_context>
<issue_to_address>
**issue:** Guard against non-numeric TELEGRAM_API_ID values to avoid a crash at startup.

`API_ID` is cast with `int(API_ID)` without checking the value. If `TELEGRAM_API_ID` is set but not strictly numeric (e.g., whitespace, token, or empty string), this will raise `ValueError` at startup. Please validate the env var first (e.g., `isdigit()` or `try/except ValueError` with a clear error message and exit) so misconfiguration fails cleanly instead of with a stack trace.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread reper.py
Comment on lines +71 to +72
api_id = int(API_ID)
api_hash = API_HASH
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue: Guard against non-numeric TELEGRAM_API_ID values to avoid a crash at startup.

API_ID is cast with int(API_ID) without checking the value. If TELEGRAM_API_ID is set but not strictly numeric (e.g., whitespace, token, or empty string), this will raise ValueError at startup. Please validate the env var first (e.g., isdigit() or try/except ValueError with a clear error message and exit) so misconfiguration fails cleanly instead of with a stack trace.

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