VibeCode|自建高音质 Telegram 专属点歌台:yt-dlp + TG Bot 部署指南

2026年5月22日

在这个流媒体版权四分五裂的时代,利用闲置的云服务器搭建一个属于自己的“云端点歌台”,是一件极具赛博朋克浪漫的事情。

本文将手把手带你部署一个通过 Telegram 远程控制的 YouTube Music 下载机器人。它支持原声直出、高频防封以及多用户权限管理。


💡 这是什么?

这是一个基于 Python 和 yt-dlp 构建的 Telegram 交互式机器人。你可以把它理解为一个没有广告、音质拉满、且完全受你控制的云端音乐中枢。

💡 核心亮点(更新版)

  • ⚡️ 极速原声直出:打破“本地转码 MP3”的低效思维,直接剥离 YouTube 源头的 M4A (AAC) 高音质音频流。零转码等待,瞬间发送至 Telegram,且原生支持 TG 音乐播放器(带封面、可后台连播)。

  • 🔒 权限隔离与持久化:不仅能发给 TG,还支持将高品质音源持久化下载到服务器本地,配合 Navidrome / Plex 打造你的专属流媒体库,并配备严格的管理员鉴权机制。

  • 🛡 智能多链路防护(Anti-Wind/Anti-Blocking):摒弃了易失效的 Cookies 伪装方案。通过“计算与网络分离”架构,将 Bot 运行逻辑与流量出口解耦。支持接入优质 ISP/家宽代理,在 YouTube 风控严密的环境下,依然能实现秒级响应与高并发下载。


📸 界面预览

1779446283863.png 1779449481435.png 1779449536090.jpg


🕹 怎么用?

部署成功后,向机器人发送指令即可开启数字点歌体验:

  • /start:调出主菜单与功能指引。
  • /music [歌名]:一键点歌。机器人将在后台静默秒级匹配最相关的单曲,下载并直接砸向你的聊天框,不产生多余交互。
  • /search [歌名]:精确检索。返回 Top 5 的相关结果供你手动挑选(适合寻找特定翻唱版本或 Live 现场)。
  • /download [歌名]:入库指令(需授权)。将音频永久保存到服务器指定物理目录,不上报 TG。
  • /admin:管理面板。查看运行时间、下载统计,并动态添加/移除群组或用户的 /download 权限。

⚙️ 依赖环境与 AMD / ARM 架构避坑指南

本项目的核心依赖为:ffmpeg、python3 以及 Python 库 yt-dlp 和 python-telegram-bot[job-queue]。

在不同 CPU 架构的服务器上部署时,获取 yt-dlp 的方式有着致命差异,这是无数新手翻车的地方:

  • 🖥 传统 AMD/x86_64 架构: 你可以直接从 GitHub Releases 下载官方预编译的 yt-dlp_linux 二进制文件运行,简单粗暴。
  • 📱 现代 ARM 架构(如 Oracle ARM、各类云手机、树莓派): 绝对不能下载官方默认的二进制文件!否则在执行时会直接爆出红色的 cannot execute binary file: Exec format error(架构不匹配)。 解法:在 ARM 机器上,必须使用系统的包管理器安装底层依赖,然后通过 Python 的 pip 来全局安装 yt-dlp。Python 虚拟机会自动为你抹平底层的架构差异。

通用底层安装指令(Debian/Ubuntu):

apt update && apt install ffmpeg python3-pip -y
pip3 install yt-dlp "python-telegram-bot[job-queue]" --break-system-packages

💻 核心代码

请在服务器上创建 bot.py 文件,并将以下完整代码粘贴进去。(注意替换代码头部的 BOT_TOKEN 与 ADMIN_USER_ID)

import os
import time
import asyncio
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
import yt_dlp

# --- 配置区 ---
BOT_TOKEN = '你的Bot Token'
ADMIN_USER_ID = 你的User ID  # 主管理员 ID

# 允许访问的用户或群组 ID 列表(初始化包含主管理员)
ALLOWED_USERS = [ADMIN_USER_ID]

CACHE_DIR = './cache'
PERSISTENT_DIR = '/storage/music'  # 持久化存储目录

