[英]How to return a value with asyncio.gather?
我想一次向多個服務器發送消息。 在 Stackoverflow 的幫助下,我在這里想出了一個這樣的解決方案。 但我不知道如何讓這段代碼工作。
async def sendmessages(embed):
ids = []
for channel in fetchedchannel:
m = await channel.send(embed = embed)
ids.append(m.id)
return ids
ids = []
try:
ids = await asyncio.gather(sendmessage(embed))
except:
pass
print(ids)
變量 fetchedchannel 是一個列表,其中包含消息應發送到的所有通道。
我期望的 output 類似於[541654984561689, 848594981654894, 549846898948489, 84869489785156489]
我得到的是[]
要從腳本中安排初始協程,您必須使用 asyncio.run。 但是,您的代碼仍將按順序發送消息,因為這只是在 for 循環中一一完成。 也不需要gather
,因為您只等待一個協程。 如果這是你想要的,你可以做 res = await sendmessages(embed)。
如果你真的想讓這些發送同時運行,你可能想大致改變你的代碼
import asyncio
async def main():
return await asyncio.gather(*(channel.send(embed = embed) for channel in fetchedchannel))
result = asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.