Custom discord bot – How to avoid exceeding Discord API rate limit?

Question:

I’m hosting a bot on a language learning server. So far the bot has two functions, which are:

  1. Scan messages in #welcome channel and delete any messages that contains any links
  2. Delete Visitor role from members when they get one of the five fluency role we have (Beginner Intermediate, Advanced, Fluent, and Native), and give members the Visitor role back when their fluency role. The fluency role is dispensed through Dyno role button function.

I managed to stitch together a code to run both functions. I got the message scan thing running okay (been ran overnight, no problem). Earlier today, I got the visitor auto role removal thing to work. Though a few hours later I got rate limited by Discord.

I’m not an avid programmer. I think there’s a lot of inefficiencies in my code that could have caused this. Would really appreciate if you guys can point out what I did wrong or if there’s a way to avoid triggering the rate limit. Thanks in advance!

P.S.: The code is running and hosted in repl.it with the keep-alive combo. Could this be part of the problem? Do I need a dedicated hosting service for the functions I’m running?

Here’s the code I used:

import discord
import os
import datetime
from keep_alive import keep_alive

intents = discord.Intents().all()
client = discord.Client(intents=intents)
#ct = datetime.datetime.now(tz=pytz.timezone('Asia/Hong_Kong'))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('$hello'):
    await message.channel.send('Hello')

  ###########link remover###########
  channelID = 840910671084xxxxxx
  channelname = 'welcome'
  msg_content = message.content.lower()
  channelmsg = client.get_channel
  links = ['http', 'https','.com']

  #channel lock
  if channelname == str(message.channel):
    exclusion = [936293188149xxxxxx, 934739311180xxxxxx, 943017611439xxxxxx]
    #link detection
    if any(word in msg_content for word in links):
      #exclude admins
      if any(rolex in [y.id for y in message.author.roles] for rolex in exclusion):
        print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), "Links detected by Admin/Staff. Ignored.")
        return
      else:
        print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), "Links detected by members. Deleted.")
        await message.delete()
        channel = client.get_channel(channelID)
        await channel.send("Sorry! To prevent spam & scam messages, no links are allowed in <#840910671084xxxxxx>.")


#fluency role pick
@client.event
async def on_member_update(before, after):
  roles_id = [932635921516xxxxxx, 932636823933xxxxxx, 932636866103xxxxxx, 932636911468xxxxxx, 932637000194xxxxxx, 935172897092xxxxxx]
  role_visitor = discord.utils.get(after.guild.roles, id=939440361896xxxxxx)
  if any(roles in [y.id for y in after.roles] for roles in roles_id):
    if after.roles is not None:
      return
    elif(939440361896xxxxxx not in [y.id for y in after.roles]):
      return
    print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), "Changes to role happened. Visitor role removed.")
    await after.remove_roles(role_visitor)
  else:
    if (939440361896xxxxxx in [y.id for y in after.roles]):
      return
    print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), "Changes to role happened. Visitor role added.")
    await after.add_roles(role_visitor)
keep_alive()
client.run(os.environ['TOKEN'])
Asked By: Andi Reyhan

||

Answers:

I was always fustrated when my bot always gets temporarily banned by discord’s api for exceeding rate limits thanks to my friends spamming the commands over and over again. But there is no way to prevent the problem on replit. But it can be fixed. Go to shell and type kill 1. And then restart your bot. Everything will be reset and you will be good to go. By the way the code has no problem

Answered By: BoomerangTheBEst

The reason you are being rate limited so frequently is because of the way Replit works. Replit hosts several users on the same IP address. Because of this, that same IP address calls on discord multiple times in a single session, and that IP address becomes rate-limited.

You can temporarily fix this by typing !kill in the shell terminal. This will assign your bot a new IP. However, because this only assigns your bot a new IP, it’ll get rate limited as more bots use the same IP address.

The only real way to fix this is to get a permanent and unique IP address; either host it yourself or find a third-party server. I suggest sparked host.

I hope this answer isn’t too late.

Answered By: Mula
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.