Files
.gitignore
bot.py
README.md
requirements.txt
Code
4 990
bot.py
import asyncio
import json
import logging
import os
import random
import re
import time
from datetime import timedelta
import aiosqlite
import discord
from discord import app_commands
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("kodari_bot")
class Database:
def __init__(self, path="bot.sqlite3"):
self.path = path
self.connection = None
async def initialize(self):
self.connection = await aiosqlite.connect(self.path)
self.connection.row_factory = aiosqlite.Row
await self.connection.executescript("""
CREATE TABLE IF NOT EXISTS config (
guild_id INTEGER NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
PRIMARY KEY (guild_id, key)
);
CREATE TABLE IF NOT EXISTS polls (
message_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL, question TEXT NOT NULL,
options TEXT NOT NULL, ends_at REAL NOT NULL,
multiple_choice INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'open'
);
CREATE TABLE IF NOT EXISTS poll_votes (
message_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
option_index INTEGER NOT NULL,
PRIMARY KEY (message_id, user_id, option_index)
);
CREATE TABLE IF NOT EXISTS giveaways (
message_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL, prize TEXT NOT NULL,
winners INTEGER NOT NULL, ends_at REAL NOT NULL,
status TEXT NOT NULL DEFAULT 'open'
);
CREATE TABLE IF NOT EXISTS giveaway_entries (
message_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
PRIMARY KEY (message_id, user_id)
);
CREATE TABLE IF NOT EXISTS suggestions (
message_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL,
author_id INTEGER NOT NULL, suggestion TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS suggestion_votes (
message_id INTEGER NOT NULL, user_id INTEGER NOT NULL,
vote INTEGER NOT NULL, PRIMARY KEY (message_id, user_id)
);
CREATE TABLE IF NOT EXISTS tickets (
channel_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'open',
created_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS temp_voice_channels (
channel_id INTEGER PRIMARY KEY, guild_id INTEGER NOT NULL,
owner_id INTEGER NOT NULL
);
""")
await self.connection.commit()
async def execute(self, query, params=()):
async with self.connection.execute(query, params) as cursor:
await self.connection.commit()
return cursor.lastrowid
async def fetchone(self, query, params=()):
async with self.connection.execute(query, params) as cursor:
return await cursor.fetchone()
async def fetchall(self, query, params=()):
async with self.connection.execute(query, params) as cursor:
return await cursor.fetchall()
async def set_config(self, guild_id, key, value):
await self.execute(
"INSERT INTO config(guild_id,key,value) VALUES(?,?,?) "
"ON CONFLICT(guild_id,key) DO UPDATE SET value=excluded.value",
(guild_id, key, str(value)),
)
async def get_config(self, guild_id, key, default=None):
row = await self.fetchone("SELECT value FROM config WHERE guild_id=? AND key=?", (guild_id, key))
return row["value"] if row else default
async def get_bool(self, guild_id, key, default=False):
value = await self.get_config(guild_id, key)
return default if value is None else value.lower() in ("1", "true", "yes", "on")
database = Database()
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
intents.voice_states = True
class KodariBot(commands.Bot):
async def setup_hook(self):
await database.initialize()
self.add_view(VerificationView())
self.add_view(SuggestionView())
self.add_view(GiveawayView())
self.add_view(TicketPanelView())
self.add_view(TicketCloseView())
self.add_view(PollView())
await self.tree.sync()
self.maintenance_task = asyncio.create_task(maintenance_loop())
async def close(self):
task = getattr(self, "maintenance_task", None)
if task:
task.cancel()
if database.connection:
await database.connection.close()
await super().close()
bot = KodariBot(command_prefix=commands.when_mentioned, intents=intents)
class V2Panel(discord.ui.LayoutView):
def __init__(self, text, buttons=(), *, persistent=True, accent=discord.Colour.blurple()):
super().__init__(timeout=None if persistent else 180)
children = [discord.ui.TextDisplay(text)]
if buttons:
children.extend((discord.ui.Separator(), discord.ui.ActionRow(*buttons)))
self.add_item(discord.ui.Container(*children, accent_colour=accent))
class VerifyButton(discord.ui.Button):
def __init__(self):
super().__init__(label="Verify", style=discord.ButtonStyle.success, custom_id="verification:verify")
async def callback(self, interaction):
if not interaction.guild or not isinstance(interaction.user, discord.Member):
return await interaction.response.send_message("This button only works in a server.", ephemeral=True)
if not await database.get_bool(interaction.guild.id, "verification_enabled", True):
return await interaction.response.send_message("Verification is currently disabled.", ephemeral=True)
role_id = await database.get_config(interaction.guild.id, "verification_role")
role = interaction.guild.get_role(int(role_id)) if role_id else None
if not role:
return await interaction.response.send_message("Verification is not configured yet. Please contact a server administrator.", ephemeral=True)
if role in interaction.user.roles:
return await interaction.response.send_message("You are already verified.", ephemeral=True)
try:
await interaction.user.add_roles(role, reason="Self-service server verification")
except discord.Forbidden:
return await interaction.response.send_message("I cannot assign the verification role. Ask an administrator to check my role position and permissions.", ephemeral=True)
await interaction.response.send_message("You are verified. Welcome!", ephemeral=True)
class VerificationView(V2Panel):
def __init__(self, text="Press Verify after reading the server rules."):
super().__init__(text, [VerifyButton()])
class SuggestionButton(discord.ui.Button):
def __init__(self, vote):
self.vote = vote
super().__init__(label="๐ Support", style=discord.ButtonStyle.success, custom_id="suggestion:up" if vote == 1 else "suggestion:down")
async def callback(self, interaction):
await record_suggestion_vote(interaction, self.vote)
class SuggestionView(V2Panel):
def __init__(self, text="Suggestion", up=0, down=0):
super().__init__(f"{text}\n\n**Support:** {up}ใ **Against:** {down}", [SuggestionButton(1), SuggestionButton(-1)])
class PollVoteButton(discord.ui.Button):
def __init__(self, index, label=None):
self.index = index
super().__init__(label=label or f"Option {index + 1}", style=discord.ButtonStyle.primary, custom_id=f"poll:vote:{index}")
async def callback(self, interaction):
await record_poll_vote(interaction, self.index)
class PollView(V2Panel):
def __init__(self, text="Poll", options=None, active=True):
options = options or [f"Option {index + 1}" for index in range(5)]
buttons = [PollVoteButton(index, option[:80]) for index, option in enumerate(options)] if active else []
super().__init__(text, buttons)