1
1
1Nyxoy12021-12-24 12:48:48
Python
1Nyxoy1, 2021-12-24 12:48:48

How to send a message to all channels at once?

you need the bot to instantly send messages to all channels at once

discord library

@client.command()
async def test(ctx):
    await ctx.author.send(f'test')
    for channel in ctx.guild.text_channels:
        try:
            await channel.send('test')
        except:
            print(f'[ ERROR ] Не отправил')


I wrote this code but it is too slow, can I speed it up, optimize it somehow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-12-24
@1Nyxoy1

Something like this. No guarantees that discord will not send your bot far and wide for spam.

@client.command()
async def test(ctx):
    await ctx.author.send(f'test')
    # сохраняем набор и порядок каналов на случай, если он поменяется в процессе отправки.
    channels = list(ctx.guild.text_channels)
    # формируем пачку корутин, выполняющих отправку
    send_coroutines = [channel.send('test') for channel in channels]
    # планируем одновременное выполнение этих корутин и ждём завершения. 
    # Исключения будут возвращены наравне с результатами, а не выброшены.
    results = await asyncio.gather(*send_coroutines, return_exceptions=True)
    # анализируем results на предмет ошибок. 
    # Успешная отправка вернёт объект сообщения, неудачная вернет (а не выбросит!) объект исключения.
    failed = [ (ch.name, str(res)) for res, ch in zip(results, channels) if isinstance(res, (Exception, asyncio.CancelledError)) ]
    if failed: # были ошибки?
        await ctx.author.send('Failed to send to the following channels:\n' + '\n'.join(f'- {ch}: {msg}' for ch, msg in failed))
    else: # ошибок не было
        await ctx.author.send('Message has been spammed successfully.')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question