Dockerized Telegram radio bot and dynamic 1280x720 audio-visual RTMPS livestream engine with 3-tier AzuraCast/Icecast/ICY metadata auto-probe, PIL state-key HUD caching, and resilient polling.
  • Python 99.8%
  • Dockerfile 0.2%
Find a file
2026-12-02 16:42:44 -05:00
assets chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
handlers chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
scripts chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
sync_utils chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
tests chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
.gitignore chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
docker-compose.yml chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
Dockerfile chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
main.py chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
README.md chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
requirements.txt chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00
token.env.example chore: initial sanitized import of DeadMoon-Radio-Telegram-Synchronizer 2026-12-02 16:42:44 -05:00

🌕 DeadMoon-Radio-Telegram-Synchronizer 🌙

Unified Dockerized Telegram Radio Bot & Dynamic 1280×720 Audio-Visual RTMPS Livestream Engine with 3-Tier Metadata Auto-Probe, PIL State-Key HUD Caching & Resilient Polling

DeadMoon Suite Python 3.12 PTB v21+ FFmpeg RTMPS Docker Compose

Part of the DeadMoon Tool Suite by @Deadplayerdmr


🖥️ Terminal Preview

      *   d~~b  .        .================.        .   d~~b   *
   .    d  b      .==='  .------------.  '===.      d  b     .
      *          /   .-'    .      o    '-.   \              *
               /  .'   o       .      .   '.  \        .
    *         [===]  .    /        \    .  [===]   .       *
        (( .--[===]     \____/    \____/   [===]--. ))   d~b
        ((    [===]   o      .----.      O [===]    ))   d b
    .    '--- [===]    .    /      \   .   [===] ---'
       *       \  '.     .            o  .'  /       *
    .           '.  '-.    o   .   .  .-'  .'     .
         *        '===='--------------'===='          .

  ════════════════════════════════════════════════════════════════════════════
      🌕   D E A D M O O N   //   R A D I O   S Y N C H R O N I Z E R   🌙
      Dynamic Audio-Visual RTMPS Engine & Radio Bot  •  Part of the DeadMoon Tool Suite by @Deadplayerdmr
  ════════════════════════════════════════════════════════════════════════════

🌙 Overview

DeadMoon-Radio-Telegram-Synchronizer is a unified Dockerized Telegram radio companion bot and supervised FFmpeg audio-visual RTMPS livestream engine built for DeadMoon Radio — and compatible with any AzuraCast, Icecast, or ICY-enabled internet radio broadcast.

It pairs a clean, spam-proof public Telegram radio bot (/whatsplaying, /np, /recent, /station) with a 24/7 headless 1280×720 RTMPS broadcaster that composites live track metadata, listener telemetry, and an optional real-time frequency visualizer directly into Telegram Live Streams.


