bclindner / valerius

Modular Discord bot based on discordgo.
GNU General Public License v3.0
0 stars 0 forks source link

RESTCommand rate limiting #8

Open bclindner opened 5 years ago

bclindner commented 5 years ago

RESTCommand can be easily abused by spamming commands, which could lead to the bot being banned from an API it makes use of. It needs a rate limiter to prevent this.

Config design seems straightforward - a rateLimit options field with data on how many requests/sec, requests/day, requests/month, etc. allowed to that API. This may present problems in the event that there are multiple commands corresponding to one API, though, since the rate limits wouldn't be controlled separately. Not a huge priority for me, honestly.

For instance, the Jikan API, which I use for a command to pull up anime, has a maximum of 2 requests per second and 30 requests per minute. A sane rateLimit object structure for taking care of this would look like so:

"rateLimit": {
  "perSecond": 2,
  "perMinute": 30
}

To implement this, the command could internally hold a slice of timestamps.

Using the Jikan API example as before - In Run, it would add a timestamp to the slice. In Test, it would take each valid constraint in the rateLimit object and ensure there are no more than 2 timestamps with time greater than a second ago, and no more than 30 timestamps with time greater than 30 seconds ago. A goroutine should be run after each test to prune this history intelligently based on the highest rate limit constraint so it doesn't flood memory too bad.