Skip to content

Conversation

@AshokShau
Copy link
Owner

@AshokShau AshokShau commented May 8, 2025

Summary by Sourcery

Create a Telegram bot for MongoDB backup and restore operations using PyTDBot, enabling users to create and import database backups directly through Telegram commands

New Features:

  • Implement MongoDB backup functionality with support for .gz and .json formats
  • Add MongoDB import/restore capability via Telegram file upload
  • Create bot commands for backup, restore, and system information

Enhancements:

  • Develop robust URI extraction and validation
  • Implement secure URI sanitization for display
  • Create flexible backup and restore utility functions

Deployment:

  • Create Dockerfile for containerized deployment
  • Add GitHub Actions workflow for code quality checks

Documentation:

  • Add comprehensive README with project badges and feature descriptions
  • Include inline documentation for bot commands and utility functions

@sourcery-ai
Copy link

sourcery-ai bot commented May 8, 2025

Reviewer's Guide

This pull request implements a Telegram bot for MongoDB backup and restore operations using the PyTDBot library. The core functionality is achieved by wrapping mongodump and mongorestore shell commands, triggered by user commands parsed via custom filters; the bot handles multiple backup formats and manages temporary files, with the project including Docker support, CI, and standard Python packaging.

File-Level Changes

Change Details Files
Implemented MongoDB backup and restore functionality using shell commands.
  • Added a command handler for initiating backup and import operations via Telegram messages.
  • Integrated mongodump to create database backups, supporting .gz and zipped .json output formats.
  • Integrated mongorestore to restore databases from provided .gz or .zip backup files.
  • Included logic for parsing MongoDB URIs from commands, selecting appropriate backup formats, and cleaning up temporary files post-operation.
src/modules/mongo.py
src/modules/utils/_mongo.py
Established the bot's PyTDBot framework and added informational command handlers.
  • Set up the main PyTDBot client, including plugin loading for modular command handling and bot lifecycle management.
  • Implemented handlers for user-facing informational commands such as /start, /help, /ping (with latency and uptime), and /privacy.
  • Added support for loading essential configurations like API credentials and bot token from environment variables.
src/__init__.py
src/__main__.py
src/modules/start.py
src/config.py
Developed custom utilities for improved command parsing and argument extraction.
  • Created custom PyTDBot filters to enable more flexible and robust command matching, accommodating various prefixes and bot mentions.
  • Added a utility function to reliably extract arguments from the text of incoming command messages.
src/modules/utils/_filters.py
src/modules/utils/_extract.py
Introduced project infrastructure for building, deploying, and maintaining the bot.
  • Created a Dockerfile for building a containerized version of the bot, including Python dependencies and MongoDB database tools.
  • Defined project metadata, dependencies, and entry points using pyproject.toml.
  • Added a comprehensive README.md with instructions on features, commands, and setup.
  • Set up a GitHub Actions workflow for automated code linting (Ruff) and formatting (Black) to ensure code quality.
Dockerfile
pyproject.toml
README.md
.github/workflows/code-fixer.yml
.gitignore
.dockerignore
.github/CODEOWNERS
uv.lock

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

Copy link

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

  • Consider replacing create_subprocess_shell with create_subprocess_exec for safer execution of external commands.
  • Ensure temporary directories created during ZIP file imports are cleaned up after the restore operation.
  • Consider restricting the /mongo command to authorized users (e.g., using OWNER_ID from config) to prevent unintended database access.
Here's what I looked at during the review
  • 🟡 General issues: 3 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.

stderr=asyncio.subprocess.PIPE
)

stdout, stderr = await proc.communicate()
Copy link

Choose a reason for hiding this comment

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

suggestion: Consider using a logger instead of print for error reporting.

run_mongodump prints errors directly; switching to our logger ensures consistency and better log level control.

Suggested implementation:

import asyncio
import logging

logger = logging.getLogger(__name__)
        logger.error(f"[mongodump error]: {stderr.decode()}")

• If your file already imports logging or defines a logger instance, adjust the changes accordingly by only replacing the print() with logger.error().

Comment on lines +45 to +48
if shutil.which("mongodump") is None:
print("❌ mongodump is not installed. Please install MongoDB tools:")
print("• Arch: yay -S mongodb-tools-bin")
print("• Ubuntu/Docker: use official .tgz tools from https://www.mongodb.com/try/download/database-tools")
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Consider handling missing mongodump as an error rather than just printing.

Instead of continuing, exit or raise an exception to stop execution and avoid later failures.

Suggested change
if shutil.which("mongodump") is None:
print("❌ mongodump is not installed. Please install MongoDB tools:")
print("• Arch: yay -S mongodb-tools-bin")
print("• Ubuntu/Docker: use official .tgz tools from https://www.mongodb.com/try/download/database-tools")
if shutil.which("mongodump") is None:
raise RuntimeError("❌ mongodump is not installed. Please install MongoDB tools:\n• Arch: yay -S mongodb-tools-bin\n• Ubuntu/Docker: use official .tgz tools from https://www.mongodb.com/try/download/database-tools")

@@ -0,0 +1,64 @@
# MongoDB Backup Bot 📦

A Telegram bot built using [PyTDBot](https://github.com/pytdbot/client) to backup and restore MongoDB databases.
Copy link

Choose a reason for hiding this comment

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

suggestion (typo): Consider using 'to back up' instead of 'to backup'.

Use “to back up” (two words) as the standard verb form, e.g., “...to back up and restore...”.

Suggested change
A Telegram bot built using [PyTDBot](https://github.com/pytdbot/client) to backup and restore MongoDB databases.
A Telegram bot built using [PyTDBot](https://github.com/pytdbot/client) to back up and restore MongoDB databases.

"""Extract MongoDB URI from text."""
uri_pattern = r"(mongodb(?:\+srv)?:\/\/[a-zA-Z0-9\-._~:\/?#[\]@!$&'()*+,;=]+)"
match = re.search(uri_pattern, text)
return match.group(0) if match else None
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Replace m.group(x) with m[x] for re.Match objects (use-getitem-for-re-match-groups)

Suggested change
return match.group(0) if match else None
return match[0] if match else None

@AshokShau AshokShau merged commit 0e33fde into master May 8, 2025
1 check passed
@AshokShau AshokShau deleted the dev branch May 8, 2025 11:26
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