discord.py 更快地向多个频道发送消息

discord.py send Message faster to multiple Channels

我正准备制作一个全球聊天机器人,它工作得很好,但由于它在 70 个服务器中,他真的很难发送消息。目前我发送消息的代码如下所示:

async def sendallchannel(self, embed):
for channel in fetchedchannel:
    try:
        await channel.send(embed = embed)
    except:
        pass

正如我刚才所说,将消息发送到每个服务器大约需要 1 分钟。有什么方法可以更快地发送消息吗?

变量 fetchedchannel 是已经获取的每个频道的列表,因此 Bot 在发送消息时不需要一个一个地获取每个频道

据我所知,这是最快的方法:

@bot.command()
async def sendToAllChannels(ctx, *message):
    message = ' '.join(message)
    for guild in bot.guilds:
        for channel in guild.channels:
            await channel.send(message)

请注意,您使用的是 nested for 循环,这显然会花费大量时间,尤其是在外循环(遍历 bot.guilds 的循环)时被执行了很多次(你说的是70,对吧?)


由于您只想向 TextChannel 发送消息,您可以添加此检查:

if str(channel.type) == 'text':

编辑:由于您已经有了所有频道的列表 (fetchedchannel),假设此列表包含 bot 可以看到的所有频道,我将以这种方式创建一个新列表。 ..

fetchedTextChannels = [channel for channel in fetchedchannel if str(channel.type) == 'text']

...为了避免 try/except 块,一旦您知道所有通道都是 'text'.

类型

然后,为了让消息不互相等待,你应该看到@Loic的解决方案,建议你使用asynchronous协程,并且会让一切更快.

这应该快得多,因为所有协程将同时 运行 :

async def sendallchannel(self, embed):
  coroutines = [channel.send(embed=embed) for channel in fetchedchannel]   
  await asyncio.gather(*coroutines)

我觉得这样比较快:

def _send_in_all_channels(ctx, embed):  # outside cog
  channels = ctx.guild.text_channels  # type: list[TextChannel]

  coroutines = (channel.send(embed=embed) for channel in channels)
  # types.Genetrator[typing.Awaitable[discord.Message], None, None]

  return asyncio.gather(*coroutines)  # type: typing.Awaitable

# usage in cog
@commands.command('big-send')
async def big_send(self, ctx, message: str):
  await _send_in_all_channels(ctx, discord.Embed(discerption=message))
  await ctx.send('done')