Files
.
.gitignore
bot.py
README.md
requirements.txt
Code
5 853
bot.py
import logging
import os
import re
from datetime import datetime, timezone
import aiosqlite
import discord
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("faction_bot")
DATABASE_PATH = "bot.db"
DEFAULT_PREFIX = "!"
database: aiosqlite.Connection | None = None
intents = discord.Intents.default()
intents.message_content = True
async def initialize_database() -> None:
global database
database = await aiosqlite.connect(DATABASE_PATH)
await database.executescript(
"""
CREATE TABLE IF NOT EXISTS guild_config (
guild_id INTEGER PRIMARY KEY,
prefix TEXT NOT NULL DEFAULT '!',
log_channel_id INTEGER
);
CREATE TABLE IF NOT EXISTS officer_roles (
guild_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (guild_id, role_id)
);
CREATE TABLE IF NOT EXISTS rank_roles (
guild_id INTEGER NOT NULL,
role_id INTEGER NOT NULL,
PRIMARY KEY (guild_id, role_id)
);
CREATE TABLE IF NOT EXISTS points (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
balance INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (guild_id, user_id)
);
CREATE TABLE IF NOT EXISTS action_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
action TEXT NOT NULL,
target_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
reason TEXT NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL
);
"""
)
await database.commit()
async def current_prefix(bot: commands.Bot, message: discord.Message) -> str:
if message.guild is None or database is None:
return DEFAULT_PREFIX
cursor = await database.execute(
"SELECT prefix FROM guild_config WHERE guild_id = ?", (message.guild.id,)
)
row = await cursor.fetchone()
await cursor.close()
return row[0] if row else DEFAULT_PREFIX
bot = commands.Bot(command_prefix=current_prefix, intents=intents)
@bot.event
async def setup_hook() -> None:
await initialize_database()
await bot.tree.sync()
@bot.event
async def on_ready() -> None:
logger.info("Bot ready as %s", bot.user)
print("KODARI_READY", flush=True)
async def fetch_prefix(guild_id: int) -> str:
cursor = await database.execute(
"SELECT prefix FROM guild_config WHERE guild_id = ?", (guild_id,)
)
row = await cursor.fetchone()
await cursor.close()
return row[0] if row else DEFAULT_PREFIX
async def require_officer(ctx: commands.Context) -> bool:
if ctx.guild is None or not isinstance(ctx.author, discord.Member):
return False
if ctx.author.guild_permissions.administrator:
return True
cursor = await database.execute(
"SELECT role_id FROM officer_roles WHERE guild_id = ?", (ctx.guild.id,)
)
rows = await cursor.fetchall()
await cursor.close()
officer_ids = {row[0] for row in rows}
return any(role.id in officer_ids for role in ctx.author.roles)
def rank_name_from_role(role: discord.Role) -> str:
return role.name
async def registered_rank_roles(guild: discord.Guild) -> list[discord.Role]:
cursor = await database.execute(
"SELECT role_id FROM rank_roles WHERE guild_id = ?", (guild.id,)
)
rows = await cursor.fetchall()
await cursor.close()
return [role for row in rows if (role := guild.get_role(row[0])) is not None]
async def member_rank_status(member: discord.Member) -> str:
ranks = await registered_rank_roles(member.guild)
current = [role.name for role in ranks if role in member.roles]
return ", ".join(current) if current else "Unranked"
def formatted_nickname(member: discord.Member, tag: str) -> str:
base_name = re.sub(r"^\[[^\]]+\]\s*", "", member.display_name).strip()
if not base_name:
base_name = member.name
clean_tag = tag.strip()
if not (clean_tag.startswith("[") and clean_tag.endswith("]")):
clean_tag = f"[{clean_tag.strip('[] ')}]"
return f"{clean_tag} {base_name}"[:32]
def action_embed(
title: str,
color: discord.Color,
target: discord.Member,
actor: discord.Member,
reason: str,
status_label: str,
status: str,
) -> discord.Embed:
embed = discord.Embed(title=title, color=color, timestamp=datetime.now(timezone.utc))
embed.add_field(
name="Target",
value=f"{target.mention} ({target} · `{target.id}`)",
inline=False,
)
embed.add_field(name="Acting Officer", value=f"{actor.mention} ({actor})", inline=True)
embed.add_field(name=status_label, value=status, inline=True)
embed.add_field(name="Reason", value=reason, inline=False)
return embed
async def record_and_log(
guild: discord.Guild,
action: str,
target: discord.Member,
actor: discord.Member,
reason: str,
status: str,
embed: discord.Embed,
) -> None:
await database.execute(
"""INSERT INTO action_log
(guild_id, action, target_id, actor_id, reason, status, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)""",
(
guild.id,
action,
target.id,
actor.id,
reason,
status,
datetime.now(timezone.utc).isoformat(),
),
)
await database.commit()
cursor = await database.execute(
"SELECT log_channel_id FROM guild_config WHERE guild_id = ?", (guild.id,)
)
row = await cursor.fetchone()
await cursor.close()
if row and row[0]:
channel = guild.get_channel(row[0])
if channel is not None and hasattr(channel, "send"):
try: