|
| 1 | +# standard imports |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +# lib imports |
| 6 | +import discord |
| 7 | +from discord.ext import commands |
| 8 | + |
| 9 | +# Get logger for this module |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +class AutoBanCog(discord.Cog): |
| 14 | + """ |
| 15 | + Discord cog that automatically bans any user who posts in the configured autoban channel. |
| 16 | + """ |
| 17 | + |
| 18 | + def __init__(self, bot): |
| 19 | + self.bot = bot |
| 20 | + |
| 21 | + @commands.Cog.listener() |
| 22 | + async def on_message(self, message: discord.Message): |
| 23 | + """ |
| 24 | + Listen for messages and ban the author if the message is in the autoban channel. |
| 25 | +
|
| 26 | + Any message sent to the channel defined by ``DISCORD_AUTOBAN_CHANNEL_ID`` will result in |
| 27 | + the author being banned from the guild. All messages from the user within the past 7 days |
| 28 | + are also deleted. Bot messages are ignored. |
| 29 | +
|
| 30 | + Parameters |
| 31 | + ---------- |
| 32 | + message : discord.Message |
| 33 | + The message object that triggered this event. |
| 34 | + """ |
| 35 | + if message.author.bot: |
| 36 | + return |
| 37 | + |
| 38 | + autoban_channel_id = os.getenv('DISCORD_AUTOBAN_CHANNEL_ID') |
| 39 | + if not autoban_channel_id: |
| 40 | + return |
| 41 | + |
| 42 | + if message.channel.id != int(autoban_channel_id): |
| 43 | + return |
| 44 | + |
| 45 | + guild = message.guild |
| 46 | + if not guild: |
| 47 | + return |
| 48 | + |
| 49 | + try: |
| 50 | + await guild.ban( |
| 51 | + user=message.author, |
| 52 | + reason="Automatic ban: posted in restricted channel.", |
| 53 | + delete_message_seconds=604800, # Delete messages from the past 7 days |
| 54 | + ) |
| 55 | + logger.warning( |
| 56 | + "Auto-banned user %s (%s) for posting in channel %s (%s).", |
| 57 | + message.author, |
| 58 | + message.author.id, |
| 59 | + message.channel.name, |
| 60 | + message.channel.id, |
| 61 | + ) |
| 62 | + except discord.Forbidden: |
| 63 | + logger.error( |
| 64 | + "Missing permissions to ban user %s (%s) in guild %s (%s).", |
| 65 | + message.author, |
| 66 | + message.author.id, |
| 67 | + guild.name, |
| 68 | + guild.id, |
| 69 | + ) |
| 70 | + except discord.HTTPException as e: |
| 71 | + logger.error( |
| 72 | + "HTTP error while banning user %s (%s): %s", |
| 73 | + message.author, |
| 74 | + message.author.id, |
| 75 | + e, |
| 76 | + exc_info=True, |
| 77 | + ) |
| 78 | + |
| 79 | + |
| 80 | +def setup(bot: discord.Bot): |
| 81 | + bot.add_cog(AutoBanCog(bot=bot)) |
0 commit comments