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



我即将制作一个全球聊天机器人,它运行得很好,但由于它在70台服务器中,他真的很难发送消息。目前我发送消息的代码如下:

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

正如我刚才所说,大约需要1分钟才能将消息发送到每个服务器。有没有办法更快地发送消息?

变量fetchedchannel是已经提取的每个通道的列表,因此Bot在想要发送消息时不需要逐个提取每个通道

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

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

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

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

请注意,以这种方式使用nestedfor循环,这显然需要大量时间,特别是当外循环(在bot.guilds上迭代的循环(被执行多次时(您说的是70,对吗?(


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

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

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

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

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


然后,为了使消息不相互等待,您应该查看@Loic的解决方案,该解决方案建议您使用async异步协程,这将使一切变得更快。

我认为这是更快的:

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')

最新更新