KEEP YOUR API KEYS SAFE AND WARM BCZ ITS ALL ABOUT API KEY AND ADMINCHAT ID WHICH IS GIVEN IF SOMEONE GOT YOUR API KEY AND CHAT ID YOUR DEVICE CAN BE COOKED SO STAY SAFE KEEP THEM SECURED
THIS BOT IS HIGLY ADVANCED SO THAT NOONE CAN ACCESS ITS CONTENT AND ONLY CAN TRY TO SEND THE MESSAGES AND BRUTE THE SOFTWARE OF TELEGRAM MAKE SURE TO KEEP YIUR API SECURE THEN EVERYTHING WILL BE FINEST EVEN WITH API KEY HACKERS CANT ACCESS YOUR CONTENT UNTILL AND UNLESS YOU ADD THEM TO CHAT_ID !! BCZ OF /START (INFINITE) DEVICES
open it create new bot then paste its API KEY into this script
start - Starts the bot or brings it back online and optionally sets or switches the device context
match - Searches for a specified file by path and sends it if found or prompts for the full file path if not provided
git - Prompts for a GitHub repository URL and clones the repository while reporting its size
writecontrol - Activates WriteControl mode where subsequent plain text messages are executed as shell commands
cat - Prompts for a file path and then displays the file content sending it as a document if too long
stop - Puts the bot into offline mode to minimize network usage only start can reactivate it
cd - Changes the working directory for the active device context
ls - Lists the contents of the current directory with icons and file sizes
pwd - Displays the current working directory for the active device
devices - Lists all active device contexts along with their current directories and last active times- READ THIS GUIDE ✨
Made by: Shainshub
GitHub: Shubsaini08-GITHUB
- Overview
- Features
- Architecture & Design
- Installation & Setup
- Code Walkthrough & Detailed Explanations
- Import Statements & Dependencies
- Global Configuration & Variables
- Utility Functions
- Command Handlers
- Start Command (/start)
- Match Command (/match)
- Git Command (/git)
- WriteControl Command (/writecontrol)
- Cat Command (/cat)
- Stop Command (/stop)
- Change Directory Command (/cd)
- List Directory Command (/ls)
- Print Working Directory Command (/pwd)
- Devices Command (/devices)
- Plain Text Handler & WriteControl Mode
- Background Connectivity Monitor
- Main Function & Bot Initialization
- Flowcharts & Command Workflow Diagrams
- Command Execution Tables & Descriptions
- Advanced Multi-Device Support
- Security Considerations & Best Practices
- Error Handling & Logging
- Deployment, Troubleshooting & Future Enhancements
- Appendix: Additional Diagrams & Tables
- Conclusion
This project is a Python-based Telegram bot that provides remote control over a system through the Telegram messaging platform. The script, telecontrol.py, allows authorized administrators to execute a wide range of system operations (e.g., cloning repositories, executing shell commands, navigating directories, file management) by sending specific commands via Telegram.
The bot’s design focuses on:
- Multi-device support: Allowing control over different “device contexts” for separate sessions.
- Security: Strict access control via a list of authorized admin IDs.
- Extensibility: Modular functions that can be expanded or modified for additional commands.
- Robustness: Background connectivity monitoring and error handling to ensure reliable operations.
- Telegram Integration: Uses the Telegram Bot API for real-time command execution.
- Remote Shell Execution: Supports shell command execution (with safety via admin checks).
- File Management: Provides commands to view, send, and manage files on the host system.
- GitHub Repository Cloning: Clones repositories from GitHub and reports repository size.
- Directory Navigation: Change directories, list contents with file sizes and icons.
- Device Contexts: Multi-session support enabling management of multiple device contexts.
- Connectivity Monitoring: Background thread checks network connectivity and alerts admins.
- Offline Mode: Ability to put the bot into a low-network-usage state.
- Dynamic Command Execution: Uses context-based handlers to interpret plain text messages.
- Logging & Error Reporting: Robust error handling and logging for maintenance and debugging.
The architecture of telecontrol.py is designed around several core components:
- Bot Configuration: Global variables and constants define the bot token, admin IDs, and mode flags.
- Utility Functions: Encapsulate common tasks such as sending messages/files, computing directory sizes, and reading file content.
- Command Handlers: Each Telegram command (e.g.,
/start,/match) is handled by a dedicated function decorated to enforce admin-only access. - Multi-threading: A background thread monitors network connectivity independently from the main command polling.
- Device Contexts: A dictionary to track different devices/sessions with their own current working directory and last activity time.
- Main Function: Initializes the bot application and registers all command handlers before entering the polling loop.
To install and run telecontrol.py, follow these steps:
-
Clone the Repository:
git clone https://github.com/Shubsaini08/telecontrol.git cd telecontrol -
Install Dependencies:
Ensure you have Python 3.8+ installed. Install required packages using pip:pip install python-telegram-bot requests
Additional dependencies include standard libraries (os, time, logging, subprocess, shutil, threading).
-
Configure the Bot:
- Open the script and set your bot token in the
BOT_TOKENvariable. - Add your Telegram admin IDs to the
ADMIN_IDSlist.
- Open the script and set your bot token in the
-
Run the Bot:
Simply execute the script:python telecontrol.py
The bot will start polling for updates and will begin executing commands received from authorized Telegram users.
Below is a thorough explanation of every section of the code.
The top section imports all necessary modules:
- os, time, logging, subprocess, requests, shutil:
These provide file system manipulation, process management, and HTTP request capabilities. - Thread from threading:
Enables running the connectivity monitor as a separate thread. - telegram & telegram.ext modules:
Core libraries for interacting with the Telegram Bot API, handling updates, and command dispatch.
Each import is chosen for its reliability and built-in support in Python to ensure portability and maintainability of the bot.
Several global variables define the operating state:
- BOT_TOKEN: The API token to authenticate with Telegram.
- ADMIN_IDS: A list of chat IDs that are permitted to issue commands to the bot.
- OFFLINE_MODE & WRITECONTROL_ACTIVE: Flags to control bot state (offline mode restricts operations; WriteControl mode enables shell command execution).
- current_device & device_contexts:
current_devicetracks which device context is active.device_contextsis a dictionary mapping device IDs to their current working directory and last activity timestamp.
These variables ensure that the bot can easily switch between different sessions and maintain state over time.
The script defines multiple helper functions to modularize tasks:
-
send_message(text):
- Purpose: Sends a text message to all authorized admin chat IDs using the Telegram Bot API.
- How: Iterates over each admin ID, constructs the request URL, and uses the
requestslibrary to POST the message.
-
send_file(file_path):
- Purpose: Sends a file as a document to all authorized admins.
- How: Opens the file in binary mode and uses multipart/form-data POST requests.
-
compute_directory_size(path):
- Purpose: Recursively calculates the total size of a directory.
- How: Uses
os.walkto traverse the directory and accumulates file sizes.
-
send_file_content(file_path):
- Purpose: Reads the content of a file (with error handling) and returns it as a string.
-
is_authorized(update):
- Purpose: Checks if the message sender is in the list of authorized admin IDs.
-
restricted_command(func):
- Purpose: A decorator that wraps command handlers to enforce that only authorized users can execute commands.
- Additional Behavior: It also checks if the bot is in offline mode and only allows the
/startcommand in that state.
These utility functions form the backbone of the bot’s operational logic, ensuring modularity and reusability.
Each command that the bot handles is implemented as an asynchronous function decorated with @restricted_command. Below is an explanation of each:
- Function:
start_command(update, context) - Behavior:
- Accepts an optional device number (e.g.,
/start 1). - Switches or initializes the device context.
- If the bot is in offline mode, it brings it back online.
- Accepts an optional device number (e.g.,
- Steps:
- Parse the optional argument for the device ID.
- Update or create the device context.
- Set
OFFLINE_MODEtoFalseand resetWRITECONTROL_ACTIVEif necessary. - Notify the admin of the bot status via a reply message and a broadcast message.
- Flowchart: See Start Command Flowchart.
- Function:
match_command(update, context) - Behavior:
- Searches for a file if the file path is provided as an argument.
- If no path is provided, it asks the user to input the file path.
- Steps:
- Check if command arguments are provided.
- Verify if the file exists; if it does, send the file.
- Otherwise, prompt the admin to provide the full file path.
- Key Point: It leverages the utility function
send_filefor file transmission.
- Function:
git_command(update, context) - Behavior:
- Prompts the admin to provide a GitHub repository URL.
- On receiving the URL (via the plain text handler), it clones the repository and calculates its size.
- Steps:
- Send a prompt message asking for the repository URL.
- Set a context flag (
awaiting_git_repo) to signal that the next plain text message is a URL. - In the plain text handler, use
subprocess.check_callto executegit clone. - Compute the directory size using
compute_directory_size.
- Flowchart: See Git Command Flowchart.
- Function:
writecontrol_command(update, context) - Behavior:
- Activates WriteControl mode so that any subsequent plain text message is treated as a shell command.
- Steps:
- Set the global flag
WRITECONTROL_ACTIVEtoTrue. - Notify the admin that full system command execution control is now active.
- Set the global flag
- Security Consideration: This mode should be used with extreme caution as it allows shell command execution on the host.
- Function:
cat_command(update, context) - Behavior:
- Prompts the admin to provide the full file path to read its contents.
- Steps:
- Prompt the admin with a message asking for a file path.
- Set a context flag (
awaiting_cat) to indicate the next text should be interpreted as a file path. - In the plain text handler, read and return the file content (or send as a document if too long).
- Note: Uses
send_file_contentfor reading file content and handles errors gracefully.
- Function:
stop_command(update, context) - Behavior:
- Puts the bot into offline mode to reduce network usage.
- Steps:
- Set
OFFLINE_MODEtoTrue. - Disable WriteControl mode by setting
WRITECONTROL_ACTIVEtoFalse. - Notify the admin that the bot is now offline.
- Set
- Implication: When offline, only the
/startcommand can bring the bot back online.
- Function:
cd_command(update, context) - Behavior:
- Changes the working directory for the active device context.
- Steps:
- Parse the provided directory path.
- Determine if the path is absolute or relative.
- Construct the absolute path and check if it exists.
- Update the current device context’s working directory.
- Edge Cases: Handles non-existent directories by sending an error message.
- Function:
ls_command(update, context) - Behavior:
- Lists the contents of the current directory, showing directories with a “💽” icon and files with a “📁” icon.
- Steps:
- Retrieve the current directory from the active device context.
- List all entries using
os.listdir. - For directories, compute the total size recursively.
- Format the results into a string and send the reply.
- Flowchart: See List Directory Flowchart.
- Function:
pwd_command(update, context) - Behavior:
- Simply replies with the current working directory for the active device context.
- Steps:
- Retrieve the current directory.
- Send a reply with the current directory path.
- Function:
devices_command(update, context) - Behavior:
- Lists all active device contexts sorted by the last active time.
- Steps:
- Iterate over the
device_contextsdictionary. - Sort the devices by their last active timestamp.
- Format and reply with a summary for each device.
- Iterate over the
- Benefit: Allows admins to quickly see the state of multiple sessions.
- Function:
handle_text(update, context) - Behavior:
- Interprets plain text messages based on the current context:
- If waiting for a GitHub URL, it will attempt to clone a repository.
- If waiting for a file path for
/matchor/cat, it processes accordingly. - If WriteControl mode is active, the plain text is treated as a shell command and executed.
- Interprets plain text messages based on the current context:
- Steps:
- Check context flags (
awaiting_git_repo,awaiting_match,awaiting_cat). - If any flag is set, process the message according to the expected behavior.
- If WriteControl mode is active, execute the text as a shell command using
subprocess.Popen. - Capture and send the output or errors back to the admin.
- Check context flags (
- Important: Timeout and exception handling ensure that runaway processes are avoided.
- Function:
monitor_connectivity() - Behavior:
- Runs continuously in a background thread to check network connectivity.
- Uses a ping command (
ping -c 1 8.8.8.8) to check if the internet is accessible. - Notifies all admins if the connectivity check fails.
- Steps:
- Enters an infinite loop.
- Executes the ping command and checks the return code.
- Sends a warning message if the ping fails.
- Waits 60 seconds before the next check.
- Justification: Helps in proactively detecting network issues so that admins can take corrective action.
- Function:
main() - Behavior:
- Starts the connectivity monitoring thread.
- Builds the Telegram bot application using
Application.builder(). - Registers all the command handlers with the bot.
- Initiates polling to start receiving and processing updates.
- Steps:
- Start a daemon thread for connectivity monitoring.
- Create the bot application with the provided token.
- Add handlers for each command (e.g.,
/start,/match,/git, etc.). - Add a general text handler for messages that aren’t commands.
- Run the polling loop, which keeps the bot active.
- Flowchart: See Main Function Flowchart.
Below are several flowcharts illustrating the command workflows and overall architecture of the bot.
flowchart TD
A[/start Command Received/] --> B{Arguments Provided?}
B -- Yes --> C[Extract device ID from args]
B -- No --> D[Set default device ID ("1")]
C --> E{Device Context Exists?}
D --> E
E -- Yes --> F[Update last active timestamp]
E -- No --> G[Create new device context with current directory]
F --> H[Check if OFFLINE_MODE is True]
G --> H
H -- Yes --> I[Set OFFLINE_MODE=False and reset WRITECONTROL_ACTIVE]
H -- No --> J[Proceed normally]
I --> K[Reply: "Bot is back online on device X"]
J --> L[Reply: "Bot started on device X"]
K --> M[Send broadcast message to all admins]
L --> M
flowchart TD
A[/git Command Received/] --> B[Reply: "Please provide GitHub URL"]
B --> C[Set awaiting_git_repo flag = True]
C --> D[Next plain text message received]
D --> E[Extract repository URL from message]
E --> F[Execute git clone via subprocess]
F --> G{Clone Successful?}
G -- Yes --> H[Compute repository size]
G -- No --> I[Reply with error message]
H --> J[Reply with success message and repo size]
flowchart TD
A[Plain Text Message Received] --> B{Is awaiting_git_repo True?}
B -- Yes --> C[Process as GitHub URL]
B -- No --> D{Is awaiting_match True?}
D -- Yes --> E[Process as file path for /match]
D -- No --> F{Is awaiting_cat True?}
F -- Yes --> G[Process as file path for /cat]
F -- No --> H{Is WRITECONTROL_ACTIVE True?}
H -- Yes --> I[Execute text as shell command]
H -- No --> J[Reply: "No action assigned for this message"]
flowchart TD
A[Start Main Function] --> B[Start connectivity monitor thread]
B --> C[Build Telegram bot application]
C --> D[Register command handlers (/start, /match, /git, etc.)]
D --> E[Register plain text handler]
E --> F[Enter polling loop]
F --> G[Bot continuously processes updates]
Below is a detailed table summarizing each command, its description, execution flow, and key functions:
| Command | Description | Key Functions & Steps | Notes |
|---|---|---|---|
/start |
Starts the bot or brings it back online; supports optional device context switching. | 1. Parse device ID from args. 2. Create/update device context. 3. Set OFFLINE_MODE/WRITECONTROL_ACTIVE. 4. Reply with status message. |
Initializes the session; only allowed command in offline mode. |
/match |
Searches for a file based on provided path or prompts for a complete file path. | 1. Check for argument presence. 2. Validate file existence. 3. Send file if found. 4. Prompt if not provided. |
Uses send_file() utility. |
/git |
Clones a GitHub repository; expects a repository URL in the next plain text message. | 1. Prompt admin for URL. 2. Set flag ( awaiting_git_repo).3. Execute git clone on receiving URL.4. Compute directory size. |
Leverages subprocess calls; error handling for clone failures. |
/writecontrol |
Activates WriteControl mode, treating any plain text as a shell command. | 1. Set WRITECONTROL_ACTIVE flag to True.2. Notify admin of full control. |
Highly sensitive; ensure only trusted admins can trigger. |
/cat |
Reads and displays the content of a file; sends as a document if content is too long. | 1. Prompt admin for file path. 2. Set flag ( awaiting_cat).3. Read file using send_file_content().4. Send output or file as document if too long. |
Useful for quickly inspecting file contents without logging into the system directly. |
/stop |
Puts the bot into offline mode (reduces network usage); only /start can re-enable. |
1. Set OFFLINE_MODE to True.2. Reset WRITECONTROL_ACTIVE.3. Notify admin of state change. |
Prevents further command execution except /start until reactivated. |
/cd |
Changes the working directory of the active device. | 1. Parse provided directory path. 2. Construct absolute path. 3. Validate existence. 4. Update the device context’s directory. |
Allows relative and absolute paths; essential for file system navigation. |
/ls |
Lists the contents of the current working directory, including file sizes and type icons. | 1. Retrieve current directory. 2. Use os.listdir.3. For directories, compute recursive size. 4. Format output with icons and sizes. |
Provides a user-friendly view of the file system’s state. |
/pwd |
Displays the current working directory of the active device. | 1. Retrieve current directory from device context. 2. Reply with directory path. |
A simple but essential command for orientation. |
/devices |
Lists all active device contexts with their current directories and last active times. | 1. Iterate over device_contexts.2. Sort by last active timestamp. 3. Format and reply with details. |
Helps in managing and tracking multiple sessions. |
| Plain Text Input | Varies based on context: Git URL for /git, file paths for /match and /cat, or shell commands in WriteControl mode. |
1. Check context flags (awaiting_git_repo, awaiting_match, awaiting_cat).2. Process accordingly. 3. If none, check for WriteControl mode and execute shell command if active. |
Central dispatcher for non-command messages; critical for dynamic behavior. |
The script supports multi-device control by maintaining a dictionary (device_contexts) that holds:
- Current Working Directory: Each device session can operate in its own directory.
- Last Active Timestamp: Helps in sorting and tracking session activity.
How It Works:
- On receiving the
/startcommand, an optional device ID can be provided. If a new device is specified, a new entry is created. - All commands (e.g.,
/cd,/ls,/pwd) reference thecurrent_devicevariable to determine which device context to operate on. - This design allows a single bot instance to manage multiple sessions simultaneously, which is especially useful in environments where remote control needs to be segmented.
Flowchart for Device Context Handling:
flowchart TD
A[Receive /start with device ID] --> B{Device ID exists?}
B -- Yes --> C[Update last active time]
B -- No --> D[Create new device context with current directory]
C --> E[Set current_device = device ID]
D --> E
E --> F[Subsequent commands use current_device to operate]