Files
config.json
main.py
README.md
requirements.txt
Code
4 1,861
main.py
import asyncio
import io
import json
import os
import random
import re
import sqlite3
import time
from collections import defaultdict, deque
from datetime import timedelta
from typing import Optional
import aiohttp
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv
load_dotenv()
def load_config() -> dict:
with open("config.json", "r", encoding="utf-8") as file:
return json.load(file)
CONFIG = load_config()
TOKEN = os.getenv("DISCORD_TOKEN")
WEBHOOK_NAMES = (
"tickets",
"moderation",
"giveaways",
"suggestions",
"applications",
"welcome",
"system",
)
WEBHOOKS = {
name: os.getenv(f"WEBHOOK_{name.upper()}", "")
for name in WEBHOOK_NAMES
}
def parse_duration(value: str) -> Optional[int]:
matches = re.findall(r"(\d+)\s*(s|m|h|d|w)", value.lower())
if not matches or "".join(number + unit for number, unit in matches) != re.sub(
r"\s+", "", value.lower()
):
return None
multipliers = {
"s": 1,
"m": 60,
"h": 3600,
"d": 86400,
"w": 604800,
}
seconds = sum(int(number) * multipliers[unit] for number, unit in matches)
if seconds < 10 or seconds > 30 * 86400:
return None
return seconds
def format_duration(seconds: int) -> str:
parts = []
for suffix, divider in (("d", 86400), ("h", 3600), ("m", 60), ("s", 1)):
amount, seconds = divmod(seconds, divider)
if amount:
parts.append(f"{amount}{suffix}")
return " ".join(parts) or "0s"
class Database:
def __init__(self, path: str):
self.connection = sqlite3.connect(path, check_same_thread=False)
self.connection.row_factory = sqlite3.Row
self.lock = asyncio.Lock()
async def initialize(self):
async with self.lock:
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS tickets (
channel_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
ticket_type TEXT NOT NULL,
created_at INTEGER NOT NULL,
closed_at INTEGER
);
CREATE TABLE IF NOT EXISTS giveaways (
message_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
channel_id INTEGER NOT NULL,
host_id INTEGER NOT NULL,
prize TEXT NOT NULL,
winners INTEGER NOT NULL,
ends_at INTEGER NOT NULL,
ended INTEGER NOT NULL DEFAULT 0
);
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 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
);
"""
)
self.connection.commit()
async def fetchone(self, query: str, parameters: tuple = ()):
async with self.lock:
cursor = self.connection.execute(query, parameters)
return cursor.fetchone()
async def fetchall(self, query: str, parameters: tuple = ()):
async with self.lock:
cursor = self.connection.execute(query, parameters)
return cursor.fetchall()
async def execute(self, query: str, parameters: tuple = ()):
async with self.lock:
cursor = self.connection.execute(query, parameters)
self.connection.commit()
return cursor.lastrowid
async def open_ticket(
self,
channel_id: int,
guild_id: int,
user_id: int,
ticket_type: str,
):
await self.execute(
"""
INSERT INTO tickets
(channel_id, guild_id, user_id, ticket_type, created_at)
VALUES (?, ?, ?, ?, ?)
""",
(channel_id, guild_id, user_id, ticket_type, int(time.time())),
)
async def get_ticket_by_channel(self, channel_id: int):
return await self.fetchone(
"SELECT * FROM tickets WHERE channel_id = ? AND closed_at IS NULL",
(channel_id,),
)
async def get_open_ticket_for_user(self, guild_id: int, user_id: int):
return await self.fetchone(
"""
SELECT * FROM tickets
WHERE guild_id = ? AND user_id = ? AND closed_at IS NULL
""",
(guild_id, user_id),
)
async def close_ticket(self, channel_id: int):
await self.execute(
"UPDATE tickets SET closed_at = ? WHERE channel_id = ?",
(int(time.time()), channel_id),
)
async def create_giveaway(
self,
message_id: int,
guild_id: int,
channel_id: int,
host_id: int,
prize: str,
winners: int,
ends_at: int,
):
await self.execute(
"""
INSERT INTO giveaways
(message_id, guild_id, channel_id, host_id, prize, winners, ends_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
message_id,
guild_id,
channel_id,
host_id,
prize,
winners,