python 3.x版不和.py音乐机器人如何制作可以在多个服务器上播放的音乐队列

2024-03-29 15:18:25 发布

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

我有一个python discord bot的代码,它很适合在一台服务器上排队播放音乐,但是当多台服务器都在使用它时,它会等到请求的第一首歌曲完成后,再在另一台服务器上播放下一首。我想得到它,这样它将能够在多个服务器播放多首歌曲。在

import asyncio
from discord.ext import commands

client = commands.Bot(command_prefix='!')
songs = asyncio.Queue()
play_next_song = asyncio.Event()


@client.event
async def on_ready():
    print('client ready')


async def audio_player_task():
    while True:
        play_next_song.clear()
        current = await songs.get()
        current.start()
        await play_next_song.wait()


def toggle_next():
    client.loop.call_soon_threadsafe(play_next_song.set)


@client.command(pass_context=True)
async def play(ctx, url):
    if not client.is_voice_connected(ctx.message.server):
        voice = await client.join_voice_channel(ctx.message.author.voice_channel)
    else:
        voice = client.voice_client_in(ctx.message.server)

    player = await voice.create_ytdl_player(url, after=toggle_next)
    await songs.put(player)

client.loop.create_task(audio_player_task())

client.run('token')

Tags: 服务器clientasynciomessagetaskplayasyncsong
1条回答
网友
1楼 · 发布于 2024-03-29 15:18:25

编一本字典,把键设为服务器id像歌曲一样有价值。 像这样:

client = commands.Bot(command_prefix='!')
songs = asyncio.Queue()
play_next_song = asyncio.Event()
queues = {} #new dictionary

@client.event
async def on_ready():
    print('client ready')


async def audio_player_task():
    while True:
        play_next_song.clear()
        current = await queues[id].get()
        current.start()
        await play_next_song.wait()

def toggle_next():
    client.loop.call_soon_threadsafe(play_next_song.set)

@client.command(pass_context=True)
async def play(ctx, url):
    ctx.message.server = server
    queues[server.id] = songs
    ...

当你添加新歌时, 这样做:等待排队[服务器id].put(播放器)

相关问题 更多 >