发布于 2026-01-06 0 阅读
0

Telegram 视频下载机器人 - 教程

Telegram 视频下载机器人 - 教程

本文将一步步指导您如何创建一个能够从 YouTube 等网站下载视频的 Telegram 聊天机器人。

我们将使用 Python 和一个名为 的流行库python-telegram-bot来构建聊天机器人。让我们开始吧!

第一步:设置 Telegram 机器人

  • 打开 Telegram 并搜索“BotFather”机器人。
  • 与 BotFather 开始聊天,并按照说明创建一个新机器人。
  • 机器人创建完成后,您将收到一个 API 令牌。请保存此令牌,稍后会用到。

步骤 2:搭建开发环境

  • 如果您的电脑上还没有安装Python,请先安装。您可以从Python官方网站(python.org)下载。
  • 选择一款适用于 Python 的代码编辑器。一些常用的选择包括 Visual Studio Code、PyCharm 或 Sublime Text。安装你选择的编辑器。

步骤 3:安装所需库

  • 打开终端或命令提示符,运行以下命令安装python-telegram-bot库:
 pip install python-telegram-bot youtube_dl
Enter fullscreen mode Exit fullscreen mode

步骤 4:创建一个新的 Python 脚本

  • 打开代码编辑器,创建一个新的 Python 脚本。你可以给它命名telegram_video_downloader.py,或者选择任何你喜欢的名字。

步骤五:导入所需库

  • 在 Python 脚本开头添加以下代码行,以导入必要的库:
  import logging
  from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
  import youtube_dl
Enter fullscreen mode Exit fullscreen mode

步骤 6:设置日志记录

  • 添加以下代码行以在脚本中启用日志记录。这将有助于您调试可能出现的任何问题:
  logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                      level=logging.INFO)
  logger = logging.getLogger(__name__)
Enter fullscreen mode Exit fullscreen mode

步骤 7:定义一个处理/start命令的函数

  • 添加以下代码以定义一个函数,该函数将/start在机器人接收到命令时处理该命令:
  def start(update, context):
      context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm a video downloader bot. Just send me the URL of the video you want to download.")
Enter fullscreen mode Exit fullscreen mode

步骤 8:定义一个处理视频下载的函数

  • 添加以下代码以定义一个处理视频下载功能的函数:
def download_video(update, context):
    url = update.message.text

    ydl_opts = {
        'outtmpl': '%(title)s.%(ext)s',  # Output file name template
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',  
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(url, download=False)
            video_title = info['title']
            video_url = info['url']
            ydl.download([url])
            context.bot.send_message(chat_id=update.effective_chat.id, text="Video downloaded successfully!")
                        context.bot.send_video(chat_id=update.effective_chat.id, video=video_url, caption=video_title)
        except Exception as e:
            logger.error(f"Error downloading video: {e}")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to download the video.")
Enter fullscreen mode Exit fullscreen mode

步骤 9:设置主功能

  • 添加以下代码以设置运行机器人的主函数:
  def main():
      updater = Updater(token='YOUR_API_TOKEN', use_context=True)

      dispatcher = updater.dispatcher

      dispatcher.add_handler(CommandHandler("start", start))
      dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, download_video))

      updater.start_polling()

      updater.idle()
Enter fullscreen mode Exit fullscreen mode

步骤 10:运行机器人

  • 'YOUR_API_TOKEN'将函数中的值替换main()为您在步骤 1 中从 BotFather 收到的 API 令牌。
  • 在脚本末尾添加以下代码以运行机器人:
  if __name__ == '__main__':
      main()
Enter fullscreen mode Exit fullscreen mode

第 11 步:测试你的机器人

  • 保存 Python 脚本,然后使用以下命令从终端或命令提示符运行它:
  python telegram_video_downloader.py
Enter fullscreen mode Exit fullscreen mode
  • 打开 Telegram 并搜索你的机器人名称。
  • 开始与你的机器人聊天,并向它发送一个 YouTube 视频网址。
  • 机器人应回复一条消息,表明视频已成功下载。

你的机器人的完整代码应该如下所示:

import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import youtube_dl

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I'm a video downloader bot. Just send me the URL of the video you want to download.")

def download_video(update, context):
    url = update.message.text

    ydl_opts = {
        'outtmpl': '%(title)s.%(ext)s',
        'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best',
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(url, download=False)
            video_title = info['title']
            video_url = info['url']
            ydl.download([url])
            context.bot.send_message(chat_id=update.effective_chat.id, text="Video downloaded successfully!")
            context.bot.send_video(chat_id=update.effective_chat.id, video=video_url, caption=video_title)
        except Exception as e:
            logger.error(f"Error downloading video: {e}")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Failed to download the video.")

def main():
    updater = Updater(token='YOUR_API_TOKEN', use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, download_video))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

Enter fullscreen mode Exit fullscreen mode

'YOUR_API_TOKEN'请记住将函数中的值替换main()为您从 BotFather 收到的 API 令牌。

文章来源:https://dev.to/vlythr/video-downloader-bot-for-telegram-tutorial-541f