Files
bot.py
config.json
requirements.txt
Code
3 1,732
bot.py
import asyncio
import copy
import html
import io
import json
import logging
import os
import re
import sqlite3
import time
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
CONFIG_PATH = BASE_DIR / "config.json"
DATABASE_PATH = BASE_DIR / "tickets.sqlite3"
CUSTOM_EMOJI_RE = re.compile(r"<a?:[A-Za-z0-9_]+:(\d+)>")
USER_MENTION_RE = re.compile(r"<@!?(\d+)>")
logger = logging.getLogger("hexaclouds_tickets")
def load_config():
with CONFIG_PATH.open("r", encoding="utf-8") as config_file:
config = json.load(config_file)
config.setdefault("defaults", {})
config["defaults"].setdefault("staff_role_ids", [])
config["defaults"].setdefault("admin_role_ids", [])
config["defaults"].setdefault("log_channel_id", None)
config["defaults"].setdefault("premium_role_id", None)
config["defaults"].setdefault("notification_role_ids", {"normal": [], "priority": []})
config["defaults"].setdefault("staff_apply_open", True)
config["defaults"].setdefault("panel_title", "Welcome to HexaClouds Support <:Vps1:1544659108807053332>")
config["defaults"].setdefault(
"panel_intro",
"Need assistance with your hosting or services? Select the appropriate category below to open a support ticket.",
)
config["defaults"].setdefault(
"panel_guidelines",
"Provide as much detail as possible, including logs, screenshots, and error messages. Our HexaClouds support team will assist you as quickly as possible.",
)
config["defaults"].setdefault(
"panel_notice",
"Please do not open multiple tickets for the same issue. Spamming or abusing the ticket system may result in moderation action.",
)
config["defaults"].setdefault("categories", [])
config.setdefault("guilds", {})
return config
CONFIG = load_config()
def save_config():
temp_path = CONFIG_PATH.with_suffix(".json.tmp")
with temp_path.open("w", encoding="utf-8") as config_file:
json.dump(CONFIG, config_file, indent=2, ensure_ascii=False)
config_file.write("\n")
temp_path.replace(CONFIG_PATH)
def guild_config(guild_id):
settings = copy.deepcopy(CONFIG["defaults"])
settings.update(copy.deepcopy(CONFIG["guilds"].get(str(guild_id), {})))
return settings
def save_guild_config(guild_id, settings):
CONFIG["guilds"][str(guild_id)] = copy.deepcopy(settings)
save_config()
def brand_embed(title, description=None, *, color=None):
embed = discord.Embed(
title=title,
description=description,
color=color or discord.Colour.from_rgb(45, 212, 191),
timestamp=discord.utils.utcnow(),
)
embed.set_footer(text="HexaClouds β’ Premium Support")
return embed
async def branded_response(interaction, description, *, title="HexaClouds Support", ephemeral=True, view=None):
await interaction.response.send_message(
embed=brand_embed(title, description),
ephemeral=ephemeral,
view=view,
)
def category_is_open(category, settings):
return category.get("key") != "staff_apply" or settings.get("staff_apply_open", True)
def active_categories(settings):
return [category for category in settings["categories"] if category_is_open(category, settings)]
def category_key(name):
key = re.sub(r"[^a-z0-9]+", "_", name.strip().lower()).strip("_")
return key or f"category_{int(time.time())}"
class TicketStore:
def __init__(self, path):
self.connection = sqlite3.connect(path, isolation_level=None)
self.connection.row_factory = sqlite3.Row
self.connection.execute("PRAGMA journal_mode=WAL")
self.connection.executescript(
"""
CREATE TABLE IF NOT EXISTS tickets (
channel_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
category_key TEXT NOT NULL,
opened_at REAL NOT NULL,
status TEXT NOT NULL DEFAULT 'open',
claimed_by INTEGER,
premium INTEGER NOT NULL DEFAULT 0,
priority_level INTEGER NOT NULL DEFAULT 0,
response_seconds REAL,
control_message_id INTEGER
);
CREATE INDEX IF NOT EXISTS tickets_active_user
ON tickets(guild_id, user_id, status);
CREATE TABLE IF NOT EXISTS settings (
guild_id INTEGER NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY(guild_id, key)
);
CREATE TABLE IF NOT EXISTS ticket_feedback (
ticket_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
rating INTEGER NOT NULL CHECK(rating BETWEEN 1 AND 5),
feedback TEXT,
submitted_at REAL NOT NULL,
log_message_id INTEGER
);
CREATE TABLE IF NOT EXISTS ticket_blacklist (
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
added_by INTEGER NOT NULL,
reason TEXT NOT NULL,
added_at REAL NOT NULL,
PRIMARY KEY(guild_id, user_id)
);
"""
)
columns = {row["name"] for row in self.connection.execute("PRAGMA table_info(tickets)")}
if "priority_level" not in columns:
self.connection.execute("ALTER TABLE tickets ADD COLUMN priority_level INTEGER NOT NULL DEFAULT 0")
self.connection.execute("UPDATE tickets SET priority_level = 1 WHERE premium = 1 AND priority_level = 0")
def active_count(self, guild_id, user_id):
row = self.connection.execute(
"SELECT COUNT(*) AS count FROM tickets WHERE guild_id = ? AND user_id = ? AND status = 'open'",
(guild_id, user_id),
).fetchone()
return row["count"]
def add_ticket(self, channel_id, guild_id, user_id, category):
self.connection.execute(
"INSERT INTO tickets(channel_id, guild_id, user_id, category_key, opened_at) VALUES (?, ?, ?, ?, ?)",
(channel_id, guild_id, user_id, category, time.time()),
)
def get_ticket(self, channel_id):
row = self.connection.execute("SELECT * FROM tickets WHERE channel_id = ?", (channel_id,)).fetchone()
return dict(row) if row else None
def set_claim(self, channel_id, user_id):
self.connection.execute(
"UPDATE tickets SET claimed_by = ?, response_seconds = COALESCE(response_seconds, "
"MAX(0, ? - opened_at)) WHERE channel_id = ? AND status = 'open'",
(user_id, time.time(), channel_id),
)
def set_priority(self, channel_id, level):
self.connection.execute(
"UPDATE tickets SET premium = ?, priority_level = ? WHERE channel_id = ? AND status = 'open'",
(int(level > 0), level, channel_id),
)
def set_control_message(self, channel_id, message_id):
self.connection.execute(
"UPDATE tickets SET control_message_id = ? WHERE channel_id = ?",
(message_id, channel_id),
)
def close_ticket(self, channel_id):
self.connection.execute(
"UPDATE tickets SET status = 'closed' WHERE channel_id = ? AND status = 'open'",
(channel_id,),