Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 683
bot.py
import logging
import os
import random
import re
import time
from datetime import datetime, timedelta, timezone
import aiosqlite
import discord
from discord.ext import commands, tasks
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",
)
log = logging.getLogger("kodari-bot")
PREFIX = os.getenv("BOT_PREFIX", "!")
TOKEN = os.getenv("DISCORD_TOKEN")
DATABASE_PATH = os.getenv("DATABASE_PATH", "bot.sqlite3")
class Database:
def __init__(self, path: str):
self.path = path
self.connection: aiosqlite.Connection | None = None
async def connect(self) -> None:
self.connection = await aiosqlite.connect(self.path)
self.connection.row_factory = aiosqlite.Row
await self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL,
remind_at INTEGER NOT NULL,
message TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS warnings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
moderator_id INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS afk (
user_id INTEGER NOT NULL,
guild_id INTEGER NOT NULL,
reason TEXT NOT NULL,
PRIMARY KEY (user_id, guild_id)
);
CREATE TABLE IF NOT EXISTS guild_settings (
guild_id INTEGER PRIMARY KEY,
verification_role_id INTEGER
);
"""
)
await self.connection.commit()
async def execute(self, query: str, parameters: tuple = ()) -> int:
if self.connection is None:
raise RuntimeError("Database is not connected")
cursor = await self.connection.execute(query, parameters)
await self.connection.commit()
return cursor.lastrowid
async def fetchone(self, query: str, parameters: tuple = ()) -> aiosqlite.Row | None:
if self.connection is None:
raise RuntimeError("Database is not connected")
cursor = await self.connection.execute(query, parameters)
return await cursor.fetchone()
async def fetchall(self, query: str, parameters: tuple = ()) -> list[aiosqlite.Row]:
if self.connection is None:
raise RuntimeError("Database is not connected")
cursor = await self.connection.execute(query, parameters)
return await cursor.fetchall()
async def close(self) -> None:
if self.connection is not None:
await self.connection.close()
self.connection = None
def parse_duration(value: str, maximum_seconds: int = 28 * 24 * 60 * 60) -> int:
match = re.fullmatch(r"\s*(\d+)\s*(s|m|h|d|w)\s*", value.lower())
if not match:
raise ValueError("Use a duration such as `10m`, `2h`, or `1d`.")
amount = int(match.group(1))
multipliers = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
seconds = amount * multipliers[match.group(2)]
if seconds <= 0 or seconds > maximum_seconds:
raise ValueError("That duration is outside the allowed range.")
return seconds
def human_duration(seconds: int) -> str:
units = ((604800, "week"), (86400, "day"), (3600, "hour"), (60, "minute"), (1, "second"))
parts = []
remaining = seconds
for size, name in units:
count, remaining = divmod(remaining, size)
if count:
parts.append(f"{count} {name}{'' if count == 1 else 's'}")
return ", ".join(parts) or "0 seconds"
intents = discord.Intents.all()
class Bot(commands.Bot):
def __init__(self) -> None:
super().__init__(
command_prefix=commands.when_mentioned_or(PREFIX),
intents=intents,
help_command=None,
case_insensitive=True,
description="A general-purpose Discord bot with utility, fun, and moderation commands.",
)
self.db = Database(DATABASE_PATH)
self.started_at = time.monotonic()
async def setup_hook(self) -> None:
await self.db.connect()
self.add_view(VerifyView())
self.reminder_worker.start()
synced = await self.tree.sync()
log.info("Synced %d application commands", len(synced))
async def close(self) -> None:
if self.reminder_worker.is_running():
self.reminder_worker.cancel()
await self.db.close()
await super().close()
@tasks.loop(seconds=30)
async def reminder_worker(self) -> None:
now = int(datetime.now(timezone.utc).timestamp())
reminders = await self.db.fetchall(
"SELECT id, user_id, channel_id, message FROM reminders WHERE remind_at <= ?",
(now,),
)
for reminder in reminders:
try:
channel = self.get_channel(reminder["channel_id"])
if channel is None:
channel = await self.fetch_channel(reminder["channel_id"])
await channel.send(
f"<@{reminder['user_id']}> ⏰ Reminder: {reminder['message']}"
)
except (discord.DiscordException, TypeError) as error:
log.warning("Could not deliver reminder %s: %s", reminder["id"], error)
finally:
await self.db.execute("DELETE FROM reminders WHERE id = ?", (reminder["id"],))
@reminder_worker.before_loop
async def before_reminder_worker(self) -> None:
await self.wait_until_ready()
bot = Bot()
class VerifyView(discord.ui.View):
def __init__(self) -> None:
super().__init__(timeout=None)
@discord.ui.button(
label="Verify",
style=discord.ButtonStyle.success,
emoji="✅",
custom_id="verification:verify",
)
async def verify_button(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message("Verification is only available in a server.", ephemeral=True)
return
setting = await bot.db.fetchone(
"SELECT verification_role_id FROM guild_settings WHERE guild_id = ?",
(interaction.guild.id,),
)
role_id = setting["verification_role_id"] if setting else None
role = interaction.guild.get_role(role_id) if role_id else None
if role is None:
await interaction.response.send_message("Verification has not been configured yet.", ephemeral=True)
return
if role.managed or role == interaction.guild.default_role:
await interaction.response.send_message("The configured verification role cannot be assigned.", ephemeral=True)
return
if interaction.guild.me is None or role >= interaction.guild.me.top_role:
await interaction.response.send_message("I cannot assign the configured verification role. Move my role above it.", ephemeral=True)
return
if role in interaction.user.roles: