[英]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.