Skip to content

Dev#9

Merged
Silentely merged 10 commits intomainfrom
dev
Jun 8, 2025
Merged

Dev#9
Silentely merged 10 commits intomainfrom
dev

Conversation

@Silentely
Copy link
Copy Markdown
Member

@Silentely Silentely commented Jun 8, 2025

Summary by Sourcery

Introduce comprehensive i18n support and an optional Telegram userbot fallback for file fetching, update dependencies, adjust handler registration, and enhance logging and task models for userbot usage

New Features:

  • Add internationalization (i18n) support with locale files, localizer utilities, and related configuration

Enhancements:

  • Integrate optional Telegram userbot client to authenticate and fetch messages/files when primary client fails
  • Provide a CLI tool to generate i18n key constants
  • Update and bump numerous dependencies, including adding backoff and charmbracelet libraries
  • Refine dispatcher handler registration to skip channel/private chat events and propagate userbot usage in tasks and received files
  • Enhance logging and OS file‐removal utilities to use localized messages with a unified log template

Summary by CodeRabbit

  • New Features

    • Added internationalization (i18n) support, enabling localized messages and logs.
    • Introduced Telegram userbot integration, including terminal-based authentication and userbot-specific configuration options.
    • Enhanced file handling to optionally use a userbot client for file retrieval and downloads.
  • Improvements

    • Added new configuration options for language selection and userbot settings.
    • Improved logging with customizable templates and support for localized output.
    • Expanded error handling and status messages with localization.
  • Dependency Updates

    • Updated and added several dependencies to support new features and improve reliability.
  • Bug Fixes

    • Improved error messages and fallback mechanisms when fetching files or handling messages.
  • Chores

    • Added new middleware for Telegram client error recovery, retries, and flood wait handling.
    • Generated constants for i18n keys and added Simplified Chinese translations.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai bot commented Jun 8, 2025

Reviewer's Guide

This PR bumps numerous dependencies, integrates a full internationalization layer, adds a userbot-based fallback for file retrieval, refines dispatcher handler registration, and internationalizes logging and configuration messages.

Sequence Diagram for File Retrieval with Userbot Fallback

sequenceDiagram
    actor User
    participant BotApp as SaveAny-Bot Application
    participant BotClient as Primary Telegram Client
    participant UserClient as Fallback User Client
    participant TelegramAPI

    User->>BotApp: Send message with file link
    BotApp->>BotApp: parseLink(link)
    BotApp->>BotApp: tryFetchFileFromMessage(chatID, messageID)
    activate BotApp
    BotApp->>BotClient: FileFromMessage(chatID, messageID)
    activate BotClient
    BotClient->>TelegramAPI: Get file info/download
    TelegramAPI-->>BotClient: Respond (e.g., success or error)
    deactivate BotClient
    alt File fetch failed with BotClient (e.g., peer not found) AND UserClient enabled
        BotApp->>UserClient: FileFromMessage(chatID, messageID)
        activate UserClient
        UserClient->>TelegramAPI: Get file info/download
        TelegramAPI-->>UserClient: Respond
        deactivate UserClient
        UserClient-->>BotApp: File object / error
    else BotClient succeeded or UserClient not used
        BotClient-->>BotApp: File object / error
    end
    deactivate BotApp
    BotApp->>BotApp: Process file (e.g., add to queue, save)
    BotApp->>User: Notify status (e.g., "File processing started")
Loading

Class Diagram for the New Internationalization (i18n) Module

classDiagram
    class I18nModule {
        <<Module>>
        +Init(lang: string)
        +T(key: string, templateData: map) string
        +TWithLang(lang: string, key: string, templateData: map) string
        +TWithoutInit(lang: string, key: string, templateData: map) string
    }
    class Config {
        +Lang: string
    }
    class CmdRun {
        +InitAll()
    }
    class Logger {
        +Error(message: string)
        +Info(message: string)
    }
    Config --|> I18nModule : provides lang for Init
    CmdRun ..> I18nModule : calls Init()
    Logger ..> I18nModule : uses T() for messages
    note for I18nModule "Loads translations from locale/*.toml files"
