jinwoo_playzz_yt

make a discord bot

Kodari AI
KodariOct 2 at 5:53 am 1
DiscordBotCore
A Python-based Discord bot framework using discord.py. Features include command handling with prefix and slash commands, event listeners for member joins/messages, moderation tools like kick/ban/mute, role management, customizable welcome messages, and a help command system. Includes async/await architecture, error handling, and configurable settings via environment variables. Designed for easy extension with cogs for modular functionality.
  • Create a discord.py bot with !hello and !ping commands.

  • Add command cooldowns, error handling, logging, and the required KODARI_READY startup signal.

  • Add dependencies and a .env token placeholder.

Created a discord.py bot with !hello and !ping, per-user cooldowns, logging, error handling, and the KODARI_READY startup signal.

Install dependencies with pip install -r requirements.txt, set DISCORD_TOKEN in .env, then run python bot.py. Enable Message Content Intent for the bot in the Discord Developer Portal.

jinwoo_playzz_yt

ok

Kodari AI
KodariOct 2 at 5:53 am 1

You’re all set. Add your bot token to .env, enable Message Content Intent in the Discord Developer Portal, then run python bot.py.

jinwoo_playzz_yt

make a discord bot

Kodari AI
KodariOct 2 at 5:55 am 1

Your Discord bot is already set up with !hello and !ping. Add your token to .env, enable Message Content Intent in the Discord Developer Portal, then start it with:

Shell
pip install -r requirements.txt
python bot.py
jinwoo_playzz_yt

make a rules regulater bot

Kodari AI
KodariOct 2 at 5:59 am 1
  • Add server-specific rules and blocked phrases, saved to rules_data.json.

  • Add admin commands to set rules and manage the filter; !rules displays the server rules.

  • Automatically remove messages containing blocked phrases and tell the author why.

Added a rules and moderation bot:

  • !setrules <text> sets the server rules; members can view them with !rules.

  • !blockword <word or phrase> and !unblockword <word or phrase> manage the auto-moderation filter.

  • Matching messages are deleted, and the author gets a brief notice.

  • Settings are saved in rules_data.json. Admin commands require Manage Server; the bot needs Manage Messages to remove messages.

Enable Message Content Intent in the Discord Developer Portal, then run python bot.py.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 209
bot.py
import json
import logging
import os
import re
from pathlib import Path

import discord
from discord.ext import commands
from dotenv import load_dotenv


logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("kodari_bot")

load_dotenv()

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)
DATA_FILE = Path("rules_data.json")


def load_guild_data():
    try:
        with DATA_FILE.open(encoding="utf-8") as data_file:
            data = json.load(data_file)
            return data if isinstance(data, dict) else {}
    except FileNotFoundError:
        return {}
    except (json.JSONDecodeError, OSError):
        logger.exception("Could not read %s; starting with empty rules", DATA_FILE)
        return {}


guild_data = load_guild_data()


def save_guild_data():
    with DATA_FILE.open("w", encoding="utf-8") as data_file:
        json.dump(guild_data, data_file, ensure_ascii=False, indent=2)


def get_guild_data(guild_id):
    return guild_data.setdefault(str(guild_id), {"rules": "", "blocked_words": []})


@bot.event
async def on_ready():
    logger.info("Logged in as %s", bot.user)
    print("KODARI_READY", flush=True)


@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def hello(ctx):
    """Say hello."""
    await ctx.send(f"Hello, {ctx.author.mention}!")


@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def ping(ctx):
    """Show the bot's response latency."""
    latency_ms = round(bot.latency * 1000)
    await ctx.send(f"Pong! `{latency_ms} ms`")


@bot.command()
@commands.cooldown(1, 3, commands.BucketType.user)
async def rules(ctx):
    """Show this server's rules."""
    if ctx.guild is None:
        await ctx.send("Rules can only be viewed in a server.")
        return

    server_rules = get_guild_data(ctx.guild.id).get("rules", "")
    if not server_rules:
        await ctx.send("No rules have been set yet. An admin can add them with `!setrules <rules>`.")
        return

    await ctx.send(embed=discord.Embed(title=f"{ctx.guild.name} Rules", description=server_rules))


@bot.command()
@commands.guild_only()
@commands.has_guild_permissions(manage_guild=True)
async def setrules(ctx, *, text: str):
    """Set the rules shown by !rules."""
    if len(text) > 3900:
        await ctx.send("Rules must be 3,900 characters or fewer.")
        return

    get_guild_data(ctx.guild.id)["rules"] = text
    save_guild_data()
    await ctx.send("Server rules updated. Members can view them with `!rules`.")


@bot.command()
@commands.guild_only()
@commands.has_guild_permissions(manage_guild=True)
async def blockword(ctx, *, phrase: str):
    """Add a word or phrase that the bot removes from messages."""
    phrase = phrase.strip()
    if not phrase:
        await ctx.send("Provide a word or phrase to block.")
        return

    blocked_words = get_guild_data(ctx.guild.id).setdefault("blocked_words", [])
    if phrase.casefold() in (word.casefold() for word in blocked_words):
        await ctx.send("That word or phrase is already blocked.")
        return

    blocked_words.append(phrase)
    save_guild_data()
    await ctx.send(f"Added `{phrase}` to the blocked phrases. Matching messages will be removed.")


@bot.command()
@commands.guild_only()
@commands.has_guild_permissions(manage_guild=True)
async def unblockword(ctx, *, phrase: str):
    """Remove a word or phrase from the blocked list."""
    blocked_words = get_guild_data(ctx.guild.id).setdefault("blocked_words", [])
    match = next((word for word in blocked_words if word.casefold() == phrase.strip().casefold()), None)
    if match is None:
        await ctx.send("That word or phrase is not on the blocked list.")
        return

    blocked_words.remove(match)
    save_guild_data()
    await ctx.send(f"Removed `{match}` from the blocked phrases.")


@bot.event
async def on_message(message):
    if message.author.bot:
        return

    context = await bot.get_context(message)
    if context.command is not None and context.command.name in {"blockword", "unblockword"}:
        await bot.process_commands(message)
        return

    if message.guild is not None:
        blocked_words = get_guild_data(message.guild.id).get("blocked_words", [])
        matched_phrase = next(
            (
                phrase
                for phrase in blocked_words
                if re.search(rf"(?<!\w){re.escape(phrase)}(?!\w)", message.content, re.IGNORECASE)
            ),
            None,
        )
        if matched_phrase is not None:
            try:
                await message.delete()
                await message.channel.send(
                    f"{message.author.mention}, your message was removed because it contains a blocked phrase.",
                    delete_after=8,
                )
            except discord.Forbidden:
                logger.warning("Missing permission to delete a blocked message in %s", message.guild.id)
            except discord.HTTPException:
                logger.exception("Could not remove a blocked message in %s", message.guild.id)
            return

    await bot.process_commands(message)


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandNotFound):
        return

    if isinstance(error, commands.CommandOnCooldown):
        await ctx.send(f"Please wait {error.retry_after:.1f}s before using that command again.")
        return

    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send(f"Missing required argument: `{error.param.name}`.")
        return

    if isinstance(error, commands.MissingPermissions):
        await ctx.send("You need the **Manage Server** permission to use that command.")
        return

    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send("That command can only be used in a server.")
        return

    logger.error("Command error in %s: %s", ctx.command, error)
    await ctx.send("Something went wrong while running that command.")


def main():
    token = os.getenv("DISCORD_TOKEN")