Logan Anderson

i want a bot that does everything for my lakora state roleplay community.

Kodari AI
KodariYesterday at 3:25 pm 2
LakoraStateBot
A comprehensive Discord bot for the Lakora State roleplay community. Features include member registration and verification, character management with profiles, economy system with currency and shops, job and business systems, housing management, vehicle registration, law enforcement tools for police roleplay, court and legal systems, faction management, event scheduling, moderation commands, and a help menu. Built with discord.py using cogs for modularity, SQLite for persistent data storage, and slash commands for user-friendly interaction.

I’ll build a slash-command bot with moderation, private support tickets, announcements, and persistent roleplay profiles.

Built the Lakora community bot with roleplay profiles, dice rolls, private tickets, announcements, and moderation commands.

Add your bot token to .env, then invite it with the bot and applications.commands scopes. Ticket channels are visible to the owner and server administrators. Character profiles are stored in lakora.db.

What other Lakora-specific features would you like, such as applications, departments, or a CAD system?

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 224
bot.py
import asyncio
import logging
import os
import random
import sqlite3
from datetime import timedelta

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

load_dotenv()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("lakora")


class LakoraBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
        self.db = sqlite3.connect("lakora.db")
        self.db.execute(
            "CREATE TABLE IF NOT EXISTS characters ("
            "guild_id INTEGER NOT NULL, user_id INTEGER NOT NULL, "
            "name TEXT NOT NULL, occupation TEXT NOT NULL, bio TEXT NOT NULL, "
            "PRIMARY KEY (guild_id, user_id))"
        )
        self.db.commit()

    async def setup_hook(self):
        await self.tree.sync()

    async def close(self):
        self.db.close()
        await super().close()


bot = LakoraBot()


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


@bot.tree.error
async def command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
    if isinstance(error, app_commands.MissingPermissions):
        message = "You don't have permission to use this command."
    elif isinstance(error, app_commands.BotMissingPermissions):
        message = "I don't have the necessary permissions to do that."
    elif isinstance(error, app_commands.CommandOnCooldown):
        message = f"Please wait {error.retry_after:.1f} seconds before trying again."
    elif isinstance(error, app_commands.NoPrivateMessage):
        message = "Use this command in a server."
    else:
        logger.error("Application command failed", exc_info=(type(error), error, error.__traceback__))
        message = "Something went wrong. Check my permissions and try again."
    if interaction.response.is_done():
        await interaction.followup.send(message, ephemeral=True)
    else:
        await interaction.response.send_message(message, ephemeral=True)


@bot.tree.command(name="help", description="See Lakora's community commands")
async def help_command(interaction: discord.Interaction):
    embed = discord.Embed(title="Lakora State Roleplay", description="Community bot commands", color=discord.Color.blurple())
    embed.add_field(name="Roleplay", value="`/character set`, `/character view`, `/character delete`, `/roll`", inline=False)
    embed.add_field(name="Support", value="`/ticket open`, `/ticket close`", inline=False)
    embed.add_field(name="Staff", value="`/announce`, `/purge`, `/timeout`, `/kick`, `/ban`", inline=False)
    await interaction.response.send_message(embed=embed, ephemeral=True)


character = app_commands.Group(name="character", description="Manage your roleplay character", guild_only=True)
bot.tree.add_command(character)


@character.command(name="set", description="Create or update your character")
@app_commands.describe(name="Character name", occupation="Character's job or role", bio="A short character biography")
async def character_set(interaction: discord.Interaction, name: app_commands.Range[str, 1, 80], occupation: app_commands.Range[str, 1, 100], bio: app_commands.Range[str, 1, 1000]):
    bot.db.execute(
        "INSERT INTO characters (guild_id, user_id, name, occupation, bio) VALUES (?, ?, ?, ?, ?) "
        "ON CONFLICT(guild_id, user_id) DO UPDATE SET name=excluded.name, occupation=excluded.occupation, bio=excluded.bio",
        (interaction.guild_id, interaction.user.id, name, occupation, bio),
    )
    bot.db.commit()
    await interaction.response.send_message("Your character profile has been saved.", ephemeral=True)


@character.command(name="view", description="View a character profile")
async def character_view(interaction: discord.Interaction, member: discord.Member = None):
    member = member or interaction.user
    row = bot.db.execute("SELECT name, occupation, bio FROM characters WHERE guild_id=? AND user_id=?", (interaction.guild_id, member.id)).fetchone()
    if row is None:
        await interaction.response.send_message("That member doesn't have a character profile yet.", ephemeral=True)
        return
    embed = discord.Embed(title=row[0], description=row[2], color=discord.Color.blue())
    embed.add_field(name="Occupation", value=row[1], inline=False)
    embed.set_footer(text=f"Player: {member.display_name}")
    await interaction.response.send_message(embed=embed, allowed_mentions=discord.AllowedMentions.none())


@character.command(name="delete", description="Delete your character profile")
async def character_delete(interaction: discord.Interaction):
    cursor = bot.db.execute("DELETE FROM characters WHERE guild_id=? AND user_id=?", (interaction.guild_id, interaction.user.id))
    bot.db.commit()
    await interaction.response.send_message("Character deleted." if cursor.rowcount else "You don't have a character profile.", ephemeral=True)


@bot.tree.command(name="roll", description="Roll dice for a roleplay scene")
@app_commands.describe(dice="Number of dice", sides="Number of sides per die")
@app_commands.checks.cooldown(3, 10.0, key=lambda i: (i.guild_id, i.user.id))
async def roll(interaction: discord.Interaction, dice: app_commands.Range[int, 1, 10] = 1, sides: app_commands.Range[int, 2, 100] = 20):
    results = [random.randint(1, sides) for _ in range(dice)]
    await interaction.response.send_message(f"🎲 {interaction.user.mention} rolled {dice}d{sides}: {', '.join(map(str, results))} **(total: {sum(results)})**", allowed_mentions=discord.AllowedMentions.none())


ticket = app_commands.Group(name="ticket", description="Open and close private support tickets", guild_only=True)
bot.tree.add_command(ticket)


@ticket.command(name="open", description="Open a private support ticket")
@app_commands.checks.bot_has_permissions(manage_channels=True)
@app_commands.checks.cooldown(1, 60.0, key=lambda i: (i.guild_id, i.user.id))
async def ticket_open(interaction: discord.Interaction, reason: app_commands.Range[str, 1, 500]):
    guild = interaction.guild
    topic = f"lakora-ticket-owner:{interaction.user.id}"
    existing = discord.utils.get(guild.text_channels, topic=topic)
    if existing:
        await interaction.response.send_message(f"You already have an open ticket: {existing.mention}", ephemeral=True)
        return
    await interaction.response.defer(ephemeral=True)
    overwrites = {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        interaction.user: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True),
        guild.me: discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True, manage_channels=True),
    }
    channel = await guild.create_text_channel(f"ticket-{interaction.user.id}", topic=topic, overwrites=overwrites, reason=f"Support ticket by {interaction.user}")
    embed = discord.Embed(title="Support ticket", description=reason, color=discord.Color.green())
    embed.set_footer(text="A server administrator can help you here. Use /ticket close when finished.")
    await channel.send(content=f"Ticket opened by {interaction.user.mention}.", embed=embed, allowed_mentions=discord.AllowedMentions(users=[interaction.user]))
    await interaction.followup.send(f"Your ticket is ready: {channel.mention}", ephemeral=True)


@ticket.command(name="close", description="Close the current support ticket")
@app_commands.checks.bot_has_permissions(manage_channels=True)
async def ticket_close(interaction: discord.Interaction):
    channel = interaction.channel
    topic = getattr(channel, "topic", None) or ""
    if not topic.startswith("lakora-ticket-owner:"):
        await interaction.response.send_message("This isn't a Lakora support ticket.", ephemeral=True)
        return
    if topic != f"lakora-ticket-owner:{interaction.user.id}" and not interaction.user.guild_permissions.manage_channels:
        await interaction.response.send_message("Only the ticket owner or staff with Manage Channels can close this ticket.", ephemeral=True)
        return
    await interaction.response.send_message("Closing this ticket in 3 seconds.")
    await asyncio.sleep(3)
    await channel.delete(reason=f"Ticket closed by {interaction.user}")


@bot.tree.command(name="announce", description="Send a staff announcement")
@app_commands.guild_only()
@app_commands.checks.has_permissions(manage_guild=True)
async def announce(interaction: discord.Interaction, channel: discord.TextChannel, title: app_commands.Range[str, 1, 256], message: app_commands.Range[str, 1, 4000]):
    embed = discord.Embed(title=title, description=message, color=discord.Color.gold())
    embed.set_footer(text=f"Announcement by {interaction.user.display_name}")
    await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
    await interaction.response.send_message(f"Announcement sent to {channel.mention}.", ephemeral=True)


@bot.tree.command(name="purge", description="Delete recent messages in this channel")
@app_commands.guild_only()
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True, read_message_history=True)
async def purge(interaction: discord.Interaction, amount: app_commands.Range[int, 1, 100]):
    await interaction.response.defer(ephemeral=True)
    deleted = await interaction.channel.purge(limit=amount)
    await interaction.followup.send(f"Deleted {len(deleted)} messages.", ephemeral=True)


@bot.tree.command(name="timeout", description="Temporarily timeout a member")
@app_commands.guild_only()
@app_commands.checks.has_permissions(moderate_members=True)
@app_commands.checks.bot_has_permissions(moderate_members=True)
async def timeout(interaction: discord.Interaction, member: discord.Member, minutes: app_commands.Range[int, 1, 40320], reason: app_commands.Range[str, 1, 500] = "No reason provided"):
    if member == interaction.user or (interaction.user != interaction.guild.owner and member.top_role >= interaction.user.top_role):
        await interaction.response.send_message("You cannot moderate this member.", ephemeral=True)
        return
    await member.timeout(timedelta(minutes=minutes), reason=f"{interaction.user}: {reason}")
    await interaction.response.send_message(f"Timed out {member} for {minutes} minutes.", ephemeral=True)


@bot.tree.command(name="kick", description="Kick a member from the server")
@app_commands.guild_only()
@app_commands.checks.has_permissions(kick_members=True)
@app_commands.checks.bot_has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: app_commands.Range[str, 1, 500] = "No reason provided"):
    if member == interaction.user or (interaction.user != interaction.guild.owner and member.top_role >= interaction.user.top_role):
        await interaction.response.send_message("You cannot moderate this member.", ephemeral=True)