0

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

EntchenEric
  • 361
  • 2
  • 17
  • See also https://stackoverflow.com/questions/49005651/how-does-asyncio-actually-work for the underlying theory. There are multiple issues here and it would be best to work through an asyncio tutorial first - it's more or less a prerequisite for properly wrapping one's head around an async API like Discord's. – Karl Knechtel Jan 30 '22 at 10:55

1 Answers1

0

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())
Simon Hawe
  • 3,968
  • 6
  • 14