Spaces:
Sleeping
๐ด Telegram Auction Bot Documentation
Welcome to the Telegram Auction Bot documentation! This document provides a comprehensive guide to the bot's architecture, setup, commands, and inner workings.
๐๏ธ Architecture & Flow
The bot is built on Node.js using the CommonJS module system and the node-telegram-bot-api library. It uses a lightweight, local JSON file (db.json) as a persistent database, and manages active bidding sessions dynamically in-memory.
flowchart TD
A[Telegram Group Chat] -->|"/help" or "bid start"| B[Telegram Bot Listener]
B -->|Bidding Command| C{Session Manager}
C -->|No Session / Phase: inactive| D[Initialize Session]
C -->|Phase: bidding| E[Bidding Engine]
E -->|Timer ticks / Bid placed| F[Start/Reset Timer]
F -->|Timer reaches 0| G[Resolve Bid]
G -->|Update DB & Standings| H[(db.json Database)]
G -->|Next Actress / End Session| C
โ๏ธ Configuration & Data Store
1. Environment Variables (.env)
The bot reads its credentials from a .env file at the root of the project:
BOT_TOKEN: Your secret API token obtained from Telegram's@BotFather.ADMIN_IDS: A comma-separated list of Telegram User IDs (e.g.6260798528) who have access to administrative controls.
2. Local Database (db.json)
Persistent state is saved to db.json whenever records change. The schema contains:
users: Tracks user statistics, lifetime coins, wins, and won actresses.customCharacters: Holds actresses added by admins (includingfile_idreferences).deletedDefaultIds: Tracks hardcoded actress IDs that the admin has deleted (hidden).
๐ฌ Command Reference
For Everyone
These commands can be run by any player in the group chat.
| Command | Action / Input | Description |
|---|---|---|
bid start |
Plain text | Join or start an auction session. |
[amount] |
Plain number (e.g., 120) |
Place a bid during an active auction. |
/leaderboard |
Slash command | Shows the all-time top 10 players by total wins. |
/mystats |
Slash command | Shows your current stats, lifetime coins, and list of won actresses. |
/listactresses |
Slash command | Lists all active actresses in the pool. |
/how |
Slash command | Shows simple guide on how to play (rules & constraints). |
/help or /start |
Slash command | Shows the helper text (public commands only). |
For Admins Only
These commands require the sender's Telegram User ID to be listed in ADMIN_IDS in the .env file.
| Command | Syntax | Description |
|---|---|---|
| Admin Help | /helpadmin |
Lists all admin commands and details. |
| View Status | /adminstatus |
Prints process uptime, memory usage, active sessions, registered users, and system versions. |
| Inspect Session | /adminsession |
Shows the active phase, ready users, current actress, current highest bid, timer countdown, and participants. |
| Set Min Players | /setminplayers [num] |
Configures the minimum number of users required to start an auction lobby. |
| Add Actress | Send photo with caption starting with /newactress |
Adds a new actress using Telegram as a free photo host (uses line-separated caption). |
| View skins | /actressimages [id] |
Sends a media album containing all skins/images of an actress. |
| Add Image / Skin | Send photo with caption starting with /addimage |
Adds an alternative artwork/skin to an actress, optionally with a caption on line 2. |
| Update Actress | /updateactress [id] , [field] , [value] |
Updates actress fields (name, price, or features). |
| Delete Actress | /deleteactress [id] |
Deletes a custom actress or hides a default actress. |
| Bulk Delete | /deletemultiactress [id1], [id2]... |
Deletes multiple actress IDs in a single command. |
| Cancel Session | /cancelsession |
Forcefully terminates the active session immediately, clearing all timers. |
| Edit Image Caption | /editcaption [new caption] |
Edits the caption of an existing image (must reply to the target photo message). |
| Delete Image | /deleteimage |
Deletes a specific image from an actress's skin/image pool (must reply to the target photo message). |
๐ฎ Actress Management (CRUD)
1. Adding an Actress (No Image Required / Direct Photo Upload)
Method A (Direct Photo Upload): Send an image to the bot with a caption formatted by new lines:
/newactress Disha Patani 80 ๐ฅ Series: Bollywood โก Power: Dancer- Line 1:
/newactress [Actress Name] - Line 2:
[Base Price](a valid positive number) - Line 3+: Features (each feature on a new line)
- Line 1:
Method B (Text-Only, No Image): Send this text command to add an actress without any photo:
/submitactress Disha Patani , 80 , ๐ฅ Series: Bollywood , โก Power: Dancer
2. Storing Multiple Images / Skins with Captions (Single/Plural)
- Method A (Single Image / Caption): Send a photo with a caption starting with:
/addimage disha Alternative fit! - Method B (Album / Sequential Captions): Upload multiple photos as a Telegram album (media group). In the main album caption, write
/addimages [actress_id]followed by the captions for each photo on separate lines:/addimages disha Traditional wear Western wear Casual fit- Behavior: The bot automatically debounces album uploads, sorts the photos based on their send order, and maps each newline caption sequentially (Photo 1 gets caption line 1, Photo 2 gets caption line 2, etc.).
- When an actress has multiple images, the bot will pick a random image to present initially. During the bidding phase, the bot will cycle through all images and send them to the group chat every 5 seconds alongside the live bid status!
3. Modifying Actresses (Copy-on-Write)
You can update existing actress attributes by typing:
/updateactress [id] , [field] , [value]
Supported fields: name, price, features (comma-separated list).
Copy-on-Write (COW): If you update a hardcoded default actress (defined in
characters.js), the bot automatically duplicates it into thedb.jsondatabase with the edits, and flags the original default actress as hidden. This keeps default actresses editable without changing source code!
4. Editing Image Captions & Deleting Specific Images (Reply Commands)
Admins can manage individual images from an actress's skin/image pool directly inside the Telegram chat interface:
- Edit Caption: Reply to the specific photo message (sent by the bot via
/actressimages) with/editcaption [new caption text]. To clear/remove the caption, reply with just/editcaption. - Delete Image: Reply to the specific photo message with
/deleteimage. This permanently deletes that image skin from the actress's database record. - Note: Both commands fully support Copy-on-Write (COW) for default actresses, keeping your database safe and clean.
๐ Private Admin Control (Connect Chat)
Admins can link their private direct message (DM) chat with the bot to a specific Telegram group chat. This allows running active session commands (such as cancelling a session or checking live session stats) privately inside the bot DM, keeping the main group chat free of admin logs and status text.
Connection Steps:
- Request Connection String: In your Telegram group chat, type
/connect. - Retrieve Connection ID: The bot will send connection instructions containing the group chat's ID (e.g.
/connect -100xxxxxxxxxx). - Establish Connection: Copy this command, open a private chat with the bot, and send the copied command
/connect -100xxxxxxxxxx. - Usage:
- Run
/adminsessionin the private DM to fetch live active bidding statistics of the connected group. - Run
/cancelsessionin the private DM to immediately cancel the connected group's session. The bot will notify players in the group and confirm the cancellation to your private DM.
- Run
โ๏ธ Core Engines & Technical Optimizations
1. Concurrency Lock (session.resolving)
To prevent duplicate messages and database integrity issues, the bot uses a lock flag during actress transitions:
- When a bid timer hits
0,resolveBid()runs and setssession.resolving = truesynchronously. - Any bids sent while the bot is writing to the database or waiting for
sendMessageto resolve are safely rejected. - The lock is released (
session.resolving = false) only when the next actress is successfully loaded and sent.
2. Combined Bid Confirmation and Countdown
Rather than sending a separate bid confirmation message and a countdown timer message consecutively (which clutters the chat), the bot merges them into a single active countdown message.
- When a player places a valid bid, the previous countdown message is immediately deleted.
- A new combined message is posted at the bottom of the chat, stating the current highest bid details alongside the active progress bar and remaining seconds.
- To avoid Telegram rate limits (429) on message editing, the active countdown edits itself only every multiple of 5 seconds and once per second in the final 3 seconds.
3. Resilient Error Handling
All asynchronous Telegram API calls are wrapped in robust try-catch blocks. Additionally, global listeners for polling_error, unhandledRejection, and uncaughtException are set up. If a temporary connection drop occurs (such as an ECONNRESET socket reset), the bot logs the error and recovers automatically instead of crashing Node.js.
4. Automatic Message Cleanup (De-Clutter)
To keep group chats clean, the bot logs all auction-related message IDs (such as bid starts, countdown timer messages, bid confirmations, and player bid messages) in-memory during active sessions. When an auction session completes, the bot iterates over these IDs and executes deleteMessage API calls to delete them in bulk, leaving only the final scoreboard.
Additionally, if a user places an invalid bid (e.g. less than the base price or highest bid, or if they are not a participant), both the player's invalid bid message and the bot's warning message are automatically deleted after 3 seconds to keep the active bidding screen clear of clutter.
The bot requires Delete Messages permissions as a group administrator to delete other players' bidding messages. If it lacks this permission, it will only delete its own messages.
5. Transition Delay
Between actresses, the bot introduces a mandatory 20-second cooldown period configured via NEXT_CHARACTER_DELAY_MS. When an actress is resolved, the bot sends a notification โณ Next Bid in 20s โ Get ready for [Actress Name]! to alert players and allow them to prepare before starting the next bidding timer.
6. In-Group Restricted Actress Selection Lobby
When players join the session by typing bid start in the group chat, the bot sends an interactive inline keyboard menu listing all active actresses directly in the same group chat.
- Player Specific Interaction: Each player's menu is restricted to them. If another user attempts to click a button on player A's keyboard, the bot displays a pop-up alert:
โ ๏ธ This selection menu is only for the player who requested it!. - Duplicate Prevention: If a player attempts to select an actress already selected by another player in the lobby, the bot displays a pop-up warning:
โ ๏ธ This actress is already selected by @username! Please select another., blocking duplicate selections. - Toggles & Finalization: Players toggle their preferred actresses and click
Done Selectingto lock choices. - Empty Selection Prevention: If a player attempts to click
Done Selectingwithout having selected at least one actress, the bot blocks the finalization and displays an alert pop-up:โ ๏ธ You must select at least one actress before clicking Done!. - Deferred Start: The auction bidding session will not begin until the player count reaches
REQUIRED_PLAYERSAND all joined players have finalized their choices by clickingDone Selecting. - Auction Pool Construction: The bot merges selections from all lobby participants to construct the custom bidding pool. Bidding runs exclusively on the actresses chosen by the players (no padding with random actresses, no truncation).
7. Resolution Outcome Photo Captions
Rather than sending intermediate actress photos every 5 seconds, the bot now stays quiet during active countdown ticks. When a bidding round is resolved, the bot sends the actress's photo with the outcome (SOLD details or UNSOLD notice) embedded directly as the caption.
- Image/Skin Variation: If an actress has multiple skins/photos in the database, the bot automatically selects a different skin for the outcome message than the one displayed at the start of the auction. If only one image is available, it safely falls back to the same image. This ensures a fresh visual presentation upon round completion.
8. Bulk Actress Import System (CSV)
To add hundreds of actresses in bulk without adding them one-by-one:
- Export your actress data as a CSV file or fill out the automatically generated
characters.csvfile in the project root directory. - Structure the columns as:
Name,Base Price,Features,Image URLs.- Features: Semicolon-separated list of details (e.g.
Series: Bollywood; Rarity: SSR). - Image URLs / File IDs: Semicolon-separated list of image references. Add a caption directly after any reference using a pipe symbol (e.g.
AgACAg...|Disha Patani fit 1; AgACAg...|Disha Patani fit 2).
- Features: Semicolon-separated list of details (e.g.
- Run the script from the command line:
node import_characters.js - The script will parse the entries, run validation checks (reporting line errors if any format is incorrect), and append the actresses to the active database.