# 简易运行统计数据
STATS = {
    "start_time": time.time(),
    "tg_sends": 0,
    "server_saves": 0
}

# 确保目录存在
os.makedirs(CACHE_DIR, exist_ok=True)
os.makedirs(PERSISTENT_DIR, exist_ok=True)

# --- 权限校验装饰器 ---
def check_permission(func):
    async def wrapper(update: Update, context: ContextTypes.DEFAULT_TYPE, *args, **kwargs):
        user_id = update.effective_user.id
        chat_id = update.effective_chat.id
        if user_id in ALLOWED_USERS or chat_id in ALLOWED_USERS:
            return await func(update, context, *args, **kwargs)
        else:
            await update.message.reply_text("🔒 抱歉,您没有权限使用此命令。如需授权,请联系管理员。")
    return wrapper

# --- YT-DLP 搜索与下载逻辑 ---
def search_yt_music(query, limit=5):
    """搜索 YouTube 音乐并返回结果列表"""
    ydl_opts = {
        'extract_flat': True,
        'quiet': True,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        search_query = f"ytsearch{limit}:{query} music"
        res = ydl.extract_info(search_query, download=False)
        return res.get('entries', [])

def download_audio(video_id, output_dir):
    """直接下载 YouTube 的 M4A 原声,不进行重编码转码"""
    ydl_opts = {
        # 优先要求 m4a 格式(AAC编码),这样能保证发给 TG 时被识别为音乐
        'format': 'm4a/bestaudio/best',

        # 移除 FFmpegExtractAudio,不再进行 MP3 重编码!
        # 仅保留元数据写入等轻量级操作
        'outtmpl': f'{output_dir}/%(title)s_{video_id}.%(ext)s',
        'quiet': True,
        'no_warnings': True
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(video_id, download=True)
        # 获取实际下载的文件名(此时后缀通常是 .m4a)
        filepath = ydl.prepare_filename(info)
        return filepath

# --- 定时任务:清理 24 小时前的缓存 ---
async def cleanup_cache(context: ContextTypes.DEFAULT_TYPE):
    now = time.time()
    for filename in os.listdir(CACHE_DIR):
        filepath = os.path.join(CACHE_DIR, filename)
        if os.path.isfile(filepath):
            if now - os.path.getmtime(filepath) > 24 * 3600:
                try:
                    os.remove(filepath)
                    print(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] 清理过期缓存: {filename}")
                except Exception as e:
                    print(f"清理缓存失败: {e}")

# --- 核心命令回调 ---

async def start_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ /start 菜单与引导 """
    menu_text = (
        "🎵 *欢迎使用 YT 点歌宝* 🎵\n\n"
        "可以使用以下命令进行操作:\n"
        "\n▶️ `/music 歌曲名` \\- *⚡️一键点歌*\n"
        "\n🔍 `/search 歌曲名` \\- 搜索歌曲\n"
        "\n⚙️ *管理指令*:`/admin` \\(查看统计与授权群组\\)"
    )
    await update.message.reply_text(menu_text, parse_mode='MarkdownV2')

async def admin_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ /admin 管理面板 """
    if update.effective_user.id != ADMIN_USER_ID:
        await update.message.reply_text("❌ 您不是主管理员,无权查看管理面板。")
        return

    args = context.args
    if args and len(args) >= 2:
        action = args[0].lower()
        try:
            target_id = int(args[1])
            if action == 'add':
                if target_id not in ALLOWED_USERS:
                    ALLOWED_USERS.append(target_id)
                    await update.message.reply_text(f"✅ 已成功授权 ID: `{target_id}`", parse_mode='MarkdownV2')
                else:
                    await update.message.reply_text("💡 该 ID 已经在授权列表中。")
                return
            elif action == 'del':
                if target_id == ADMIN_USER_ID:
                    await update.message.reply_text("❌ 无法删除主管理员账号。")
                elif target_id in ALLOWED_USERS:
                    ALLOWED_USERS.remove(target_id)
                    await update.message.reply_text(f"🗑 已解除授权 ID: `{target_id}`", parse_mode='MarkdownV2')
                else:
                    await update.message.reply_text("💡 授权列表中未找到该 ID。")
                return
        except ValueError:
            await update.message.reply_text("⚠️ 请输入正确的整数型 用户/群组 ID。")
            return

    uptime = time.time() - STATS["start_time"]
    days, rem = divmod(uptime, 86400)
    hours, rem = divmod(rem, 3600)
    mins, _ = divmod(rem, 60)

    admin_text = (
        "🛠 *管理员后台面板*\n\n"
        f"⏱ *运行时间*:{int(days)}天 {int(hours)}小时 {int(mins)}分钟\n"
        f"📊 *累计发送到TG*:{STATS['tg_sends']} 次\n"
        f"💾 *累计存入服务器*:{STATS['server_saves']} 次\n\n"
        f"👥 *当前授权列表* \\({len(ALLOWED_USERS)}人/群组\\):\n"
        f"`{list(ALLOWED_USERS)}`\n\n"
        "👉 *授权操作指令*:\n"
        "• 添加授权: `/admin add ID`\n"
        "• 取消授权: `/admin del ID`"
    )
    await update.message.reply_text(admin_text, parse_mode='MarkdownV2')

async def music_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ /music ⚡️直达点歌:直接抓取最相关的第一个结果下载并发送 """
    query = " ".join(context.args)
    if not query:
        await update.message.reply_text("⚠️ 请提供歌曲名称!例如:`/music 稻香`")
        return

    msg = await update.message.reply_text(f"正在获取歌曲信息: {query} ...")

    # 限制搜索数只需1个,提升检索效率
    results = await asyncio.to_thread(search_yt_music, query, limit=1)

    if not results:
        await msg.edit_text("❌ 未找到相关音乐或程序异常。")
        return

    best_match = results[0]
    vid = best_match['id']

    await msg.edit_text("⏳ 已经锁定最匹配音源,正在调度 yt-dlp 下载...")

    try:
        # 直接丢线程去下载,不需要弹按钮
        filepath = await asyncio.to_thread(download_audio, vid, CACHE_DIR)

        file_size_mb = os.path.getsize(filepath) / (1024 * 1024)
        filename_clean = os.path.basename(filepath)

        await msg.edit_text(f"✅ 下载完成 ({file_size_mb:.2f} MB),正在发送...")

        with open(filepath, 'rb') as audio_file:
            await context.bot.send_audio(
                chat_id=update.effective_chat.id,
                audio=audio_file,
                title=filename_clean.replace('.mp3', ''),
                caption=f"📊 文件大小: {file_size_mb:.2f} MB\n⏱ 下载留存时间: 24小时"
            )
        STATS["tg_sends"] += 1
        await msg.delete()

    except Exception as e:
        await msg.edit_text(f"❌ 发生错误:{str(e)}")

async def process_search_and_respond(update: Update, context: ContextTypes.DEFAULT_TYPE, force_save: bool):
    """ 列表搜索与按钮生成逻辑(用于 /search 和 /download) """
    query = " ".join(context.args)
    if not query:
        cmd_type = "/download" if force_save else "/search"
        await update.message.reply_text(f"⚠️ 请提供歌曲名称!例如:`{cmd_type} 稻香`", parse_mode='MarkdownV2')
        return

    msg = await update.message.reply_text(f"🔍 正在搜索列表: {query} ...")
    results = await asyncio.to_thread(search_yt_music, query)

    if not results:
        await msg.edit_text("❌ 未找到相关音乐。")
        return

    keyboard = []
    for item in results:
        vid = item['id']
        title = item.get('title', 'Unknown Title').replace('|', '-')
        channel = item.get('channel', 'Unknown Artist')
        duration = int(item.get('duration') or 0)

        m_s = f"{duration//60}:{duration%60:02d}"
        display_text = f"🎵 {title} - {channel} ({m_s})"

        keyboard.append([InlineKeyboardButton(display_text, callback_data='noop')])

        if force_save:
            # 管理员专享:仅显示存入服务器
            keyboard.append([InlineKeyboardButton("💾 确认存入服务器 /storage", callback_data=f"save|{vid}")])
        else:
            # 普通搜索列表:仅显示发送给 TG
            keyboard.append([InlineKeyboardButton("🎵️ 点歌 ", callback_data=f"send|{vid}")])

    reply_markup = InlineKeyboardMarkup(keyboard)
    await msg.edit_text("请选择要下载的曲目:", reply_markup=reply_markup)

async def search_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ /search 列表点歌 """
    await process_search_and_respond(update, context, force_save=False)

@check_permission
async def download_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """ /download 持久化下载(带鉴权) """
    await process_search_and_respond(update, context, force_save=True)

# --- 按钮回调交互 ---
async def handle_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()

    if query.data == 'noop':
        return

    action, vid = query.data.split('|')
    is_persistent = (action == 'save')

    if is_persistent:
        user_id = update.effective_user.id
        chat_id = update.effective_chat.id
        if user_id not in ALLOWED_USERS and chat_id not in ALLOWED_USERS:
            await query.edit_message_text("🔒 错误:您当前没有持久化下载的权限。")
            return

    target_dir = PERSISTENT_DIR if is_persistent else CACHE_DIR
    await query.edit_message_text("⏳ 正在调度 yt-dlp 转换高音质 MP3,请稍候...")

    try:
        filepath = await asyncio.to_thread(download_audio, vid, target_dir)

        file_size_bytes = os.path.getsize(filepath)
        file_size_mb = file_size_bytes / (1024 * 1024)
        filename_clean = os.path.basename(filepath)

        if is_persistent:
            STATS["server_saves"] += 1
            escaped_path = filepath.replace('_', '\\_').replace('.', '\\.').replace('-', '\\-')
            await query.edit_message_text(
                f"💾 *已成功持久化至服务器*\n\n"
                f"📦 *文件名*:{filename_clean}\n"
                f"📐 *文件大小*:`{file_size_mb:.2f} MB`\n"
                f"📂 *存储路径*:`{escaped_path}`",
                parse_mode='MarkdownV2'
            )
        else:
            STATS["tg_sends"] += 1
            await query.edit_message_text(f"✅ 下载完成 ({file_size_mb:.2f} MB),正在发送...")

            with open(filepath, 'rb') as audio_file:
                await context.bot.send_audio(
                    chat_id=update.effective_chat.id,
                    audio=audio_file,
                    title=filename_clean.replace('.mp3', ''),
                    caption=f"📊 文件大小: {file_size_mb:.2f} MB\n⏱ 下载留存时间: 24小时"
                )
            await query.delete_message()

    except Exception as e:
        await query.edit_message_text(f"❌ 发生错误:{str(e)}")

def main():
    application = Application.builder().token(BOT_TOKEN).build()

    # 注册 1 小时缓存自动清理任务
    application.job_queue.run_repeating(cleanup_cache, interval=3600, first=10)

    # 命令集注册
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("admin", admin_command))
    application.add_handler(CommandHandler("music", music_command))
    application.add_handler(CommandHandler("search", search_command))
    application.add_handler(CommandHandler("download", download_command))

    # 按键回调注册
    application.add_handler(CallbackQueryHandler(handle_callback))

    print("Bot is running with optimized routing...")
    application.run_polling()

if __name__ == '__main__':
    main()

守护进程:创建 systemctl 长期运行

为了让机器人能在服务器重启后自动拉起,以及在崩溃时自动复活,我们推荐使用 Debian 原生的 systemd 进行守护。

1. 创建服务配置文件

nano /etc/systemd/system/musicbot.service

2. 填入配置(请根据实际情况修改 /data/tgbot 路径)

[Unit]
Description=Telegram Music Bot
After=network-online.target

[Service]
Type=simple
User=root
# 你的代码所在目录
WorkingDirectory=/data/tgbot
# 如果使用了虚拟环境,请将 /usr/bin/python3 替换为虚拟环境的路径
ExecStart=/usr/bin/python3 /data/tgbot/bot.py
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

3. 启动并设置开机自启

systemctl daemon-reload
systemctl enable musicbot
systemctl start musicbot

(使用 journalctl -u musicbot -f 可实时查看运行日志。)


🐳 进阶:打包 Docker 运行指南

如果你不想污染宿主机的环境,或者需要在多台机器间快速迁移,Docker 是最优雅的选择。

1. 准备文件结构 新建一个目录,将你的 bot.py 放入其中,并创建以下两个文件:

requirements.txt:

yt-dlp
python-telegram-bot[job-queue]

Dockerfile:

FROM python:3.11-slim

# 安装底层的 ffmpeg 支持
RUN apt-get update && \
    apt-get install -y --no-install-recommends ffmpeg && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

# 设置工作目录
WORKDIR /app

# 安装 Python 依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# 复制业务代码
COPY bot.py .

# 运行机器人
CMD ["python", "bot.py"]

2. 编写 `docker-compose.yml 这样可以方便地映射持久化音乐目录和配置文件(比如规避 403 用的cookies.txt`):

