简体   繁体   中英

How to return a value with asyncio.gather?

I want to Send a Message to multiple Servers at once. with the help of Stackoverflow I came up with a solution like this here. But I don't know how to get this code Working.

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)

The variable fetchedchannel is a list with all the Channels the message should be sent to.

The output I expect is something like [541654984561689, 848594981654894, 549846898948489, 84869489785156489] What I get is []

To schedule an initial coroutine from your script, you have to use asyncio.run. However, your code will still send the messages sequentially as that is just done in that for loop one by one. Also gather is not needed as you are only awaiting a single coroutine. If that is what you want, you can just do res = await sendmessages(embed).

If you actually want to have those sends to run concurrently, you might want to change your code roughly like

import asyncio

async def main():
    return await asyncio.gather(*(channel.send(embed = embed) for channel in fetchedchannel))

result = asyncio.run(main())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM