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

时间:2021-02-02 10:35:07

标签: python discord.py

我制作了一个播放音乐的 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: ")

1 个答案:

答案 0 :(得分:0)

在您的项目中创建一个名为 #NavList { background: #43C17A; color: white; text-align: center; padding: 30px 0 30px 50px; width: 100%; max-width: 200px; top: 0; bottom: 0; position: fixed; } #NavList li { font-size: 16px; padding: 8px; margin: 8px 0; list-style-type: none; transition: 250ms; } #NavList li:hover { background:white; color: #43C17A; cursor: pointer; } 的文件夹,然后将一个名为 cogs 的文件添加到 cogs 文件夹中。将以下所有代码放入该 music.py 文件中:

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)) 文件的 on_ready() 方法中,添加以下内容:

.py

将代码修改为您希望命令打印的任何内容。如果有效,请验证此答案。