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

为Python Discord音乐机器人添加YouTube关键词搜索功能(保留URL播放)的新手指导请求

Adding YouTube Search to Your Discord Music Bot

Hey there! I see you're just starting out with Discord.py and building a music bot—great choice for practice! Let's get that YouTube keyword search feature working alongside your existing URL playback. Here's a step-by-step breakdown tailored for beginners:

1. Get a YouTube Data API Key

First, you'll need an API key to make search requests to YouTube:

  • Head to Google Cloud Console, create a new project.
  • Search for "YouTube Data API v3" and enable it for your project.
  • Go to "Credentials" > "Create Credentials" > "API Key"—copy this key, you'll need it later.

2. Install Required Libraries

You'll need the Google API client to interact with the YouTube API. Also, consider switching to yt-dlp (a maintained fork of youtube_dl) since it's more up-to-date and fixes many compatibility issues:

pip install google-api-python-client yt-dlp discord.py

3. Modify Your Bot Code

Let's adjust your existing command to handle both URLs and search queries. Here's the updated code with clear explanations:

First, add the necessary imports and API setup at the top of your file:

import discord
from discord.ext import commands
import yt_dlp as youtube_dl
from googleapiclient.discovery import build

# Replace this with your actual YouTube API key
YOUTUBE_API_KEY = "YOUR_API_KEY_HERE"
youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)

# Keep your existing options (tweaked slightly for yt-dlp)
YDL_OPTIONS = {
    'format': 'bestaudio/best',
    'noplaylist': True,
    'quiet': True
}

FFMPEG_OPTIONS = {
    'options': '-vn'
}

Now, update your p command to handle search queries:

async def p(self, ctx, *, query):
    # Check if user is in a voice channel
    if ctx.author.voice is None:
        return await ctx.send("You are not connected to a voice channel!")
    voice_channel = ctx.author.voice.channel

    # Connect or move to the user's voice channel
    if ctx.voice_client is None:
        await voice_channel.connect()
    else:
        await ctx.voice_client.move_to(voice_channel)
    
    ctx.voice_client.stop()
    vc = ctx.voice_client

    # Determine if input is a URL or search query
    if "youtube.com" in query or "youtu.be" in query:
        video_url = query
    else:
        # Use YouTube API to fetch the top search result
        try:
            search_response = youtube.search().list(
                q=query,
                part="id",
                maxResults=1,
                type="video"
            ).execute()

            if not search_response['items']:
                return await ctx.send("No results found for that search query!")
            
            video_id = search_response['items'][0]['id']['videoId']
            video_url = f"https://www.youtube.com/watch?v={video_id}"
            await ctx.send(f"Found your song: {video_url}")
        except Exception as e:
            return await ctx.send(f"Oops, something went wrong searching YouTube: {str(e)}")
    
    # Play the audio (using yt-dlp for better reliability)
    try:
        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(video_url, download=False)
            url2 = info['url']  # yt-dlp simplifies this compared to old youtube_dl
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)
            await ctx.send(f"Now playing: {info['title']}")
    except Exception as e:
        await ctx.send(f"Error playing the audio: {str(e)}")

Key Tips for Beginners:

  • The * in ctx, *, query lets the command accept multi-word search queries (like !p never gonna give you up).
  • We added basic error handling to catch issues like no search results or API problems—this will help you debug as you learn.
  • yt-dlp is a drop-in replacement for youtube_dl, so you won't have to rewrite most of your existing playback code.

Important Reminders:

  • Keep your YouTube API key private—don't share it in public code repositories!
  • The free YouTube API quota gives you 10,000 units per day, which is more than enough for a testing bot.

That's it! Test the command with both URLs and search keywords—your bot should now handle both cases smoothly.

内容的提问来源于stack exchange,提问作者Agni Sen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:57:31