如何制作不在系统上下载音乐的discord.py音乐?

2024-04-26 09:53:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个discord bot命令来播放音乐。它做得很好,也在播放音乐。问题是,每当我命令它时,它都会在我的系统上下载音乐。我的系统上没有太多的空间来保留这些mp3。那么,我能做些什么。下面是代码。希望你能帮助我。(我还下载了所有模块,包括ffmpeg)

@client.command(aliases=["p"])
async def play(ctx, *, query):
    try:
        voiceChannel = discord.utils.get(ctx.guild.voice_channels, name=str(ctx.message.author.voice.channel))
        await voiceChannel.connect()
        await ctx.send("Joined " + str(ctx.message.author.voice.channel) + " voice channel!:white_check_mark:")
    except AttributeError:
        await ctx.send(ctx.message.author.mention + " is not in any voice channel :negative_squared_cross_mark:")
        return
    except Exception as e:
        print(e)

    url = None
    if len(query) == 0:
        await ctx.send(
            ctx.message.author.mention + "you need to provide a youtube video link or any query with the play command :negative_squared_cross_mark:")
        return
    elif query.startswith("https://www.youtube.com/watch?v="):
        url = query
    else:
        s = gs.search("https://www.youtube.com/results?search_query=" + query.replace(" ", "+"), "com", "en", num=10,
                      stop=10, pause=2.0)
        for i in s:
            if i.startswith("https://www.youtube.com/watch?v="):
                url = i
                break
    if url == None:
        await ctx.send(ctx.message.author.mention + " some error is caused :negative_squared_cross_mark:")
        return
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    yt = YouTube(str(url))
    yt_embed = discord.Embed(title=yt.title + ":musical_note:", description=yt.description, color=discord.Colour.red())
    yt_embed.set_thumbnail(url=yt.thumbnail_url)
    yt_embed.add_field(name="Author: ", value=yt.author + ":musical_score: ", inline=False)
    yt_embed.add_field(name="Duration: ", value=str(yt.length) + " seconds :clock3: ", inline=False)
    yt_embed.add_field(name="Publish date: ", value=str(yt.publish_date) + ":calendar_spiral:", inline=False)
    yt_embed.add_field(name="Rating: ", value=str(yt.rating) + ":star2:", inline=False)
    yt_embed.add_field(name="Views: ", value=str(yt.views) + ":eyes:", inline=False)
    t = yt.streams.filter(only_audio=True)
    t[0].download(".\songs")
    try:
        print(".\songs\\" + yt.title + ".mp4")
        voice.play(discord.FFmpegPCMAudio(".\songs\\" + yt.title + ".mp4"))
        await ctx.send("Playing " + yt.title + " :loud_sound:")
        await ctx.send(embed=yt_embed)
    except Exception as e:
        print(e)
        await ctx.send(ctx.message.author.mention + " Alena already playing audio :negative_squared_cross_mark:")
        await ctx.send(
            "Use stop command to stop the currently playing song and leave command to make Alena exit the current voice channel")
        return



@client.command(aliases=["disconnect", "exit"])
async def leave(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_connected():
        await voice.disconnect()
        await ctx.send("Disconnected :wave:")
    else:
        await ctx.send("The bot is not connected to a voice channel. :negative_squared_cross_mark:")


@client.command()
async def pause(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_playing():
        voice.pause()
        await ctx.send("Paused :pause_button:")
    else:
        await ctx.send("Currently no audio is playing. :negative_squared_cross_mark:")



@client.command()
async def resume(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_paused():
        voice.resume()
        await ctx.send("Resumed :play_pause: ")
    else:
        await ctx.send("The audio is not paused. :negative_squared_cross_mark:")

@client.command()
async def stop(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    voice.stop()
    await ctx.send("Stopped playing :octagonal_sign: ")

Tags: clientsendisembedawaitquerycommandauthor
1条回答
网友
1楼 · 发布于 2024-04-26 09:53:31

在项目中创建名为cogs的文件夹,然后将名为music.py的文件添加到cogs文件夹中。将下面的所有代码放在music.py文件中:

import asyncio
import discord
import youtube_dl
from discord.ext import commands

# Suppress noise about console usage from errors
youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

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

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
        self.url = data.get('url')

    @classmethod
    async def from_url(cls, url, *, loop=None, stream=False):
        loop = loop or asyncio.get_event_loop()
        data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))

        if 'entries' in data:
            # take first item from a playlist
            data = data['entries'][0]

        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)


class Music(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(description="joins a voice channel")
    async def join(self, ctx):
        if ctx.author.voice is None or ctx.author.voice.channel is None:
            return await ctx.send('You need to be in a voice channel to use this command!')

        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            vc = await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)
            vc = ctx.voice_client

    @commands.command(description="streams music")
    async def play(self, ctx, *, url):
        async with ctx.typing():
            player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
            ctx.voice_client.play(player, after=lambda e: print('Player error: %s' % e) if e else None)
        await ctx.send('Now playing: {}'.format(player.title))
    
    @commands.command(description="pauses music")
    async def pause(self, ctx):
        ctx.voice_client.pause()
    
    @commands.command(description="resumes music")
    async def resume(self, ctx):
        ctx.voice_client.resume()

    @commands.command(description="stops and disconnects the bot from voice")
    async def leave(self, ctx):
        await ctx.voice_client.disconnect()

    @play.before_invoke
    async def ensure_voice(self, ctx):
        if ctx.voice_client is None:
            if ctx.author.voice:
                await ctx.author.voice.channel.connect()
            else:
                await ctx.send("You are not connected to a voice channel.")
                raise commands.CommandError("Author not connected to a voice channel.")
        elif ctx.voice_client.is_playing():
            ctx.voice_client.stop()

def setup(bot):
    bot.add_cog(Music(bot))

然后,在主.py文件的on_ready()方法中,添加以下内容:

@bot.event
async def on_ready():
    bot.load_extension("cogs.music")

将代码修改为希望命令打印的内容。请验证此答案是否有效

相关问题 更多 >