[英]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在發送消息時不需要逐個獲取每個頻道
這應該會快得多,因為所有協程都將同時運行:
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)
請注意,這種方式您使用的是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的解決方案,它建議您使用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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.