如何在discord.py中将速率限制添加到dm_all命令?

时间:2020-08-17 12:47:22

标签: python discord.py discord.py-rewrite

我正在使用下面的代码对服务器上的每个成员进行dm设置,有时bot最终被禁止使用。我知道这是反对的,但是出于好奇,我想问一种办法,我可以给机器人增加限制,例如它每分钟仅发送30个dms并持续下去,直到它向我的服务器上的每个用户发送dms。

这是我正在使用的代码:

@bot.command(pass_context = True)
@commands.has_permissions(manage_messages=True)
async def dm_all(ctx, *, args=None):
    
    if args != None:
        members = ctx.guild.members
        for member in members:
            try:
                await member.send(args)
                await ctx.channel.send(" sent to: " + member.name)

            except:
                await ctx.channel.send("Couldn't send to: " + member.name)

    else:
        await ctx.channel.send("Please provide a message to send!")

1 个答案:

答案 0 :(得分:0)

仅跟踪向您发送了dms的用户数。然后在30 dms之后等待60秒,可以用来避免速率限制。

代码:

@bot.command(pass_context = True)
@commands.has_permissions(manage_messages=True)
async def dm_all(ctx, *, args=None):
    sended_dms = 0
    rate_limit_for_dms = 30
    time_to_wait_to_avoid_rate_limit = 60

    if args != None:
        members = ctx.guild.members
        for member in members:
            try:
                await member.send(args)
                await ctx.channel.send(" sent to: " + member.name)

            except:
                await ctx.channel.send("Couldn't send to: " + member.name)
            sended_dms += 1
            if sended_dms % rate_limit_for_dms == 0: # used to check if 30 dms are sent
                asyncio.sleep(time_to_wait_to_avoid_rate_limit) # wait till we can continue

    else:
        await ctx.channel.send("Please provide a message to send!")