You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在discord.py项目中用Python发HTTP请求获取YouTube搜索结果URL

Python 端实现指导

1. 输入内容合法性判断(是否为YouTube链接)

用正则匹配即可覆盖绝大多数YouTube合法链接场景,代码示例:

import re

YOUTUBE_URL_PATTERN = re.compile(
    r'^(https?://)?(www\.)?(youtube\.com|youtu\.be)/(watch\?v=|shorts/|embed/)?[a-zA-Z0-9_-]{11}(&.*)?$'
)

def is_youtube_link(input_str: str) -> bool:
    return bool(YOUTUBE_URL_PATTERN.match(input_str.strip()))

匹配范围包括常规watch链接、短链youtu.be、shorts链接、嵌入链接等常见YouTube链接格式

2. YouTube关键词搜索实现

你已经在使用youtube-dl/yt-dlp,无需额外引入HTTP请求解析逻辑,直接复用下载工具内置的搜索能力即可,搜索前缀为ytsearch{N}:,其中N为需要返回的结果数量,取首个结果填1即可。

与现有流程适配逻辑

你原有播放流程可以无需大改,仅需要在传入youtube-dl前对非链接输入做包装:

def get_ytdl_input(user_input: str) -> str:
    if is_youtube_link(user_input):
        return user_input.strip()
    # 非链接内容包装为搜索指令
    return f"ytsearch1:{user_input.strip()}"

搜索结果URL提取(可选)

如果你需要单独拿到搜索结果的URL再走原有下载逻辑,可以用youtube-dl的模拟提取功能直接拿到结果URL,无需下载:

import youtube_dl

def get_first_search_result_url(keyword: str) -> str | None:
    ydl_opts = {
        'quiet': True,
        'noplaylist': True,
        'extract_flat': 'in_playlist'
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        try:
            info = ydl.extract_info(f"ytsearch1:{keyword}", download=False)
            if not info.get('entries'):
                return None
            return info['entries'][0]['webpage_url']
        except Exception:
            return None

3. Discord.py 指令侧适配示例

以常规前缀指令为例,修改你的play指令处理逻辑即可:

@bot.command(name='play')
async def play(ctx, *, input_content: str):
    # 1. 处理用户输入
    if not is_youtube_link(input_content):
        video_url = get_first_search_result_url(input_content)
        if not video_url:
            await ctx.send("未找到对应搜索结果")
            return
    else:
        video_url = input_content.strip()
    # 2. 走你原有下载、转码、播放逻辑即可
    # 你的原有代码...

注意事项

  • 若你已经替换为yt-dlp(youtube-dl的分支维护版本,兼容性更强),以上逻辑完全通用无需修改
  • 可自行调整ytsearch{N}中的N值,返回多个搜索结果让用户选择

内容的提问来源于stack exchange,提问作者Happy Lama

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 11:12:03