A sophisticated, high-performance music streaming engine for Telegram.
Engineering Stack • Dockerization • Deployment • Configuration
Melody is an optimized fork of the ShrutiMusic architecture, re-engineered for ultra-low latency and maximum uptime. This project was heavily vibe coded with a relentless focus on aesthetics, fluid interactions, and visual excellence.
- Distributed Engine: Leveraging a high-speed bypass API for resilient media delivery across all regions.
- Asynchronous Core: Built on the
Pyrogramframework andMotor(MongoDB) for high-concurrency handling. - Adaptive Quality: Intelligent transcoding system that balances audio fidelity with network stability.
| Capability | Technical Detail |
|---|---|
| Audiophile Grade | High-fidelity audio streaming optimized for Telegram's Opus codec. |
| Universal Support | Seamless playback from YouTube, Spotify, SoundCloud, and Direct Links. |
| Instant Playback | API-accelerated pre-fetching ensures tracks start in 1-3 seconds. |
| Smart Moderation | Visual command suite for volume control, dynamic queuing, and auto-skip. |
| Global Localization | Multi-language support with 15+ fully localized interface translations. |
Melody is built on a modern, asynchronous stack designed for high-concurrency and low-latency performance.
| Library | Role in Melody |
|---|---|
| Kurigram | An advanced fork of Pyrogram used as the primary Telegram MTProto framework for high-speed bot interaction. |
| Py-TgCalls | The industry standard for handling Telegram Group Call streaming (transcoding and pushing audio/video). |
| FastAPI | Powers the internal web service used for health monitoring and keeping the bot alive on cloud platforms. |
| Library | Role in Melody |
|---|---|
| Motor | Asynchronous driver for MongoDB, ensuring database operations never block the streaming loop. |
| Redis | High-speed cache for keeping track of live player states and group-specific settings. |
| yt-dlp | The primary engine for extracting and downloading media from 1000+ supported sites. |
| Spotipy | Native integration for resolving Spotify tracks and playlists into streamable content. |
Melody includes a built-in FastAPI server that runs in the background of the main bot process. This serves two critical technical purposes:
- Health Monitoring: Provides a
/and/pingendpoint that cloud providers can query to verify the bot is operational. - Persistence (Anti-Idling): On platforms like Render or Koyeb, the bot must listen on an HTTP port to prevent the "Free Tier" from putting it to sleep.
The web server is fully asynchronous and shares the main bot application's asyncio event loop, ensuring zero performance overhead.
Melody utilizes a high-performance Multi-Stage Docker Architecture to ensure the production image is lightweight, secure, and reproducible.
- Stage 1 (Builder): Compiles Python dependencies and builds an isolated virtual environment using
python:3.13-slim. - Stage 2 (Runtime): Copies only the necessary artifacts (venv) from the builder into a clean environment, reducing image size by ~60%.
- Non-Root Execution: The bot runs under a dedicated
botuserto prevent container escape and unauthorized system access. - Health Checks: Built-in
HEALTHCHECKinstructions monitor the FastAPI status endpoint. If the web service fails, the container is automatically marked asunhealthyfor orchestration recovery. - Optimized Layering: Strategic use of
.dockerignoreand single-layerRUNcommands ensures rapid build times and efficient caching.
| Command | Description |
|---|---|
/play <query> |
Discover and stream audio from YouTube, Spotify, and more. |
/vplay <query> |
Stream video directly into the Group Voice Chat. |
/cplay <query> |
Stream audio in a linked Channel Voice Chat. |
/playmode |
Configure the default playback mode for your group. |
/playlist |
View and manage your personal/group streaming queues. |
| Command | Description |
|---|---|
/pause / /resume |
Toggle the playback state of the current track. |
/skip |
Transition to the next item in the playback queue. |
/stop / /end |
Halt the stream and clear the active session. |
/seek <duration> |
Jump to a specific timestamp in the current track. |
/loop <1-10> |
Enable looping for the current track or the entire queue. |
/shuffle |
Randomize the order of the current playback queue. |
/speed |
Adjust the playback speed (0.5x to 2.0x). |
/auth / /unauth |
Grant or revoke administrative command permissions. |
| Command | Description |
|---|---|
/settings |
Access and modify bot configurations for your group. |
/language |
Change the bot's interface language. |
/ping |
Check the bot's response latency and uptime. |
/stats |
View global and group-specific streaming statistics. |
/reload |
Refresh the bot's cache and authorized user list. |
To use Melody, you must obtain a STRING_SESSION for your assistant account. This acts as the login key for the Userbot that joins Voice Chats.
Tip
This web-based generator is the most secure and reliable method to obtain your session string. Ensure you select Pyrogram and User type.
Melody supports various hosting environments. Choose the platform that best fits your technical expertise.
| Platform | Recommendation | Status |
|---|---|---|
| ◈ VPS Deployment | Highly Recommended | 24/7 Stability |
| ◈ Cloud Deployment | Beginner Friendly | Verified |
Melody has been confirmed operational on the following environments:
- ◈ Verified: Heroku, Render, and Koyeb.
- ◈ Expected Support: Ubuntu/Debian VPS (Native & Docker).
This method offers the best performance and reliability. Recommended for long-term project hosting.
Run these commands to prepare your Linux server (Ubuntu/Debian recommended).
# Update system packages to the latest version
sudo apt-get update && sudo apt-get upgrade -y
# Install core dependencies: Python, Pip, Git, FFmpeg (for audio), and Screen (for persistence)
sudo apt-get install python3 python3-pip python3-venv ffmpeg git screen curl -y
# Install Node.js (Required for internal components)
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejsClone your code and set up an isolated environment to avoid package conflicts.
# Clone the repository
git clone https://github.com/bisug/Melody && cd Melody
# Create and activate a Virtual Environment
python3 -m venv venv
source venv/bin/activate
# Install all required Python libraries
pip3 install -U pip
pip3 install -U -r requirements.txt# Create your environment file
cp sample.env .env
nano .envTip
Use the arrow keys to navigate and Ctrl+O, Enter, Ctrl+X to save and exit. Ensure all required variables are filled.
You have two options to keep your bot active after you close your terminal:
Option A: Using Screen (Easiest for Beginners)
# Start a new persistent window
screen -S melody
# Start the bot
python3 -m Melody
# To exit: Press 'Ctrl+A' followed by 'D'. This leaves the bot running.
# To return: Type 'screen -r melody'.Option B: Using Systemd (Professional & Permanent) Create a service file to ensure the bot restarts automatically if the server reboots.
sudo nano /etc/systemd/system/melody.servicePaste the following (replace {username} with your VPS username and {path} with your project path):
[Unit]
Description=Melody Music Bot
After=network.target
[Service]
Type=simple
User={username}
WorkingDirectory={path}/Melody
ExecStart={path}/Melody/venv/bin/python3 -m Melody
Restart=always
[Install]
WantedBy=multi-user.targetRun: sudo systemctl enable melody --now
Running with Docker is the most reliable way to ensure a consistent environment across different VPS providers.
Run these commands to install Docker and Docker-Compose on your VPS.
# Install Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# Start Docker and enable at boot
sudo systemctl start docker
sudo systemctl enable dockerEnsure you have your .env file ready in the project root as described in Phase 3 of the native VPS guide.
Use the provided Dockerfile to build and run the bot in an isolated container.
# Build the image
docker build -t melody .
# Run the container (detached mode)
docker run -d --restart always --name melody-bot --env-file .env melody# View logs
docker logs -f melody-bot
# Stop the bot
docker stop melody-bot
# Restart the bot
docker restart melody-botCloud platforms automate the infrastructure setup using Docker, ensuring identical environments regardless of hosting.
Heroku uses the provided Dockerfile or Procfile to build and run your bot in an isolated "dyno".
- 🚀 One-Click Setup: Clicking the button below will take you to a "New App" page on Heroku.
- 🔑 Variables: You will be prompted to fill in your environment variables.
- 🏢 Heroku Teams: If you are deploying to a Heroku Team, you MUST have Admin permissions within that team to create new apps.
- ✅ Enable Worker: Once deployed, go to the Resources tab and ensure the
workerdyno is enabled.
Render is a modern cloud platform that directly supports Docker images from your repository.
- 🐳 Docker Powered: Render reads the
Dockerfilein this repo to build a dedicated container for your bot. - 🔄 Auto-Build: Every time you push a change to your repository, Render will automatically rebuild and redeploy your bot.
- ⚡ Ease of Use: It handles environment isolation and port management automatically.
- ◈ New Web Service: Click New + > Web Service.
- ◈ Connect Repo: Link your fork of
bisug/Melody. - ◈ Runtime: Select Docker.
- ◈ Environment: Add all required variables from your
.env.- Crucial: Set
WEB_SERVICEtoTrueandPORTto8000.
- Crucial: Set
- ◈ Deploy: Render will automatically build the image from the
Dockerfile.
Koyeb provides a high-performance serverless platform with a generous free tier.
- ◈ Create App: Click Create Service.
- ◈ Source: Select GitHub and connect your repository.
- ◈ Service Type: Choose Web Service.
- ◈ Builder: Select Dockerfile.
- ◈ Environment Variables:
- Add all keys from your
.env. - Ensure
WEB_SERVICE=TrueandPORT=8000.
- Add all keys from your
- ◈ Region: Choose the region closest to your MongoDB/Redis for lowest latency.
- ◈ Finish: Your bot will be live in minutes.
Important
Persistence Tip: If using Free Tiers, your bot will go to sleep unless you follow the Keep-Alive Guide.
Warning
SECURITY ADVISORY: After forking this repository, NEVER commit your sensitive credentials (API IDs, Tokens, Session Strings) into a public .env or config.py.
- Recommended: Use Environment Variables on your hosting platform (Heroku, Render, etc.).
- Alternative: If you absolutely must commit your settings, ensure your repository is set to Private first.
| Variable | Required | Description |
|---|---|---|
API_ID |
Yes | Your API ID from my.telegram.org. |
API_HASH |
Yes | Your API Hash from my.telegram.org. |
BOT_TOKEN |
Yes | Token from @BotFather. |
MONGO_DB_URI |
Yes | MongoDB Atlas connection string. |
MONGO_DB_NAME |
No | Name of your MongoDB database (Default: Melody). |
REDIS_URI |
No | Optional Redis string for 2x faster cache. See Guide |
STRING_SESSION |
Yes | Primary Pyrogram V2 session string. Generator |
STRING_SESSION2-5 |
No | Additional session strings for multi-assistant support. |
To ensure your bot runs correctly, you must provide these essential credentials. Follow these steps carefully.
- How to Get:
- Go to my.telegram.org.
- Enter your phone number in international format (e.g.,
+91...) and confirm the code sent to your Telegram. - Click on API Development Tools.
- App title: Any name (e.g.,
MelodyPlayer). - Short name: Any short word (e.g.,
Melody). - Click Create application.
- Copy the App api_id and App api_hash.
- Why it's Required: These are the master keys that allow Melody to "piggyback" on the Telegram desktop/mobile app infrastructure. Without them, the bot cannot connect to the servers to stream music.
- How to Get:
- Open Telegram and search for @BotFather.
- Send
/newbot. - Enter a Display Name for your bot.
- Enter a Username (must end in
bot, e.g.,Melody_123_bot). - BotFather will send a message containing your HTTP API Token.
- Why it's Required: This token acts as the specific password for your bot account. It allows the software to take control of that specific @username on Telegram.
- How to Get:
- Sign up at MongoDB Atlas.
- Create a Cluster: Choose the FREE (Shared) M0 cluster. Select a region near you.
- Database Access: Create a user. Make sure to remember the Username and Password.
- Network Access: Click Add IP Address and select Allow Access from Anywhere (0.0.0.0/0). Critical for cloud hosting.
- Connect: Go to Deployment > Database and click Connect.
- Choose Drivers (Python).
- Copy the connection string (e.g.,
mongodb+srv://user:pass@cluster.mongodb.net/?...). - Important: Replace
<password>in the string with your actual database user password.
- Why it's Required: This is where Melody stores its "memory"—including who is authorized, your preferred language, and group settings. Without it, the bot will reset every time it restarts.
- How to Get:
- Create a free account on Upstash.
- Create a new Redis database.
- Select Global or a region nearest to your bot's hosting.
- In the Connect to your database section, copy the Redis Connect String (starts with
rediss://).
- Why it's Required: Redis is used for ultra-fast temporary data storage (caching). It handles the live player state and prevents unnecessary heavy hits to your MongoDB, ensuring your bot stays snappy and responsive.
- How to Get: Use our official Session String Generator.
- Why it's Required: Standard bots cannot join Voice Chats. To play music, Melody uses a "User Assistant" (your secondary account) to join the VC and play the audio. This session string acts as the login key for that assistant.
| Variable | Required | Description |
|---|---|---|
OWNER_ID |
Yes | Telegram user ID for the bot owner. |
DEV_ID |
No | Additional developer IDs for maintenance. |
LOG_GROUP_ID |
Yes | ID of the group/channel for logs (starts with -100). See Guide |
IDs are unique numbers used by Telegram to identify users and groups. Melody uses these to know who you are and where to send logs.
- Open Telegram and search for @MissRose_bot or @GetIDsBot.
- Send
/idto the bot. - Copy the numeric ID (e.g.,
123456789).
- Add @MissRose_bot to your group or channel.
- Send
/idin the group or forward a message from the channel to the bot. - Critical: Ensure the ID starts with
-100(e.g.,-1001234567890). If it doesn't, it is not a "Supergroup" or a "Channel," which is required for logging.
| Variable | Required | Description |
|---|---|---|
YT_API_URL |
No | shrutibots.site (Provided by NoxxOP). |
COOKIES_URL |
No | URL to fetch YouTube cookies for bypass. See Guide |
START_IMG_URL |
No | Direct link to the image shown on /start. See Guide |
To bypass YouTube's bot detection, you need to provide your account cookies in Netscape format.
- 📥 Install the EditThisCookie or Get cookies.txt extension.
- 🕵️ Recommended: Open YouTube in Incognito Mode.
- 🌐 Log in to your account.
- 📤 Click the extension and Export cookies as Netscape format.
- 📋 Go to BatBin and paste your cookies.
- 🔗 Save and copy the Raw URL (e.g.,
https://batbin.me/raw/...). ⚠️ Critical: Immediately close the browser/Incognito window after exporting.
- 📥 Install Mozilla Firefox and the cookies.txt extension.
- 🕵️ Open YouTube in a Private Tab.
- 🌐 Log in to your account.
- 📤 Use the extension to download/copy cookies in Netscape format.
- 📋 Paste to BatBin and get the Raw URL.
⚠️ Critical: Immediately close the private tab after exporting.
Use high-quality direct links for your bot's start image (JPEG or PNG recommended).
- 📤 Upload your image to a hosting platform like ImgBB, Catbox, or Telegraph.
- 🔗 Copy the Direct Link (the URL should end with
.jpg,.jpeg, or.png). - 🔑 Provide this URL as your
START_IMG_URL.
| Variable | Required | Description |
|---|---|---|
SUPPORT_CHANNEL |
No | bisug Melody |
SUPPORT_GROUP |
No | bisug Music |
Fine-tune your bot's behavior and link your community resources.
SUPPORT_CHANNEL/SUPPORT_GROUP: Enter the public username of your Telegram channel/group (e.g.,MelodySupport). This will be displayed in the/startmessage and help menu.
DURATION_LIMIT: Sets the maximum allowed length (in minutes) for a single song. Recommended:300(5 hours). Use0for no limit.PLAYLIST_FETCH_LIMIT: Limits how many songs the bot will load when a user plays a large playlist. This prevents the bot from lagging while processing 1000s of items. Recommended:25or50.
AUTO_LEAVING_ASSISTANT: If set toTrue, the Assistant account (Userbot) will automatically leave the Voice Chat if no one else is listening. This saves resources and keeps the VC clean.
WEB_SERVICE: MUST be set toTrueif you are hosting on "Web Service" platforms like Render or Koyeb.PORT: Default is8000. This is the internal port the bot "listens" on to stay active.
Warning
Free Tier Idling: Web services like Render (Free Tier) will automatically "sleep" after inactivity. This will stop your bot.
To keep your bot running 24/7 on free hosting, use a cronjob service (like Cron-job.org) to ping your service URL every 1 minutes.
𝐒𝐭𝐞𝐩𝐬:
- 🌐 Create a free account on Cron-job.org
- ➕ Click Create Cronjob
- 🔗 Title:
Melody Keep-Alive - 🌍 URL:
https://your-app-name.onrender.com(Replace with your actual app URL) - ⏱️ Schedule: Every 1 minutes
- ✅ Save: Now your bot will never sleep!
| Contributor | Role & Impact | Resource |
|---|---|---|
| NoxxOP | Original Architect • Designed the core framework and the underlying media streaming engine that powers this project. | |
| All Contributors | Project Evolution • Significant contributions from the global open-source community. |
| Contributor | Role & Impact | Profile |
|---|---|---|
| Bisug (Bisu G) | Lead Maintainer • Focused on stability, performance optimization, and implementing modern UI/UX enhancements. |
This project’s documentation and code refinements were synthesized with the support of state-of-the-art AI models:
- Claude 4.5 Sonnet – Orchestrated complex technical documentation and logical restructuring.
- Gemini 3 Flash – Provided architectural analysis and rapid debugging insights.
- Google Jules – Optimized visual layout and premium technical formatting.