Loading

File-Level Changes

Change Details Files
Bulk dependency upgrades and additions
  • Updated versions of core and indirect modules
  • Added i18n, userclient and UI related libraries
  • Synchronized go.mod and go.sum to match required dependencies
go.mod
go.sum
Internationalization support
  • Introduced i18n package with bundle and localizer
  • Embedded locale TOML files and generated key constants
  • Extended config to include lang setting and default
  • Replaced hardcoded messages with i18n.T and TWithoutInit
i18n/i18n.go
cmd/geni18n/main.go
i18n/locale/zh-Hans.toml
i18n/i18nk/keys.go
config/viper.go
cmd/run.go
common/os.go
Userbot fallback and context propagation
  • Added userclient package for phone-based login and session
  • Implemented tryFetchFileFromMessage with fallback to userbot
  • Propagated UseUserClient flag in ReceivedFile, Task and AddToQueue
  • Switched download API to use userclient when flag is set
  • Initialized userclient login in startup if enabled
userclient/auth.go
userclient/userclient.go
userclient/middlewares/recovery/recovery.go
userclient/middlewares/retry/retry.go
userclient/middlewares/middlewares.go
bot/handle_link.go
bot/handle_add_task.go
types/task.go
dao/model.go
core/download.go
cmd/run.go
Dispatcher handler registration tweaks
  • Renamed dispatcher parameter to disp for clarity
  • Added early-return filters for channel and chat message types
  • Standardized AddHandler calls on disp
bot/handlers.go
Logging and output templating
  • Removed default channel name override
  • Applied custom template to console and file handlers
  • Internationalized RmFileAfter debug and error messages
common/logger.go
common/os.go

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

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Jun 8, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces internationalization (i18n) support, adds a Telegram userbot client with authentication and middleware, and enhances file handling logic to optionally use the userbot for Telegram file retrieval. Numerous log and error messages are now localized. Dependency versions are updated, and new tooling for i18n key generation is included.

Changes

File(s) Change Summary
bot/handle_add_task.go, bot/handle_link.go, core/download.go, types/task.go, dao/model.go Added UseUserClient flag to file/task structs and logic; file retrieval and download can use userbot client.
bot/handlers.go Added chat/channel message handlers; updated parameter names and imports.
bot/handle_start.go Changed commit hash display to show full hash instead of truncated.
cmd/run.go, common/os.go, common/logger.go, config/viper.go Replaced hardcoded log/error messages with i18n; added language config; updated logging format.
go.mod Added and upgraded several dependencies, including i18n and userbot-related libraries.
i18n/i18n.go, i18n/i18nk/keys.go, i18n/locale/zh-Hans.toml Introduced i18n package, key constants, and Simplified Chinese translations.
cmd/geni18n/main.go Added a tool to auto-generate Go constants for i18n keys from TOML files.
userclient/auth.go, userclient/userclient.go Added userbot client with terminal authentication and context management.
userclient/middlewares/middlewares.go, userclient/middlewares/recovery/recovery.go, userclient/middlewares/retry/retry.go Introduced middleware for userbot client: recovery, retry, and floodwait handling.

Sequence Diagram(s)

Telegram File Retrieval with Optional Userbot

sequenceDiagram
    participant User
    participant Bot
    participant UserClient
    participant TelegramAPI

    User->>Bot: Sends message with file
    Bot->>Bot: Check UseUserClient flag
    alt UseUserClient is true and UserClient available
        Bot->>UserClient: Request file via userbot context
        UserClient->>TelegramAPI: Fetch file
        TelegramAPI-->>UserClient: Return file
        UserClient-->>Bot: File data
    else
        Bot->>TelegramAPI: Fetch file via bot context
        TelegramAPI-->>Bot: Return file
    end
    Bot->>Bot: Store UseUserClient flag in task
    Bot-->>User: Continue processing
Loading

Userbot Login Flow

sequenceDiagram
    participant App
    participant User
    participant UserClient
    participant TelegramAPI

    App->>UserClient: Initialize with config
    UserClient->>User: Prompt for phone/code/password
    User->>UserClient: Provide auth info
    UserClient->>TelegramAPI: Authenticate
    TelegramAPI-->>UserClient: Auth result
    UserClient->>App: Success or error