version: '3.8'

services:
  tg-music-bot:
    build: .
    container_name: tg_music_bot
    restart: unless-stopped
    volumes:
      # 映射缓存与持久化目录 (宿主机路径:容器内路径)
      - ./cache:/app/cache
      - /your/host/storage/music:/storage/music
      # 如果有 cookies 文件,取消下方注释映射进去
      # - ./cookies.txt:/app/cookies.txt

3. 一键起飞 在包含 docker-compose.yml 的目录下执行:

docker-compose up -d

现在,你的机器人已经安全地隔离在容器中 24 小时为你待命了!

这是一个非常棒的决定!把实战中的“掉坑”经历和“填坑”方案写进文档,才是这篇指南最值钱的地方。这能帮你省去未来可能再次遇到的所有疑惑,也能帮助别人避开重复的错误。

你可以参考这个结构来扩充你的文档,让它变得既硬核又有温度:


🚨 避坑指南:YouTube 风控对抗实录

在部署过程中,我们并非一帆风顺,以下是针对 YouTube 反爬虫风控的真实排查路径。

问题一:Requested format is not available

  • 现象:程序报错 Requested format is not available,即便歌曲明明存在。
  • 原因:YouTube 对机房 IP(VPS)进行了“隐性封锁(Shadowban)”,隐藏了所有流媒体格式。
  • 解决方案:不要试图在代码中挂载个人 Cookies(会导致异地关联封锁),应改用 代理链路隔离 策略。

