已完成

Telegram YouTube Bot

A powerful Telegram bot for downloading YouTube videos

技术栈

TypeScriptNode.jsTelegram Bot APIYouTube API

Telegram YouTube Bot

项目概述

这是一个功能强大的Telegram机器人,专门用于下载YouTube视频。用户可以通过简单的命令在Telegram中直接下载YouTube内容,支持多种格式和质量选择。

技术架构

🤖 核心技术栈

  • TypeScript: 主要开发语言,提供类型安全
  • Node.js: 运行时环境
  • Telegram Bot API: 机器人交互接口
  • YouTube API: 视频信息获取
  • ytdl-core: YouTube视频下载核心库

📱 Bot架构设计

用户输入 → 命令解析 → YouTube解析 → 视频下载 → 文件发送
    ↓         ↓         ↓         ↓         ↓
Telegram   Bot API   ytdl-core  FFmpeg   Telegram

主要功能

1. 视频下载

  • 支持YouTube视频链接解析
  • 多种质量选择(720p, 1080p, 4K等)
  • 音频提取功能
  • 批量下载支持
import { Telegraf } from 'telegraf';
import ytdl from 'ytdl-core';

class YouTubeBot {
  private bot: Telegraf;
  
  constructor(token: string) {
    this.bot = new Telegraf(token);
    this.setupCommands();
  }
  
  private setupCommands() {
    this.bot.command('download', async (ctx) => {
      const url = ctx.message.text.split(' ')[1];
      
      if (!ytdl.validateURL(url)) {
        return ctx.reply('请提供有效的YouTube链接');
      }
      
      await this.downloadVideo(ctx, url);
    });
  }
  
  private async downloadVideo(ctx: any, url: string) {
    try {
      const info = await ytdl.getInfo(url);
      const title = info.videoDetails.title;
      
      ctx.reply(`正在下载: ${title}`);
      
      const stream = ytdl(url, {
        quality: 'highest',
        filter: 'audioandvideo'
      });
      
      // 发送视频文件
      await ctx.replyWithVideo({ source: stream });
      
    } catch (error) {
      ctx.reply('下载失败,请检查链接是否有效');
    }
  }
}

2. 智能命令系统

  • /start - 启动机器人
  • /download <URL> - 下载视频
  • /audio <URL> - 仅下载音频
  • /info <URL> - 获取视频信息
  • /help - 帮助信息

3. 用户体验优化

  • 实时下载进度显示
  • 文件大小预检查
  • 错误处理和用户提示
  • 多语言支持

核心实现

YouTube视频信息获取

async function getVideoInfo(url: string) {
  try {
    const info = await ytdl.getInfo(url);
    
    return {
      title: info.videoDetails.title,
      duration: info.videoDetails.lengthSeconds,
      views: info.videoDetails.viewCount,
      author: info.videoDetails.author.name,
      thumbnail: info.videoDetails.thumbnails[0].url,
      formats: info.formats.map(format => ({
        quality: format.qualityLabel,
        container: format.container,
        size: format.contentLength
      }))
    };
  } catch (error) {
    throw new Error('无法获取视频信息');
  }
}

文件大小控制

function checkFileSize(format: any): boolean {
  const maxSize = 50 * 1024 * 1024; // 50MB Telegram限制
  return parseInt(format.contentLength) < maxSize;
}

async function selectBestFormat(formats: any[]) {
  // 选择最佳质量但不超过大小限制的格式
  const validFormats = formats.filter(checkFileSize);
  
  return validFormats.reduce((best, current) => {
    if (!best) return current;
    
    const currentQuality = parseInt(current.qualityLabel);
    const bestQuality = parseInt(best.qualityLabel);
    
    return currentQuality > bestQuality ? current : best;
  });
}

错误处理机制

class BotErrorHandler {
  static handle(error: Error, ctx: any) {
    console.error('Bot Error:', error);
    
    if (error.message.includes('Video unavailable')) {
      ctx.reply('❌ 视频不可用或已被删除');
    } else if (error.message.includes('Private video')) {
      ctx.reply('❌ 无法下载私有视频');
    } else if (error.message.includes('Too large')) {
      ctx.reply('❌ 文件过大,请选择较低质量');
    } else {
      ctx.reply('❌ 下载失败,请稍后重试');
    }
  }
}

部署方案

1. Heroku部署

{
  "name": "telegram-youtube-bot",
  "description": "YouTube downloader bot for Telegram",
  "repository": "https://github.com/quanxquan/telegram-youtube-bot",
  "keywords": ["telegram", "bot", "youtube", "downloader"],
  "env": {
    "BOT_TOKEN": {
      "description": "Telegram Bot Token from @BotFather"
    },
    "NODE_ENV": {
      "value": "production"
    }
  },
  "buildpacks": [
    {
      "url": "heroku/nodejs"
    },
    {
      "url": "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git"
    }
  ]
}

2. Docker部署

FROM node:16-alpine

# 安装FFmpeg
RUN apk add --no-cache ffmpeg

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

COPY . .

RUN npm run build

EXPOSE 3000

CMD ["npm", "start"]

3. 环境配置

BOT_TOKEN=your_telegram_bot_token
YOUTUBE_API_KEY=your_youtube_api_key
MAX_FILE_SIZE=50000000
DOWNLOAD_PATH=/tmp/downloads

性能优化

1. 内存管理

  • 流式下载,避免大文件占用内存
  • 定时清理临时文件
  • 连接池管理

2. 并发控制

class DownloadQueue {
  private queue: Array<DownloadTask> = [];
  private processing = 0;
  private maxConcurrent = 3;
  
  async add(task: DownloadTask) {
    this.queue.push(task);
    this.process();
  }
  
  private async process() {
    if (this.processing >= this.maxConcurrent || this.queue.length === 0) {
      return;
    }
    
    this.processing++;
    const task = this.queue.shift();
    
    try {
      await task.execute();
    } finally {
      this.processing--;
      this.process(); // 处理下一个任务
    }
  }
}

安全考虑

1. 用户限制

  • 下载频率限制
  • 文件大小限制
  • 用户白名单机制

2. 内容过滤

  • 版权内容检测
  • 恶意链接过滤
  • 年龄限制内容处理

使用统计

📊 性能指标

  • 日均下载量:200+
  • 成功率:95%
  • 平均响应时间:3秒
  • 支持格式:MP4, WEBM, MP3

👥 用户反馈

  • 用户数量:150+
  • 满意度:4.8/5
  • 功能请求:10+

未来规划

短期目标

  • 添加播放列表下载
  • 支持更多视频平台
  • 改进用户界面
  • 添加下载历史

长期规划

  • Web管理面板
  • 用户订阅系统
  • 云存储集成
  • API开放接口

学习收获

通过这个项目,我深入学习了:

  1. Telegram Bot开发

    • Bot API的使用
    • Webhook vs Polling
    • 用户交互设计
  2. 视频处理技术

    • YouTube API集成
    • 流媒体处理
    • 格式转换
  3. 系统设计

    • 异步处理
    • 错误恢复
    • 性能优化
  4. 部署运维

    • 容器化部署
    • 监控告警
    • 日志管理

这个项目不仅提升了我的技术能力,还让我理解了如何构建用户友好的自动化工具。通过实际用户的使用和反馈,我学会了如何持续改进产品体验。