'How to add Rate limit to dm_all command in discord.py?
I am using the code below to dm every member on the server and sometimes bot get rate limted at ultimately banned. I know this is against tos but out of curiosity I am asking is there a way I can add a limit to the bot like it send only 30 dms per minute and continues it until it send dms to every user on my server.
Here is the code I am using:
@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!")
Solution 1:[1]
Simply tracking how many users you sended dms to. And then wait 60 seconds after 30 dms, can be used to avoid being rate limited.
Code:
@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!")
Solution 2:[2]
@client.event
async def on_guild_join(guild):
sent_dms = 0
#Send Dm here
sent_dms += 1
if sent_dms == 30:
asyncio.sleep(60)
sent_dms = 0
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Deru |
Solution 2 | EpicGamer123 |