Files
bot.py
requirements.txt
Code
2 368
bot.py
import asyncio
import logging
import os
import re
import sqlite3
import time
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("kurdking")
DATABASE = sqlite3.connect(os.getenv("KURDKING_DB_PATH", "kurdking.sqlite3"))
def initialize_database() -> None:
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS stats (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
messages INTEGER NOT NULL DEFAULT 0,
voice_seconds INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (guild_id, user_id)
)"""
)
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS voice_sessions (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
started_at REAL NOT NULL,
PRIMARY KEY (guild_id, user_id)
)"""
)
DATABASE.execute(
"""CREATE TABLE IF NOT EXISTS temporary_bans (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
expires_at REAL NOT NULL,
PRIMARY KEY (guild_id, user_id)
)"""
)
DATABASE.commit()
def finish_voice_session(guild_id: int, user_id: int, ended_at: float) -> None:
row = DATABASE.execute(
"SELECT started_at FROM voice_sessions WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
).fetchone()
if row is None:
return
DATABASE.execute(
"UPDATE stats SET voice_seconds = voice_seconds + ? WHERE guild_id = ? AND user_id = ?",
(max(0, int(ended_at - row[0])), guild_id, user_id),
)
DATABASE.execute(
"DELETE FROM voice_sessions WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
)
def parse_ban_duration(value: str) -> int | None:
normalized = value.strip().casefold()
if normalized in {"permanent", "perm", "هەمیشە"}:
return None
match = re.fullmatch(r"(\d+)([smhd])", normalized)
if match is None:
raise ValueError("ماوەکە بە شێوەی 30m، 12h، 7d یان permanent بنووسە.")
amount = int(match.group(1))
if amount < 1:
raise ValueError("ماوەکە دەبێت لە سفر زیاتر بێت.")
multiplier = {"s": 1, "m": 60, "h": 3600, "d": 86400}[match.group(2)]
return amount * multiplier
def format_voice_time(seconds: int) -> str:
hours, remainder = divmod(seconds, 3600)
minutes = remainder // 60
if hours:
return f"{hours} کاتژمێر و {minutes} خولەک"
return f"{minutes} خولەک"
class KurdkingBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self) -> None:
initialize_database()
await self.tree.sync()
asyncio.create_task(self.process_temporary_bans())
async def process_temporary_bans(self) -> None:
while not self.is_closed():
expired = DATABASE.execute(
"SELECT guild_id, user_id FROM temporary_bans WHERE expires_at <= ?",
(time.time(),),
).fetchall()
for guild_id, user_id in expired:
guild = self.get_guild(guild_id)
if guild is None:
continue
try:
await guild.unban(discord.Object(id=user_id), reason="Temporary ban expired")
except discord.NotFound:
pass
except discord.Forbidden:
logger.warning("Missing permission to expire ban for user %s", user_id)
continue
except discord.HTTPException:
logger.exception("Could not expire ban for user %s", user_id)
continue
DATABASE.execute(
"DELETE FROM temporary_bans WHERE guild_id = ? AND user_id = ?",
(guild_id, user_id),
)
DATABASE.commit()
await asyncio.sleep(30)
bot = KurdkingBot()
@bot.event
async def on_ready() -> None:
now = time.time()
active_voice_users: set[tuple[int, int]] = set()
for guild in bot.guilds:
for channel in guild.voice_channels:
for member in channel.members:
if not member.bot:
active_voice_users.add((guild.id, member.id))
DATABASE.execute(
"INSERT OR IGNORE INTO stats (guild_id, user_id) VALUES (?, ?)",
(guild.id, member.id),
)
DATABASE.execute(
"INSERT OR IGNORE INTO voice_sessions (guild_id, user_id, started_at) VALUES (?, ?, ?)",
(guild.id, member.id, now),
)
for guild_id, user_id in DATABASE.execute(
"SELECT guild_id, user_id FROM voice_sessions"
).fetchall():
if (guild_id, user_id) not in active_voice_users:
finish_voice_session(guild_id, user_id, now)
DATABASE.commit()
logger.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.tree.command(name="kurdking", description="Get a greeting from kurdking")
async def kurdking(interaction: discord.Interaction) -> None:
await interaction.response.send_message(f"Hello from kurdking, {interaction.user.mention}!")
@bot.tree.command(name="ban", description="بانکردنی ئەندام بۆ ماوەیەک یان بۆ هەمیشە")
@app_commands.guild_only()
@app_commands.describe(
member="ئەندامی سێرڤەر",
duration="وەک 30m، 12h، 7d یان permanent",
reason="هۆکاری بان",
)
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.checks.bot_has_permissions(ban_members=True)
async def ban_member(
interaction: discord.Interaction,
member: discord.Member,
duration: str,
reason: str,
) -> None:
try:
duration_seconds = parse_ban_duration(duration)
except ValueError as error:
await interaction.response.send_message(str(error), ephemeral=True)
return
guild = interaction.guild
if guild is None:
return
await guild.ban(member, reason=reason)
if duration_seconds is None:
DATABASE.execute(
"DELETE FROM temporary_bans WHERE guild_id = ? AND user_id = ?",
(guild.id, member.id),
)
message = f"{member} بۆ هەمیشە بان کرا. هۆکار: {reason}"
else:
expires_at = time.time() + duration_seconds
DATABASE.execute(
"INSERT OR REPLACE INTO temporary_bans (guild_id, user_id, expires_at) VALUES (?, ?, ?)",
(guild.id, member.id, expires_at),
)