jov8486

makes a discord bot that checks for the n word, homophobic stuff, bad slurs in both text and voice channels, name it strawgensx

Kodari AI
KodariSep 9 at 4:07 am 1
StrawGensX
StrawGensX is a Discord moderation bot that monitors both text and voice channels for offensive language, including racial slurs, homophobic remarks, and other inappropriate content. It scans messages in real-time, transcribes voice messages using speech-to-text technology, and automatically flags or removes violating content. The bot provides configurable word lists, customizable punishment actions like warnings or mutes, and detailed moderation logs for server administrators. It ensures a safe community environment by actively filtering harmful speech across all communication forms.

Created strawgensx, a Discord moderation bot with:

  • Text moderation for profanity, homophobic abuse, and common hate slurs

  • Voice-channel moderation using speech transcription

  • Automatic violating-message deletion

  • Moderation logs through MOD_LOG_CHANNEL_ID

  • Three violations within 60 seconds → 10-minute timeout

  • Commands:

    • !join

    • !leave

    • !status

  • .env token configuration

  • Dependency list and setup documentation

Files created:

  • bot.py

  • requirements.txt

  • .env.example

  • .gitignore

  • README.md

Kodari can make mistakes. Review important code before using.
Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 398
bot.py
import asyncio
import io
import logging
import os
import re
import unicodedata
from collections import defaultdict, deque
from datetime import timedelta
from typing import Optional

import discord
import speech_recognition as sr
from discord.ext import commands, voice_recv
from dotenv import load_dotenv


load_dotenv()

logging.basicConfig(
    level=os.getenv("LOG_LEVEL", "INFO").upper(),
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("strawgensx")


def configured_channel_id() -> Optional[int]:
    value = os.getenv("MOD_LOG_CHANNEL_ID", "").strip()
    return int(value) if value.isdigit() and int(value) > 0 else None


TERM_GROUPS = {
    "profanity": {
        "fuck", "fucker", "fucking", "shit", "shitty", "bitch", "bitches",
        "asshole", "bullshit", "cunt", "dickhead", "motherfucker",
    },
    "homophobic language": {
        "faggot", "faggots", "fag", "dyke", "queer", "homo",
    },
    "hate slur": {
        "nigger", "nigga", "kike", "chink", "spic", "spick", "wetback",
        "gook", "coon", "tranny", "retard", "retarded",
    },
}

LEET_TRANSLATION = str.maketrans({
    "0": "o",
    "1": "i",
    "3": "e",
    "4": "a",
    "5": "s",
    "7": "t",
    "@": "a",
    "$": "s",
})


def normalize_text(text: str) -> str:
    text = unicodedata.normalize("NFKC", text).lower().translate(LEET_TRANSLATION)
    text = re.sub(r"[\u200b-\u200f\u202a-\u202e]", "", text)
    return re.sub(r"[^a-z0-9\s]", " ", text)


def find_violation(text: str) -> Optional[tuple[str, str]]:
    normalized = normalize_text(text)
    compact = normalized.replace(" ", "")
    for category, terms in TERM_GROUPS.items():
        for term in terms:
            if re.search(rf"(?<![a-z0-9]){re.escape(term)}(?![a-z0-9])", normalized):
                return category, term
            if len(term) >= 4 and term in compact:
                return category, term
    return None


class VoiceModerationSink(voice_recv.AudioSink):
    """Collect short PCM windows and send them to the transcription worker."""

    def __init__(self, bot: "StrawgensX", guild_id: int):
        super().__init__()
        self.bot = bot
        self.guild_id = guild_id
        self.buffers: defaultdict[int, bytearray] = defaultdict(bytearray)
        self.window_size = 48_000 * 2 * 2 * 5

    def wants_opus(self) -> bool:
        return False

    def write(self, user: Optional[discord.Member], data: voice_recv.VoiceData) -> None:
        if user is None or user.bot or not data.pcm:
            return

        buffer = self.buffers[user.id]
        buffer.extend(data.pcm)
        while len(buffer) >= self.window_size:
            pcm = bytes(buffer[:self.window_size])
            del buffer[:self.window_size]
            try:
                future = asyncio.run_coroutine_threadsafe(
                    self.bot.transcribe_voice(self.guild_id, user, pcm),
                    self.bot.loop,
                )
                future.add_done_callback(self._report_worker_error)
            except RuntimeError:
                return

    @staticmethod
    def _report_worker_error(future: "asyncio.Future[None]") -> None:
        try:
            future.result()
        except asyncio.CancelledError:
            pass
        except Exception:
            logger.exception("Voice transcription worker failed")

    def cleanup(self) -> None:
        self.buffers.clear()


class StrawgensX(commands.Bot):
    def __init__(self) -> None:
        intents = discord.Intents.default()
        intents.message_content = True
        intents.voice_states = True
        super().__init__(command_prefix="!", intents=intents, case_insensitive=True)
        self.log_channel_id = configured_channel_id()
        self.recent_violations: defaultdict[tuple[int, int], deque[float]] = defaultdict(deque)
        self.transcription_slots = asyncio.Semaphore(2)

    async def on_ready(self) -> None:
        logger.info("Logged in as %s (%s)", self.user, self.user.id if self.user else "unknown")
        await self.change_presence(activity=discord.Game(name="protecting the community"))

    async def transcribe_voice(self, guild_id: int, member: discord.Member, pcm: bytes) -> None:
        async with self.transcription_slots:
            try:
                transcript = await asyncio.to_thread(self._recognize_pcm, pcm)
            except sr.UnknownValueError:
                return
            except sr.RequestError as error:
                logger.warning("Speech recognition request failed: %s", error)
                return

        violation = find_violation(transcript)
        if violation is None:
            return

        guild = self.get_guild(guild_id)
        if guild is not None:
            await self.handle_violation(
                guild,
                member,
                violation,
                source="voice",
                location="voice channel",
            )

    @staticmethod
    def _recognize_pcm(pcm: bytes) -> str:
        recognizer = sr.Recognizer()
        audio = sr.AudioData(pcm, sample_rate=48_000, sample_width=2)
        return recognizer.recognize_google(audio, language="en-US")

    async def handle_violation(
        self,
        guild: discord.Guild,
        member: discord.Member,
        violation: tuple[str, str],
        *,
        source: str,
        location: str,
    ) -> None:
        category, _matched_term = violation
        key = (guild.id, member.id)
        now = asyncio.get_running_loop().time()
        history = self.recent_violations[key]
        history.append(now)
        while history and now - history[0] > 60:
            history.popleft()

        action = "warning logged"
        if len(history) >= 3:
            try:
                await member.timeout(
                    timedelta(minutes=10),
                    reason=f"Repeated {category} detected in {source}",
                )
                action = "10-minute timeout applied"
                history.clear()
            except (discord.Forbidden, discord.HTTPException):
                action = "timeout could not be applied"

        await self.send_mod_log(guild, member, category, source, location, action)

    async def send_mod_log(
        self,
        guild: discord.Guild,
        member: discord.Member,
        category: str,
        source: str,
        location: str,