问题二:Sign in to confirm you’re not a bot

  • 现象:被 YouTube 直接拦截,要求验证机器人身份。
  • 原因:Oracle/云厂商 IP 被标记为高频爬虫,且未进行合法设备验证。
  • 解决方案:放弃所有模拟手段,直接走高质量 ISP 住宅 IP 或家宽代理。

问题三:NameError: name 'output_dir' is not defined

  • 现象:逻辑崩溃,代码报错未定义变量。
  • 原因:在修改 ydl_opts 时,错误地将下载函数的配置复制到了搜索函数中。
  • 解决方案:确保搜索函数仅包含搜索所需的 extractor_args,严格区分下载与搜索功能的配置项。

🛠 终极架构方案:计算与网络分离

针对 IP 封锁问题,我们放弃了“代码伪装”,直接在网络架构层解决。

1. 架构图示

通过将逻辑运行与流量出口分离,实现了“计算力”与“IP纯净度”的完美结合。

2. 配置优化 (最终代码片段)

我们在 search_yt_music 和 download_audio 中统一使用优质节点作为出口,并移除了所有易失效的伪装参数:

# 最终稳定的出口配置
ydl_opts = {
    'format': 'bestaudio[ext=m4a]/bestaudio/best',
    'outtmpl': f'{output_dir}/%(title)s_{video_id}.%(ext)s',
    # 通过优质代理隧道绕过所有风控
    'proxy': 'socks5://这里填写代理信息,
    'quiet': True,
    'no_warnings': True
}

💡 专家提示

  • IP 筛选:优先选择 ASN 为 ISP(家宽) 或 冷门ASN 的节点,避开 Cloud/VPS 类型的 ASN。
  • 稳定性:若条件允许,构建代理节点池(Proxy Pool),实现节点的自动故障切换。
  • 环境补齐:虽然有了代理,仍建议安装 nodejs 以应对 YouTube 日益严苛的签名校验机制。

LeoKnox

Leo Leo Leo

文章评论