我制作了一个带有discordpy(ver 0.16.12)和youtube-dl的discord音乐支持机器人。我用asyncio模块制作了队列系统,但是我却陷于制作跳过系统。
此代码在python 3.5.4和3.6.8上运行,不和谐的模块版本为0.16.12。
play_next_song = asyncio.Event()
players = {}
links = {}
names = {}
m_players = asyncio.Queue()
m_links = []
m_names = []
np_link = ''
np_name = ''
async def player_task(id,ch) :
global np_link
global np_name
while True :
play_next_song.clear()
np_name = names[id].pop(0)
np_link = links[id].pop(0)
current = await players[id].get()
current.start()
await app.send_message(ch, embed=discord.Embed(title=" Now playing : " + str(np_name),description='link : ' + str(np_link) ,color=0xC47EED))
await play_next_song.wait()
np_link = ''
np_name = ''
def toggle_next() :
app.loop.call_soon_threadsafe(play_next_song.set)
if message.content.startswith('~play https:') :
url = message.content[6:]
#await app.delete_message(message)
server = message.server
ch = message.channel
links[server.id] = m_links
if message.author.voice.voice_channel == None :
await app.send_message(message.channel, embed=discord.Embed(title="⚠ Plz join in voice channel", color=0xC47EED))
else :
links[server.id].append(url)
players[server.id] = m_players
user_ch = message.author.voice.voice_channel
voice_client = app.voice_client_in(server)
if voice_client == None :
voice = await app.join_voice_channel(user_ch)
else :
voice = voice_client
player = await voice.create_ytdl_player(url,before_options="-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 2",after=toggle_next)
await players[server.id].put(player)
names[server.id] = m_names
names[server.id].append(player.title)
await app.send_message(message.channel, embed=discord.Embed(title="✅ Enqueued %s" %(player.title), color=0xC47EED))
if np_name == '' :
np_link = str(links[server.id][0])
np_name = str(names[server.id][0])
app.loop.create_task(player_task(server.id, ch))
if message.content == '~skip' :
server = message.server
ch = message.channel
try :
if app.loop.is_running() :
app.loop.stop(player_task)
app.loop.create_task(player_task(server.id, ch))
embed=discord.Embed(title="✅ skip success!", color=0xC47EED)
except :
embed=discord.Embed(title="❎ skip failed!", color=0xC47EED)
await app.send_message(message.channel, embed=embed)
我为在多个服务器上同时使用该机器人制作了一些字典变量。