让discord Music bot在多个服务器中工作?Discord.py(重写)

2024-04-26 19:19:08 发布

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

这是我当前的播放命令,我知道它在检查是否在正确的语音频道时有问题,但我可能最终会发现,我担心的是,如果人们试图在不同的服务器上同时播放音乐,我很确定这段代码不会起作用

@bot.command(name='play', help='This command plays songs')
async def play(ctx, *args):
    searchterm = " ".join(args)
    print(searchterm)
    global queue

    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
        botchannel = ctx.bot.voice_clients
        print(channel)
        print(botchannel)
        await channel.connect()


    if 'youtube.com' in searchterm:

        queue.append(searchterm)

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

        async with ctx.typing():
            player = await YTDLSource.from_url(queue[0], loop=bot.loop)
            voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('**Now playing:** {}'.format(player.title))
        del(queue[0])

    elif 'youtube.com' not in searchterm:

        results = SearchVideos(searchterm, offset=1, mode = "dict", max_results=1).result()   
        resultlist = results['search_result']
        resultdict = resultlist[0]
        url = resultdict['link']
        queue.append(url)

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

        async with ctx.typing():
            player = await YTDLSource.from_url(queue[0], loop=bot.loop)
            voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

        await ctx.send('**Now playing:** {}'.format(player.title))
        del(queue[0])

Tags: loopurlmessageplayifserverqueuebot
1条回答
网友
1楼 · 发布于 2024-04-26 19:19:08

您的代码将在多个服务器上工作,但您只需要一个唯一的队列(因为queue是一个列表)。您可以创建一个dict,服务器ID作为密钥,队列作为值:

queue = {}
@bot.command(name='play', help='This command plays songs')
async def play(ctx, *, searchterm):
    global queue
    (...)
    if 'youtube.com' in searchterm:
        try:
            queue[ctx.guild.id].append(searchterm)
        except:
            queue[ctx.guild.id] = [searchterm]

    elif 'youtube.com' not in searchterm:
        results = SearchVideos(searchterm, offset=1, mode = "dict", max_results=1).result()   
        url = results['search_result'][0]['link']
        try:
            queue[ctx.guild.id].append(url)
        except:
            queue[ctx.guild.id] = [url]

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

    async with ctx.typing():
        player = await YTDLSource.from_url(queue[ctx.guild.id][0], loop=bot.loop)
        voice_channel.play(player, after=lambda e: print('Player error: %s' % e) if e else None)

    await ctx.send(f'**Now playing:** {player.title}')
    del(queue[ctx.guild.id][0])

相关问题 更多 >