✨ Key Features

  • 🛰️ 3-Tier AzuraCast / Icecast / ICY Metadata Auto-Probe (sync_utils/stream_metadata.py):
    1. Tier 1 — AzuraCast API Auto-Probe: Automatically probes AZURACAST_API_URL, stream-origin /api/nowplaying, and local loopback endpoints (http://127.0.0.1/api/nowplaying/1, http://127.0.0.1:8090/api/nowplaying/1). Extracts live artist/title, track duration & elapsed timers, current/peak listener counts, 5-track song_history, and optional listener country flags (🌍) via AZURACAST_API_KEY. Automatically prefers LOCAL_ICECAST_URL loopback for zero-latency FFmpeg audio ingest when reachable.
    2. Tier 2 — Icecast Status JSON (/status-json.xsl): Parses active mount metadata, bitrate, and listener counts, enriching track durations via the public iTunes Search API and persisting local rolling history to data/recent_history.json.
    3. Tier 3 — Universal Icy-MetaData: 1 Stream Header Inspection: Reads icy-metaint metadata frames directly from any raw MP3/AAC broadcast stream and closes the probe socket immediately so it never lingers as a ghost listener.
  • 🎨 Three Live /visualmode Profiles (full / minimal / static):
    • full (Default): Looping animated DeadMoon canvas (bg_loop) + real-time audio spectrum visualizer (showfreqs with rate={fps}, win_size=1024, ascale=cbrt, fscale=log, colors=#F5D78E|#5CE1E6) + live 1280×720 RGBA HUD overlay (600k video at 15 fps).
    • minimal: Static DeadMoon background canvas + live 1280×720 RGBA HUD overlay (450k video at 10 fps, spectrum disabled for lower CPU).
    • static: Classic 16:9 static station logo only (350k video at 10 fps, lowest possible VPS footprint).
  • ⚡ PIL State-Key HUD Caching (compute_hud_state_key):
    • Computes a deterministic render-state signature across visual mode, online status, station name, bitrate, track artist/title, listener count/peak, top countries, progress timer/bar width, and recent 3 tracks.
    • Only re-renders and atomically replaces /dev/shm/dmr_hud.png (tmpfs) when visible HUD state actually changes — eliminating redundant Pillow draws and unnecessary disk/RAM churn on idle ticks.
  • 🛡️ VPS CPU & Log Hygiene (sync_utils/rtmp_streamer.py):
    • Caps FFmpeg libx264 encoding strictly with -threads 2 (-preset ultrafast -tune zerolatency, strict 2 * fps keyframe interval with -sc_threshold 0).
    • Resamples audio cleanly via aresample=resampler=swr:osr=48000:first_pts=0 into 48000 Hz stereo 320k AAC-LC (-profile:a aac_low).
    • FFmpeg -stats is disabled by default to keep VPS CPU wakeups minimal and prevent continuous progress-line bloat in container logs.
    • Enforces -re pacing exclusively on the visual input (never on the live HTTP audio stream) and supervises FFmpeg with exponential backoff (2s to 30s) plus automatic StreamKeyRedactingFilter scrubbing across all logs and Telegram reports.
  • 📡 Resilient Telegram Polling & Clean Group UX (main.py, handlers/public.py):
    • Configured with hardened HTTP/polling timeouts (connect_timeout=15.0, read_timeout=20.0, write_timeout=20.0, pool_timeout=15.0) and run_polling(..., timeout=15, bootstrap_retries=-1).
    • Transient NetworkError / TimedOut drops log as clean single-line warnings, and startup command/menu registration is non-fatal so brief Telegram API hiccups never crash the container on boot.
    • Public commands automatically delete trigger messages, preserve Telegram forum topic IDs (message_thread_id), enforce per-user cooldowns (COOLDOWN_SECONDS), and schedule non-blocking asyncio auto-deletion (AUTO_DELETE_DELAY).

⚙️ Configuring token.env

Every key is read live from token.env without restarting the container, and admin updates are written atomically with 0600 permissions (including Docker single-file bind-mount EBUSY handling).

Key Default Purpose
TELEGRAM_TOKEN (required) Bot token from @BotFather.
ADMIN_ID 0 Numeric Telegram ID of the bot admin (claimable via /claimadmin in private chat when 0).
AUTODETECT_PROBE 1 1 enables Tier 1 AzuraCast auto-probe; 0 uses manual STREAM_URL directly.
STREAM_URL http://127.0.0.1:8000/DeadMoonRadio.mp3 Primary audio stream URL for metadata fallback and FFmpeg ingest.
LOCAL_ICECAST_URL http://127.0.0.1:8000/DeadMoonRadio.mp3 Preferred local loopback Icecast mount probed for zero-latency FFmpeg ingest.
AZURACAST_API_URL http://127.0.0.1:8090/api/nowplaying/1 AzuraCast NowPlaying JSON API endpoint.
AZURACAST_API_KEY (blank) Optional AzuraCast API key to unlock live listener country flag breakdowns (🌍).
PUBLIC_RADIO_URL DeadMoonRadio.com Public station URL shown in Telegram replies and HUD captions.
STATION_NAME DeadMoon Radio Fallback station title when stream headers omit a station name.
COOLDOWN_SECONDS 25 Per-user cooldown between public commands (admin is exempt).
COOLDOWN_DELETE_DELAY 25 Seconds before cooldown warning notices auto-delete.
AUTO_DELETE_DELAY 180 Seconds before public bot replies auto-delete to keep group chats clean.
STREAMER_ENABLED 1 1 launches the supervised FFmpeg RTMPS engine automatically on boot.
VISUAL_MODE full Livestream visual profile: full, minimal, or static.
RTMP_SERVER_URL rtmps://dc1-1.rtmp.t.me/s/ Telegram RTMPS ingest server URL.
RTMP_STREAM_KEY (required for live) Telegram Live Stream key (redacted from all logs and status reports).
STREAM_AUDIO_BITRATE 320k Output AAC-LC audio bitrate.
STREAM_AUDIO_SAMPLERATE 48000 Output audio sample rate in Hz (48000 recommended for Telegram RTMPS).
STREAM_VIDEO_FPS 15 Target video framerate in full mode (minimal/static run at 10 fps).
STREAM_VIDEO_BITRATE 600k Target video bitrate in full mode (450k in minimal, 350k in static).

🔒 token.env is gitignored and holds live credentials. Never commit token.env — keep secrets out of token.env.example.


🎛️ Telegram Commands

👤 Public Commands

Command Effect
/whatsplaying (or /np) Displays the current artist & title, live elapsed/duration timer, listener count, station link, and auto-delete countdown.
/recent Lists the currently playing song plus the last 5 recently played tracks with relative timestamps.
/station Displays station online/offline state, audio bitrate, current/peak listeners, top countries (if configured), and current song.
/start / /help Shows the public command overview and station link (auto-deletes cleanly).

🛡️ Admin Commands (ADMIN_ID Only)

Command Effect
/claimadmin Claims admin ownership when ADMIN_ID=0, writes your numeric ID to token.env (0600), and registers the private admin / menu.
/status Full diagnostics report: radio online status, metadata tier, active stream URL, FFmpeg state/PID/restarts, and bot safeguards.
/autodetect [on|off|restart] Inspect, enable/disable, or flush and re-probe the AzuraCast/Icecast auto-detection cache.
/streamurl [url | confirm <url>] View or override the audio stream URL. Prompts with an inline confirmation guard when an AzuraCast stream is already auto-detected.
/visualmode [full|minimal|static] Switch livestream visual mode live and restart FFmpeg seamlessly.
/streamstart / /streamstop Start or stop the supervised FFmpeg RTMPS engine and persist STREAMER_ENABLED.
/streamrestart Force-regenerate logo/background/HUD assets and restart the FFmpeg livestream.
/streamstatus Shows FFmpeg runtime state, PID, uptime, visual mode, restart count, and redacted stderr tail.
/setstreamkey <key_or_rtmps_url> Deletes your message immediately, saves RTMP_SERVER_URL/RTMP_STREAM_KEY (0600), and restarts the stream if running.
/setapikey <key|clear> Deletes your message immediately and sets or clears AZURACAST_API_KEY (0600).
/setcooldown <seconds> Live-updates COOLDOWN_SECONDS.
/setautodelete <seconds> Live-updates AUTO_DELETE_DELAY.

🚀 Quick Deployment (Docker Compose)

The container runs with network_mode: host (allowing direct loopback probing of local Icecast/AzuraCast services on 127.0.0.1) and shm_size: "128m" (backing /dev/shm/dmr_hud.png atomic HUD renders in RAM).

git clone https://github.com/Deadplayerdmr/DeadMoon-Radio-Telegram-Synchronizer.git
cd DeadMoon-Radio-Telegram-Synchronizer
cp token.env.example token.env
chmod 600 token.env
nano token.env   # populate TELEGRAM_TOKEN and RTMP_STREAM_KEY
docker compose up -d --build

After startup:

  1. Open a private chat with your bot and send /claimadmin (if ADMIN_ID=0).
  2. Run /status to verify metadata auto-probe detection and FFmpeg livestream state.
  3. Monitor container logs with:
docker logs -f deadmoon-radio-synchronizer

Volume Mounts

Host Path Container Path Purpose
./token.env /app/token.env Live configuration updated atomically by admin commands
./data /app/data Persistent rolling track history (recent_history.json)
./assets /app/assets Generated station logo, static canvases, and bg_loop assets

🧪 Running Tests

python3 -m unittest discover -s tests -v

Covers config atomic writes, 3-tier metadata probing & ICY parsing, compute_hud_state_key PIL caching invariants, FFmpeg command validation (-threads 2, absence of -stats, -re placement, GOP alignment), stream-key redaction, and public/admin handlers.


🔧 Troubleshooting

Symptom Cause Solution
Livestream stays in BACKOFF RTMP_STREAM_KEY is blank or still set to placeholder Run /setstreamkey <your_key> in private chat (message is auto-deleted immediately).
FFmpeg fps/bitrate/speed telemetry shows 0.0 in /streamstatus Expected behavior — FFmpeg -stats is disabled by default for VPS CPU and log hygiene Check State: RUNNING, PID, Uptime, and Telegram Live Stream playback directly to confirm healthy broadcast.
High VPS CPU on smaller instances full mode renders animated background + real-time showfreqs spectrum Run /visualmode minimal (keeps live HUD, drops spectrum) or /visualmode static (lowest CPU).
Prompted for confirmation when running /streamurl AUTODETECT_PROBE=1 already detected a live AzuraCast station Tap ✅ Yes, Use External URL (or run /streamurl confirm <url>) to disable auto-probe and switch cleanly.
Admin commands reply Unauthorized ADMIN_ID is unset (0) or belongs to another account Send /claimadmin in private chat if ADMIN_ID=0, or verify your numeric ID in token.env.

🌌 The DeadMoon Tool Suite

Repository Role in the Ecosystem
🌕 DeadMoon-Download-Bot Whitelisted 8-platform Telegram audio acquisition bot with direct lossless engines, lock-free scheduler & 477 offline tests
📻 DeadMoon-Radio-Telegram-Synchronizer Dockerized Telegram radio bot & dynamic 1280×720 RTMPS audio-visual livestream engine with 3-tier metadata auto-probe
🤝 DeadMoon-Trade-Bot Dockerized Telegram music & dubplate escrow bot with native-SR SoX spectrograms, FTS5 catalog indexer & group trade board
📡 DeadMoon-Telegram-Scraper Single-file Windows polyglot Telegram channel/group exporter with 4-layer URL intelligence, granular media harvesting & QR login
🤖 DeadMoon-OpenHands-Launcher Zero-friction Windows launcher & installer for OpenHands with kinetic ASCII UI & automatic winnat port recovery
📚 DeadMoon-RaveBSD-Launcher Zero-friction Windows installer & launcher for RaveBSD 2.0 with kinetic ASCII UI, auto-Docker setup & Downloads mapping
🎓 DeadMoon-Scholarly-Harvester Single-file Windows polyglot scholarly PDF harvester with 7-API Recursive Omni-Resolver, 25-source Quality Judge & Command Deck WebUI
🌾 DeadMoon-Credential-Harvester Local Tampermonkey userscript (2.3v) for harvesting streaming ARLs, OAuth tokens, Netscape cookies & Widevine .wvd bundles
🔐 DeadMoon-Unified-Spotify-Provisioner Automated Windows polyglot provisioner for Spotify Premium sp_dc cookies & Android Widevine L3 device.wvd CDMs
🎶 DeadMoon-Playlist-Transfer-Tool Single-file Windows polyglot tool for migrating Deezer Favorites (Artists, Albums & Playlists) via CSV
🔍 DeadMoon-Universal-API-Verify-Script Self-contained Windows LLM statistical fingerprint verifier (lmfpd) with Smart Auto-Heal & catalog scanner

🌕 DeadMoon-Radio-Telegram-Synchronizer 🌙 — Crafted by @Deadplayerdmr