Skip to content

Instantly share code, notes, and snippets.

@jaczerob
Created October 10, 2020 22:34
Show Gist options
  • Save jaczerob/d1d6fe9f418e56ae498e7ecd87618757 to your computer and use it in GitHub Desktop.
Save jaczerob/d1d6fe9f418e56ae498e7ecd87618757 to your computer and use it in GitHub Desktop.
# Methodology obtained from https://github.com/Rapptz/RoboDanny/blob/24b757f605cc8b32aebcec87d6de0043e3812f2b/bot.py
# This file demonstrates how to write an antispam Discord Bot with discord.py
from discord.ext import commands
import datetime
MESSAGES = 5
PER = 1.0
TYPE = commands.BucketType.user
class AntispamBot(commands.Bot):
def __init__(self, command_prefix, help_command=commands.DefaultHelpCommand(), description=None, **options):
super().__init__(command_prefix=command_prefix, help_command=help_command, description=description, **options)
# This creates a bucket for users that fills up whenever the user types 5 messages within 1 second.
self.antispam = commands.CooldownMapping.from_cooldown(MESSAGES, PER, TYPE)
async def on_message(self, message):
if message.author.bot:
return
# Get the user's bucket
bucket = self.antispam.get_bucket(message)
# Get the current time
current = message.created_at.replace(tzinfo=datetime.tzinfo.utc).timestamp()
# Update the bucket and check if it is full
retry_after = bucket.update_rate_limit(current)
if retry_after:
# The user typed 5 messages within 1 second
# So after this, you can do what you need to do with that
pass
await self.process_commands(message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment