問題描述
所以我在 discord.py 上制作了這個(gè)音樂不和諧機(jī)器人.這個(gè)機(jī)器人只是從我電腦上的本地 mp3 文件中播放一個(gè)播放列表.所以我有一個(gè)播放隊(duì)列的函數(shù),它是這樣的:
So I am making this music discord bot on discord.py. This bot just plays a playlist from local mp3 files on my computer. So I have a function that plays the queue and it goes like this:
def play_song(ctx, voice):
if len(queue) == 0:
print('All the songs have been played')
create_queue()
return
song_ = queue[0][len('songs/'):-16]
voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))
print(f'Now playing {song_}')
del queue[0]
我想將此函數(shù)轉(zhuǎn)換為異步函數(shù),因?yàn)槲蚁M軌蛟诖撕瘮?shù)內(nèi)部的 discord.py 中發(fā)送消息并執(zhí)行其他操作.我面臨的問題是這一行的結(jié)果:
And I want to convert this function to an async function because I want to be able to send messages and do other things in discord.py inside this function. The problem I'm facing is a result of this line:
voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: play_song(ctx, voice))
如果我讓這個(gè)函數(shù)成為一個(gè)異步函數(shù),那么我將不得不添加一個(gè) await 語句,如果我這樣做,它將是這樣的:
If I make this function an async function than I'll have to put an await statement, and If I do that it will be like this:
voice.play(discord.FFmpegPCMAudio(queue[0]), after=lambda e: await play_song(ctx, voice))
問題在于它給了我錯(cuò)誤:在異步函數(shù)之外等待"
所以我也嘗試使用 asyncio.run()
,然后在第一首歌之后它給了我一個(gè)巨大的錯(cuò)誤滾動(dòng),接下來我該怎么辦?
The problem with that is that it's giving me the error:
"await outside of async function"
So I also tried using asyncio.run()
, and then after the first song it's giving me a huge scroll of errors, What do I do next?
推薦答案
我找到了自己問題的答案.答案是使用 asyncio.Event()
我是這樣做的:
I have found an answer to my own question.
The answer is to use asyncio.Event()
I did it like this:
async def play_song(ctx, voice):
global stop_playing, pos_in_q, time_from_song
event = asyncio.Event()
event.set()
while True:
await event.wait()
event.clear()
if len(queue) == pos_in_q - 1:
await ctx.send('Party is over! use the `.arse-play` to play again.')
print('Party is over!')
create_queue()
break
if stop_playing is True:
stop_playing = False
break
song_ = queue[pos_in_q][len('songs/'):]
voice.play(discord.FFmpegPCMAudio(queue[pos_in_q]), after=lambda e: event.set())
print(f'Now playing {song_}')
time_from_song = time.time()
pos_in_q += 1
這篇關(guān)于在 discord.py 中播放音軌隊(duì)列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!