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

如何为Python开发的Discord音乐机器人添加?search歌曲搜索播放功能

Discord音乐机器人搜索功能实现方案

你可以直接替换原有代码为以下修改后的版本,原有功能完全保留,新增的搜索逻辑完全匹配你的需求:

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):
    def __init__(self, client):
        self.client = client
        # 通用配置提前,避免重复定义
        self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        self.YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}

    @commands.command()
    async def join(self, ctx):
        if ctx.author.voice is None:
            await ctx.send("ur not in a vc bruv")
            return
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self, ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self, ctx, url):
        ctx.voice_client.stop()
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(self.YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            audio_url = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(audio_url, **self.FFMPEG_OPTIONS)
            vc.play(source)

    @commands.command()
    async def search(self, ctx, *, query):
        # 检查用户语音状态
        if ctx.author.voice is None:
            await ctx.send("ur not in a vc bruv")
            return
        # 自动加入用户所在频道
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)
        
        vc = ctx.voice_client
        vc.stop()

        with youtube_dl.YoutubeDL(self.YDL_OPTIONS) as ydl:
            # 调用YouTube搜索接口,取匹配度最高的第一条结果
            info = ydl.extract_info(f"ytsearch:{query}", download=False)
            if not info['entries']:
                await ctx.send("未找到对应歌曲")
                return
            song_info = info['entries'][0]
            audio_url = song_info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(audio_url, **self.FFMPEG_OPTIONS)
            vc.play(source)
            # 不需要显示歌名可以删掉下面这行
            await ctx.send(f"正在播放: {song_info['title']}")

    @commands.command()
    async def pause(self, ctx):
        await ctx.send("paused bro")
        await ctx.voice_client.pause()

    @commands.command()
    async def resume(self, ctx):
        await ctx.send("resumed bro")
        await ctx.voice_client.resume()

def setup(client):
    client.add_cog(music(client))

补充说明

  • search方法参数里的*是为了支持带空格的歌曲名,会把用户输入的所有关键词统一识别为搜索内容
  • 如果后续出现youtube_dl抓取失效的问题,直接替换为yt-dlp包即可,用法和接口完全兼容,无需修改其他逻辑
  • 如果需要让用户选择多个搜索结果,把搜索前缀改为ytsearch5:即可返回前5条匹配结果,自行增加选择逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:06:05