需要多条等待消息不和.py

2024-09-27 07:34:31 发布

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

基本上我在做一个测试,我想能够搜索答案,并确定哪条消息只包含艺术家,哪条消息只包含歌曲名称,以及哪条消息同时说明了这两个问题。我做了3个check函数来显示这一点,但是我希望所有3个wait_for_消息语句并排运行。有什么办法补救吗?在

await client.say("What is the song name and artist?")
def check1(msg):
    return name in msg.content.upper() and artist not in msg.content.upper()
def check2(msg):
    return artist in msg.content.upper() and name not in msg.content.upper()
def check3(msg):
    return name in msg.content.upper() and artist in msg.content.upper()
msg1 = await client.wait_for_message(timeout=10, check=check1)
msg2 = await client.wait_for_message(timeout=10, check=check2)
msg3 = await client.wait_for_message(timeout=20, check=check3)
if msg3 is not None:
   await client.say("@{} got both of them right! It was indeed {} by {}".format(msg3.author, toString(name), 
                                                                                     toString(artist)))
elif msg1 is not None and msg2 is not None:
        await client.say("@{} got the song name and @{} got the artist name! It was indeed {} by {}".format(msg1.author, 
                                                                           msg2.author, toString(name), toString(artist)))
elif msg1 is not None and msg2 is None:
        await client.say("@{} got the song name but no one got the artist! It was {} by {}".format(msg1.author,
                                                                                       toString(name), toString(artist)))
elif msg1 is None and msg2 is not None:
        await client.say("@{} got the artist name but no one got the song name! It was {} by {}".format(msg2.author,
                                                                                       toString(name), toString(artist)))
elif msg1 is None and msg2 is None and msg3 is None:
        await client.say("No one got it! It was {} by {}! Better luck next time".format(toString(name), toString(artist)))

Tags: andthenameclientnoneartistisnot
1条回答
网友
1楼 · 发布于 2024-09-27 07:34:31

您要查找的代码是^{}。这使您可以同时运行多个协程,并等待所有方法返回。在

gather返回的列表是按输入的顺序,而不是按任务完成的顺序。在

ret = await asyncio.gather(
    client.wait_for_message(timeout=10, check=check1),
    client.wait_for_message(timeout=10, check=check2),
    client.wait_for_message(timeout=10, check=check3)
)

msg1, msg2, msg3 = *ret
# msg1 has the name
# msg2 has the artist
# msg3 has both

自从重写版本不和.py使client.wait_for抛出错误而不是返回None,您可以改为这样做。在

^{pr2}$

相关问题 更多 >

    热门问题