我正在开发一个不和谐的机器人并试图解决这个问题。我想知道如何在非异步函数中使用 await 或,如果我可以在代码的最后一行 lambda 行中等待一个函数。
我试过用玩家变量做 asyncio.run
并且我也试过 asyncio.run_coroutine_threadsafe
但它没有用。
关于如何让它发挥作用的任何想法?
代码:
def queue_check(self, ctx):
global queue_list
global loop
global playing
if loop is True:
queue_list.append(playing)
elif loop is False:
playing = ''
if ctx.channel.last_message.content == '$skip' or '$s':
return
song = queue_list.pop(0)
player = await YTDLSource.from_url(song, loop=self.client.loop, stream=True)
ctx.voice_client.play(player, after= queue_check(self,ctx))
@commands.command(aliases=['p'])
@commands.guild_only()
async def play(self, ctx, *, url):
global queue_list
global playing
if ctx.voice_client is None:
if ctx.author.voice:
await ctx.author.voice.channel.connect()
else:
return await ctx.send("> You are not connected to a voice channel.")
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.client.loop, stream=True)
await ctx.send(f'> :musical_note: Now playing: **{player.title}** ')
playing = url
await ctx.voice_client.play(player, after=lambda e: queue_check(self,ctx))
答案 0 :(得分:2)
需要import asyncio
为了实际运行协程,asyncio 提供了三种主要机制:
示例
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
输出
started at 17:14:32
hello
world
finished at 17:14:34
详情here