当前位置: 首页 > 知识库问答 >
问题:

不一致py-在音乐机器人上添加队列以解决不和谐和搜索问题

张啸
2023-03-14

在有2个问题。

首先,我试图制作一个音乐机器人来处理不和谐,它一直很好,直到我试图播放它的另一首歌,播放另一首歌(也许排队?)我不得不从语音频道离开机器人,再次编写播放命令(这不是我想要的),还试图从音乐标题播放,而不仅仅是从网址播放(因为它一团糟,去youtube复制链接我想玩的每首歌),但它只有当我把标题之间undescore(像!玩name_of_the_song)我尝试了很多东西,但似乎都不起作用,所以问这里是我最后的火腿。

因此,我想要的是从play命令一首接一首地播放bot,并且我可以从其标题中搜索一首歌曲,而无需再给我一首与我正在寻找的内容无关的歌曲

我的代码现在看起来像什么:

import discord
from discord.ext import commands, tasks
import youtube_dl
import asyncio
from keep_alive import keep_alive
from random import choice
import os, shutil


folder = 'music_files'

youtube_dl.utils.bug_reports_message = lambda: ''
ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': 'music_files/%(id)s.mp3',
    '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)


client = commands.Bot(command_prefix='!')

status = ['Jamming out to music!', 'Eating!', 'Sleeping!']

@client.event
async def on_ready():
    change_status.start()
    print('Bot is online!')

@client.event
async def on_member_join(member):
    channel = discord.utils.get(member.guild.channels, name='general')
    await channel.send(f'Welcome {member.mention}!  Ready to jam out? See `?help` command for details!')

@client.command(name='ping', help='This command returns the latency')
async def ping(ctx):
    await ctx.send(f'**Pong!** Latency: {round(client.latency * 1000)}ms')

@client.command(name='hello', help='This command returns a random welcome message')
async def hello(ctx):
    responses = ['***grumble*** Why did you wake me up?', 'Top of the morning to you lad!', 'Hello, how are you?', 'Hi', '**Wasssuup!**']
    await ctx.send(choice(responses))

@client.command(name='die', help='This command returns a random last words')
async def die(ctx):
    responses = ['why have you brought my short life to an end', 'i could have done so much more', 'i have a family, kill them instead']
    await ctx.send(choice(responses))

@client.command(name='credits', help='This command returns the credits')
async def credits(ctx):
    await ctx.send('Made by Danxx')
    await ctx.send('Thanks to `RK Coding` for the base code')

@client.command(name='play', help='This command plays music')
async def play(ctx, url):
    if not ctx.message.author.voice:
        await ctx.send("You are not connected to a voice channel")
        return

    else:
        channel = ctx.message.author.voice.channel

    await channel.connect()

    server = ctx.message.guild
    voice_channel = server.voice_client

    async with ctx.typing():
        player = await YTDLSource.from_url(url, loop=client.loop, stream=True)
        voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

    await ctx.send('**Now playing:** {}'.format(player.title))

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

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

@client.command(name='stop', help='This command stops the music and makes the bot leave the voice channel')
async def stop(ctx):
    voice_client = ctx.message.guild.voice_client
    await voice_client.stop()

@client.command()
async def leave(ctx):
    for song in os.listdir(folder):
                file_path = os.path.join(folder, song)
                try:
                    if os.path.isfile(file_path) or os.path.islink(file_path):
                        os.unlink(file_path)
                    elif os.path.isdir(file_path):
                        shutil.rmtree(file_path)
                except Exception as e:
                    print('Failed to delete %s. Reason %s' % (file_path, e))
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_connected():
        await voice.disconnect()
    else:
        await ctx.send("The bot is not connected to a voice channel.")

@tasks.loop(seconds=20)
async def change_status():
    await client.change_presence(activity=discord.Game(choice(status)))


keep_alive()
client.run('TOKEN')

谢谢你的帮助注意:保持活着是我为保持活着的方法做的一个标题,所以机器人全天候在线,所以如果你想忽略它,也为我糟糕的英语感到抱歉

共有1个答案

司空奕
2023-03-14

你可以排队等待公会播放音乐。可以使用内置模块队列,也可以仅使用列表。类似这样的方法会奏效:

queue = {}
def addToQueue(guild, song):
    if guild.id in queue:
        queue[guild.id] = []
    queue[guild.id].append(song)

async def playSong(ctx, channel):
    async with ctx.typing():
        song = queue[channel.guild.id].pop(0, None)
        if song == None:
            return
        player = await YTDLSource.from_url(song, loop=client.loop, stream=True)
        channel.play(
            player,
            after=lambda e:
            print('Player error: %s' % e) if e else await playSong(ctx, channel)
        )

    await ctx.send('**Now playing:** {}'.format(player.title))

@client.command(name='play', help='This command plays music')
async def play(ctx, url):
    if not ctx.message.author.voice:
        await ctx.send("You are not connected to a voice channel")
        return

    else:
        channel = ctx.message.author.voice.channel
    
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if channel != voice and voice is None:
        await channel.connect()
    elif channel != voice and voice is not None:
        await ctx.send("Already connected to a channel")
        return

    server = ctx.message.guild
    voice_channel = server.voice_client
    addToQueue(ctx.message.guild, url)
    await playSong(ctx, voice_channel)

对于您的搜索问题,您提供的代码似乎没有试图解决这个问题。你将不得不使用Youtube API。

 类似资料:
  • 我已经在不和谐机器人上工作了几天。 起初只是简单的命令等,但慢慢地,我也致力于音乐机器人的主题。 我也使用YouTube数据API来实现这一点,到目前为止一切都正常。不过,我现在想合并一个Youtube搜索命令或将其构建到另一个(Play命令)中。我已经有半个搜索命令了。 到目前为止你可以做$play(歌名) 将选择找到的第一个轨迹。 然而,我希望能够看到前10个搜索结果,然后在它们之间进行选择。

  • 当我在discord内部运行以下脚本(“cmd中的node musicbot.js”)和“!play ytlink”时,bot加入语音通道,并在控制台中记录命令和链接。然而,音乐并没有开始播放。我安装了ffmpeg、ytdl核心和discord。js。 有人能帮我吗?我不知道是哪一部分搞砸了。

  • 我试图让我的自我机器人加入服务器。我知道self-bots反对discordtos,但我想学习一些新的东西。 这是我尝试过的命令: 错误:

  • 我正在努力让我的机器人进入语音频道,我已经阅读了这里的很多帖子,但没有一篇能够解决我的问题,我正在尝试让我的机器人复制yt视频的声音,但它甚至没有加入,我不知道该怎么办,下面是代码:

  • 我希望我的不和谐机器人加入语音频道。但是我遇到了一个问题,每当我想让它加入风投时,什么都不会发生——甚至没有错误。我尝试过SO/Git的其他解决方案,但没有一个适合我(下面有一个)。 编辑:解决了!问题是:没有不和。已安装py[语音]模块。解决方案:

  • 我使用repl。它让我的不和机器人。我使用Python并遵循本教程: https://www.youtube.com/watch?v=SPTfmiYiuok 这是我的代码: