首页 > 解决方案 > 如何在 discord.py 中为 dm_all 命令添加速率限制?

问题描述

我正在使用下面的代码对服务器上的每个成员进行 dm,有时机器人会在最终被禁止时获得限制。我知道这是反对 tos 但出于好奇,我想问有没有一种方法可以给机器人添加一个限制,就像它每分钟只发送 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!")

标签: pythondiscord.pydiscord.py-rewrite

解决方案


只需跟踪您向多少用户发送了 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!")

推荐阅读