Loading

Poem

A rabbit hops with code anew,
Now logs can greet in every hue!
With userbots and i18n keys,
We fetch your files with greater ease.
From channels, chats, and terminal screens,
This bunny builds more global dreams!
🐇🌍✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0777c98 and 6e897a1.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (21)
  • bot/handle_add_task.go (3 hunks)
  • bot/handle_link.go (5 hunks)
  • bot/handle_start.go (1 hunks)
  • bot/handlers.go (1 hunks)
  • cmd/geni18n/main.go (1 hunks)
  • cmd/run.go (3 hunks)
  • common/logger.go (1 hunks)
  • common/os.go (1 hunks)
  • config/viper.go (5 hunks)
  • core/download.go (2 hunks)
  • dao/model.go (1 hunks)
  • go.mod (1 hunks)
  • i18n/i18n.go (1 hunks)
  • i18n/i18nk/keys.go (1 hunks)
  • i18n/locale/zh-Hans.toml (1 hunks)
  • types/task.go (1 hunks)
  • userclient/auth.go (1 hunks)
  • userclient/middlewares/middlewares.go (1 hunks)
  • userclient/middlewares/recovery/recovery.go (1 hunks)
  • userclient/middlewares/retry/retry.go (1 hunks)
  • userclient/userclient.go (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Silentely Silentely merged commit 2fd7d26 into main Jun 8, 2025
3 of 5 checks passed
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Hello @Silentely, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

Hello team, Gemini here with a summary of this pull request titled "Dev". Based on the changes, it appears this PR introduces significant enhancements by integrating a Telegram user client (userbot) for potentially more robust file fetching and adds internationalization (i18n) support to the bot's messages. It also includes dependency updates and minor logging improvements.

Highlights

  • User Client Integration: Adds support for logging in and using a Telegram user client (userbot) alongside the main bot client. This user client can be configured to handle fetching files from messages, potentially bypassing limitations of the standard bot API for certain chat types or large files. A new configuration section telegram.userbot is introduced.
  • Internationalization (i18n): Introduces internationalization capabilities using the go-i18n library. Message strings are moved to TOML locale files (i18n/locale/zh-Hans.toml is added), and the bot is updated to use translated messages based on the configured language (lang config option). A command-line tool (cmd/geni18n) is added to generate Go constants for message keys.
  • Dependency Updates: Updates several dependencies, including gotd/td, gorm.io/gorm, and adds new dependencies for i18n (go-i18n), terminal UI for userbot auth (charmbracelet/huh, log, color), and custom client middlewares (cenkalti/backoff, gotd/contrib).
  • Logging and Error Handling Improvements: Updates log messages in several places to use the new i18n system. Custom middlewares for user client connection recovery and RPC retries are added to improve robustness.
  • Bot Handler Filtering: Adds filters to the main bot handlers to ignore messages from channels and group chats by default, suggesting a focus on private chat interactions unless explicitly configured otherwise (though the filter is on chat type, not mentions).

Changelog

Click here to see the changelog
  • bot/handle_add_task.go
    • Imported userclient package.
    • Modified AddToQueue to conditionally use the user client's API for fetching files if record.UseUserClient is true and the user client is initialized (lines 157-164).
    • Added UseUserClient field to the types.Task struct when creating a new task (line 179).
  • bot/handle_link.go
    • Imported userclient package.
    • Added tryFetchFileFromMessage function to attempt fetching a file using the provided context's client, and fall back to the user client if specific errors occur (peer not found, unexpected message type) and the user client is enabled (lines 57-72).
    • Added tryFetchMessage function as a wrapper around GetTGMessage (lines 75-76).
    • Modified handleLinkMessage to use tryFetchFileFromMessage to get the file and the useUserClient flag (line 105).
    • Updated file name generation in handleLinkMessage to use tryFetchMessage to get the message object if needed (lines 112-117).
    • Added UseUserClient flag to the dao.ReceivedFile record when saving (line 127).
    • Added UseUserClient flag to the types.Task struct when creating a new task (line 145).
  • bot/handle_start.go
    • Changed the help command to display the full Git commit hash instead of a truncated version (line 38).
  • bot/handlers.go
    • Imported ext package.
    • Added new message handlers to filter out messages from channels and chats (groups) before the main checkPermission handler (lines 12-17).
    • Renamed the dispatcher variable from dispatcher to disp.
  • cmd/geni18n/main.go
    • Added a new command-line tool to generate Go constants for i18n message keys from TOML locale files.
    • Reads TOML files in ./i18n/locale, extracts keys from [[...]] sections using a regex (line 23).
    • Generates a Go file (i18n/i18nk/keys.go) with PascalCase constants for the extracted keys (lines 65-71).
  • cmd/run.go
    • Imported context, i18n, i18nk, and userclient packages.
    • Modified shutdown log messages to use i18n translated strings (lines 32-33).
    • Modified cache cleaning log messages and error messages to use i18n translated strings with template data (lines 39-65).
    • Added i18n.Init call in InitAll to initialize the i18n bundle (line 76).
    • Added conditional userclient.Login call in InitAll if userbot is enabled in config (lines 81-90).
  • common/logger.go
    • Removed slog.DefaultChannelName setting (line 16).
    • Added a custom log template string (line 26).
    • Applied the custom log template to the console handler (line 28).
    • Applied the custom log template to the file handler if configured (line 37).
  • common/os.go
    • Imported i18n and i18nk packages.
    • Modified log messages in RmFileAfter to use i18n translated strings with template data (lines 15-18, 21-24, 27-30).
  • config/viper.go
    • Imported errors, i18n, and i18nk packages.
    • Added Lang field to the Config struct (line 17).
    • Added Userbot struct to telegramConfig with Enable and Session fields (lines 64-67).
    • Set default values for lang, telegram.userbot.enable, and telegram.userbot.session (lines 95, 106-107).
    • Changed error messages and info messages in Init to use i18n translated strings, including using the new TWithoutInit function for errors that occur before full i18n initialization (lines 145-148, 152-154, 160-163).
  • core/download.go
    • Imported userclient package.
    • Modified the download logic in processPendingTask to use the user client's API (userclient.UC.API()) if task.UseUserClient is true and the user client is initialized (lines 66-69).
  • dao/model.go
    • Added UseUserClient boolean field to the ReceivedFile struct to track if the userbot was used to fetch the file (line 19).
  • go.mod
    • Updated various dependencies, including gotd/td, gorm.io/gorm, golang.org/x/net, golang.org/x/time, golang.org/x/exp, golang.org/x/tools, minio/minio-go, duke-git/lancet.
    • Added new dependencies: github.com/nicksnyder/go-i18n/v2, github.com/charmbracelet/huh, github.com/charmbracelet/log, github.com/fatih/color, github.com/cenkalti/backoff/v4, github.com/gotd/contrib, and several charmbracelet/x packages.
  • go.sum
    • Updated checksums corresponding to the go.mod changes.
  • i18n/i18n.go
    • Added a new package for internationalization.
    • Uses go-i18n to load locale files embedded in the binary.
    • Provides Init function to load messages and set the default language.
    • Provides T function for translating message keys using the initialized localizer.
    • Provides TWithLang for translating with a specific language.
    • Provides TWithoutInit for translating before Init is called (used in config loading).
  • i18n/i18nk/keys.go
    • Added a new file containing Go constants for i18n message keys.
    • This file is generated by the cmd/geni18n tool.
  • i18n/locale/zh-Hans.toml
    • Added a new TOML file containing Simplified Chinese translations for various bot messages and log strings.
  • types/task.go
    • Added UseUserClient boolean field to the Task struct to indicate if the task should use the user client for downloading (line 19).
  • userclient/auth.go
    • Added a new package and file for user client authentication.
    • Defines termialAuthConversator which implements gotgproto.AuthConversator using charmbracelet/huh for interactive phone number, code, and password input in the terminal.
  • userclient/middlewares/middlewares.go
    • Added a new package and file for user client Telegram client middlewares.
    • Provides NewDefaultMiddlewares function to create a slice of default middlewares including custom recovery and retry logic.
  • userclient/middlewares/recovery/recovery.go
    • Added a new package and file implementing a custom gotd/td middleware.
    • This middleware uses cenkalti/backoff for exponential backoff and retries requests if non-Telegram business errors occur.
  • userclient/middlewares/retry/retry.go
    • Added a new package and file implementing a custom gotd/td middleware.
    • This middleware retries requests up to a maximum number of attempts if specific internal or RPC errors occur.
  • userclient/userclient.go
    • Added a new package and file for managing the user client.
    • Provides a global UC variable to hold the user client instance.
    • Provides GetCtx function to get an ext.Context from the user client.
    • Provides Login function to log in the user client using the configured session path and the termialAuthConversator for interactive authentication.
    • Uses the custom recovery and retry middlewares during client initialization.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces significant and valuable features, including internationalization (i18n) support, an optional Telegram userbot fallback for fetching files, and various enhancements to logging, configuration, and task handling. The integration of the userbot client for authentication and message/file fetching is a notable improvement for robustness. The i18n implementation is comprehensive, complete with locale files and a generation tool for keys.

Overall, the changes are well-structured. I've identified a few areas for improvement, primarily concerning context management for the user client, error handling robustness, and clarification on some handler logic. Addressing these points will further enhance the quality and reliability of the new features.

Summary of Findings

  • Context Management for User Client: The userclient.GetCtx() function incorrectly caches and reuses a single global ext.Context. This is a high-severity issue that can lead to race conditions and incorrect behavior. Each operation should obtain a fresh context.
  • Error Handling Robustness: In bot/handle_link.go, error checking in tryFetchFileFromMessage relies on string matching, which is brittle. It should ideally check for specific error types/codes.
  • Userbot Fallback Consistency: The tryFetchMessage function in bot/handle_link.go lacks a userbot fallback mechanism, unlike tryFetchFileFromMessage. This could be an area for enhancing robustness.
  • Handler Scope Clarification: The new ChatTypeChat filter in bot/handlers.go needs confirmation regarding its intended scope, particularly concerning "regular" Telegram groups.
  • i18n Key Generation Regex (Not Commented): The regex in cmd/geni18n/main.go for extracting TOML keys is functional for current simple keys but might not handle more complex TOML key specifications if used in the future. (Severity: low, not commented directly per settings).

Merge Readiness

This pull request introduces substantial and valuable enhancements. However, there is a high-severity issue related to ext.Context management in the user client (userclient.GetCtx()) that needs to be addressed to prevent potential race conditions and incorrect behavior. Additionally, there are a few medium-severity items concerning error handling robustness and handler logic clarity that would benefit from review and potential adjustment.

I recommend addressing these issues, particularly the high-severity context management problem, before merging. As an AI reviewer, I am not authorized to approve pull requests; please ensure further review and approval from other maintainers.

Comment thread userclient/userclient.go
Comment on lines +17 to +24
var ectx *ext.Context

func GetCtx() *ext.Context {
if ectx != nil {
return ectx
}
ectx = UC.CreateContext()
return ectx
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

high

The GetCtx() function caches and reuses a single global ext.Context instance (ectx). This is generally unsafe because ext.Context instances are often intended to be short-lived and specific to a single operation or update. Reusing a single instance across multiple concurrent operations can lead to race conditions, incorrect state, or issues with context cancellation.

It's recommended that each logical operation requiring a user client context obtains a fresh one by calling UC.CreateContext(). Consider removing the global ectx variable and modifying GetCtx() to always return a new context from UC.CreateContext(). You might also want to rename GetCtx to something like CreateUserClientContext to better reflect its behavior if it always creates a new one.

var UC *gotgproto.Client
// var ectx *ext.Context // Remove global cached context

// GetCtx should return a new context for each call.
// Consider renaming to CreateUserClientContext or similar.
func GetCtx() *ext.Context {
	if UC == nil {
		// This case should ideally not happen if Login is always called first.
		// Panic or return an error to indicate UC is not initialized.
		common.Log.Panic("User client (UC) is not initialized when calling GetCtx")
		return nil // Or handle error more gracefully
	}
	return UC.CreateContext()
}

Comment thread bot/handle_link.go
if err == nil {
return file, false, nil
}
if (strings.Contains(err.Error(), "peer not found") || strings.Contains(err.Error(), "unexpected message type")) && userclient.UC != nil {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The current method of checking for specific errors by matching substrings (e.g., "peer not found", "unexpected message type") can be brittle if the underlying error messages change in future library updates. Could we make this more robust, perhaps by checking for specific error types or codes if the Telegram library exposes them (e.g., using tgerr.Is or checking *tgerr.Error fields)? If not, defining these substrings as constants might be a small improvement for maintainability.

Comment thread bot/handle_link.go
Comment on lines +75 to +77
func tryFetchMessage(ctx *ext.Context, chatID int64, messageID int) (*tg.Message, error) {
return GetTGMessage(ctx, chatID, messageID)
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

The tryFetchMessage function currently only wraps GetTGMessage and doesn't seem to implement a userbot fallback, unlike tryFetchFileFromMessage. If GetTGMessage fails (e.g., due to errors like "peer not found"), could it also benefit from an attempt with the userbot client, especially when this function is used to generate a filename if file.FileName is initially empty? This would enhance consistency and robustness.

Comment thread bot/handlers.go
Comment on lines +12 to +17
disp.AddHandler(handlers.NewMessage(filters.Message.ChatType(filters.ChatTypeChannel), func(ctx *ext.Context, u *ext.Update) error {
return dispatcher.EndGroups
}))
disp.AddHandler(handlers.NewMessage(filters.Message.ChatType(filters.ChatTypeChat), func(ctx *ext.Context, u *ext.Update) error {
return dispatcher.EndGroups
}))
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

These new handlers are designed to skip events from channels and certain private chats by returning dispatcher.EndGroups. The handler for filters.Message.ChatType(filters.ChatTypeChat) will affect 1-on-1 private chats (not with the bot) and also "regular" Telegram groups (distinct from supergroups).

Could you confirm if the intent is to ignore messages from regular groups as well? If the bot is expected to function in regular groups, this filter might prevent that. If it's intended only for supergroups and DMs with the bot, then this setup (along with the subsequent filters.Message.All handler) should work as expected.

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 @Silentely - I've reviewed your changes - here's some feedback:

  • In userclient.Login's goroutine, add an early return after sending the error to the res channel to avoid sending two responses and potential deadlocks.
  • Global ectx in userclient.GetCtx is reused across all calls and may introduce context reuse or concurrency issues—consider returning a fresh context per operation or synchronizing access.
  • TWithoutInit rebuilds the i18n bundle and reloads locale files on every invocation, which can be expensive—cache the parsed bundle or localizer to avoid repeated file reads.
Here's what I looked at during the review
  • 🟡 General issues: 2 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Documentation: all looks good

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 userclient/userclient.go
Middlewares: middlewares.NewDefaultMiddlewares(ctx, 5*time.Minute),
},
)
if err != nil {
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 (bug_risk): Missing return after sending error result in Login goroutine

After sending the error to the res channel, add a return to avoid a second send and prevent the goroutine from blocking.

Comment thread userclient/userclient.go
Comment on lines +16 to +25
var UC *gotgproto.Client
var ectx *ext.Context

func GetCtx() *ext.Context {
if ectx != nil {
return ectx
}
ectx = UC.CreateContext()
return ectx
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (bug_risk): Caching a single ext.Context globally is unsafe

Storing a package-level *ext.Context can cause stale context reuse and race conditions. It's safer to return a new context from UC.CreateContext() each time.

Suggested change
var UC *gotgproto.Client
var ectx *ext.Context
func GetCtx() *ext.Context {
if ectx != nil {
return ectx
}
ectx = UC.CreateContext()
return ectx
}
var UC *gotgproto.Client
func GetCtx() *ext.Context {
return UC.CreateContext()
}

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.

2 participants