You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为已实现YouTube频道新视频检测、下载与转音频的Python脚本添加Telegram频道上传功能?

Great work on building out the YouTube video detection and audio conversion flow! Let's figure out the best way to get those audio files uploaded to your Telegram channel. Here's a breakdown of the libraries you mentioned and step-by-step implementations for the easiest options:

库选择对比

  • telegram-upload: The most straightforward option if you just need to upload files quickly. It handles authentication setup and has a minimal API, perfect for your current use case.
  • python-telegram-bot: Ideal if you plan to expand into a full-featured Telegram bot later (e.g., adding commands, handling user interactions). It’s well-documented and widely adopted.
  • Telethon: Offers low-level control over Telegram’s API, but has a steeper learning curve. Best for advanced scenarios like managing channel permissions or bulk operations.

For your immediate goal of uploading audio files to a channel, telegram-upload is the fastest to implement. If you want to build a long-running bot down the line, python-telegram-bot is the better choice. Let’s cover both:


方案1:使用telegram-upload(快速实现)

步骤1:安装库

pip install telegram-upload

步骤2:配置认证

Run this command once to set up your Telegram credentials (you’ll need an API ID/hash from Telegram’s developer portal – it’s free and takes 2 minutes):

telegram-upload --configure

Follow the prompts to enter your API ID, API hash, phone number, and verification code. This saves a config file so you don’t have to re-authenticate every time.

步骤3:修改你的代码

We’ll update your script to upload the converted MP3 right after downloading, plus clean up the dwl_vid function to use parameters instead of global variables:

import youtube_dl
import urllib.request
import re
from telegram_upload import upload  # Import the upload function

html = urllib.request.urlopen("https://www.youtube.com/c/peterschiff/videos")
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'outtmpl': '%(title)s.%(ext)s'  # Define filename pattern to easily locate the MP3
}

# Load existing video IDs from file
txt_file = open('outfile.txt', 'r')
file_content = txt_file.read()
content_list = file_content.split()
txt_file.close()

# Identify new videos
new_video_ids = set(video_ids) - set(content_list)

# Save new video IDs to file
with open('outfile.txt', 'a') as outfile:
    outfile.write('\n'.join(new_video_ids))

def download_and_convert(video_url):
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        # Extract video info to get the final MP3 filename
        info = ydl.extract_info(video_url, download=True)
        return f"{info['title']}.mp3"

def upload_to_channel(file_path, channel_username):
    # Upload the file (use @channel_username format for your channel)
    upload(files=[file_path], chat_id=channel_username)

# Process each new video
for video_id in new_video_ids:
    video_url = f'https://www.youtube.com/watch?v={video_id}'
    mp3_file = download_and_convert(video_url)
    upload_to_channel(mp3_file, "@your_telegram_channel_username")
    print(f"Successfully uploaded {mp3_file} to your channel!")

方案2:使用python-telegram-bot(适合扩展为机器人)

If you want to turn this into a long-running bot that can handle more tasks, use this approach:

步骤1:安装库

pip install python-telegram-bot

步骤2:设置机器人

  1. Chat with @BotFather on Telegram to create a new bot and get your bot token.
  2. Add the bot as an admin to your Telegram channel (grant "Send messages" and "Upload files" permissions).

步骤3:代码实现

import youtube_dl
import urllib.request
import re
from telegram import Bot
import asyncio

# Replace with your bot token and channel username
BOT_TOKEN = "your_bot_token_here"
CHANNEL_USERNAME = "@your_telegram_channel_username"

html = urllib.request.urlopen("https://www.youtube.com/c/peterschiff/videos")
video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())

ydl_opts = {
    'format': 'bestaudio/best',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    'outtmpl': '%(title)s.%(ext)s'
}

# Load existing video IDs
txt_file = open('outfile.txt', 'r')
file_content = txt_file.read()
content_list = file_content.split()
txt_file.close()

new_video_ids = set(video_ids) - set(content_list)

# Save new IDs to file
with open('outfile.txt', 'a') as outfile:
    outfile.write('\n'.join(new_video_ids))

def download_and_convert(video_url):
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(video_url, download=True)
        return f"{info['title']}.mp3"

async def upload_to_channel(file_path):
    bot = Bot(token=BOT_TOKEN)
    # Upload audio with an optional caption
    await bot.send_audio(
        chat_id=CHANNEL_USERNAME,
        audio=open(file_path, 'rb'),
        caption="New audio from your YouTube channel!"
    )
    await bot.close()

# Process new videos (run async code)
for video_id in new_video_ids:
    video_url = f'https://www.youtube.com/watch?v={video_id}'
    mp3_file = download_and_convert(video_url)
    asyncio.run(upload_to_channel(mp3_file))
    print(f"Uploaded {mp3_file} to channel!")

Quick Note

Consider switching from youtube_dl to yt-dlp (a maintained fork) since youtube_dl is no longer actively updated. Install it with pip install yt-dlp and replace import youtube_dl with import yt_dlp as youtube_dl – most of your code will work unchanged.

内容的提问来源于stack exchange,提问作者Sergio Iliev

火山引擎 最新活动