Files
path
tierlist-bot
Code
11 5,000
tierlist-bot/main.py
"""
Main entry point for Tierlist Bot.
"""

import discord
from discord.ext import commands
from discord import app_commands
import os
import asyncio
from typing import Optional
from dotenv import load_dotenv

import config
import database as db
import utils
from views import SetupView, QueueView, GamemodeSelectView, SupportTicketView
from ticket_manager import TicketManager
from queue_manager import send_queue_embed, open_queue, close_queue, next_user, force_test
from ranking import get_leaderboard_embed, get_tester_stats_embed

load_dotenv()

# =========================================================
# BOT SETUP
# =========================================================

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(
    command_prefix="!",
    intents=intents,
    description="Tierlist Testing Bot"
)

# =========================================================
# BOT EVENTS
# =========================================================

@bot.event
async def on_ready():
    """Called when the bot is ready."""
    print(f"Logged in as {bot.user} (ID: {bot.user.id})")
    print("------")

    # Initialize database
    db.init_db()
    print("Database initialized.")

    # Register persistent views
    bot.add_view(SetupView())
    bot.add_view(SupportTicketView())
    print("SetupView registered persistently.")
    print("SupportTicketView registered persistently.")

    # Register queue views
    for region in ["AS", "EU"]:
        for gamemode in config.GAMEMODES:
            queue_info = db.get_queue_message(region, gamemode)
            if queue_info and queue_info["is_open"]:
                bot.add_view(QueueView(region, gamemode))
                print(f"QueueView registered: {region} - {gamemode}")

    # Sync commands
    try:
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} commands.")
    except Exception as e:
        print(f"Failed to sync commands: {e}")

    # Start tester stats auto-refresh
    bot.loop.create_task(auto_refresh_tester_stats())


async def auto_refresh_tester_stats():
    """Auto-refresh tester statistics embeds (daily, weekly, monthly, overall) every 30 seconds."""
    await bot.wait_until_ready()
    while not bot.is_closed():
        try:
            for guild in bot.guilds:
                channel = await utils.get_guild_channel(guild, "testerstat", config.TESTERSTAT_CHANNEL)
                if channel:
                    for period in ["daily", "weekly", "monthly", "overall"]:
                        embed, _ = get_tester_stats_embed(period)
                        await _update_embed(channel, embed, f"testerstats_{period}")
        except Exception:
            pass
        await asyncio.sleep(30)


async def _update_embed(channel: discord.TextChannel, embed: discord.Embed, identifier: str):
    """Update or create a persistent embed in a channel."""
    async for message in channel.history(limit=50):
        if message.author == bot.user and message.embeds:
            existing = message.embeds[0]
            if existing.title == embed.title:
                await message.edit(embed=embed)
                return
    await channel.send(embed=embed)


# =========================================================
# COMMAND: SETUP
# =========================================================

@bot.tree.command(
    name="setup",
    description="Post the verification setup embed."
)
async def setup(interaction: discord.Interaction):
    """Post the verification and waitlist setup embed."""
    if not await utils.has_administrator_permission(interaction):
        return

    embed = discord.Embed(
        title="Evaluation Testing Waitlist",
        description=(
            "Upon applying, you will be added to a waitlist channel. You will be pinged when a tester is available. If you are HT3 or higher, a high test ticket will be created.\n\n"
            "โ€ข **Region** should be the region of the server you wish to test on.\n"
            "โ€ข **Username** should be the account you will be testing on.\n\n"
            "**๐Ÿ›‘Failure to provide authentic information will result in a denied test.**"
        ),
        color=discord.Color.blue()
    )
    await interaction.response.send_message(embed=embed, view=SetupView())


# =========================================================
# COMMAND: SETGAMEMODE
# =========================================================

@bot.tree.command(
    name="setgamemode",
    description="Set the gamemode for this server."
)
@discord.app_commands.describe(gamemode="Select the gamemode for this server")
@discord.app_commands.choices(gamemode=[
    discord.app_commands.Choice(name=gm, value=gm) for gm in config.GAMEMODES
])
async def setgamemode(interaction: discord.Interaction, gamemode: str):
    """Set the gamemode for the current server."""
    if not interaction.guild:
        await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
        return

    if not await utils.has_administrator_permission(interaction):
        return

    db.set_server_gamemode(interaction.guild_id, gamemode)
    embed = discord.Embed(
        title="โœ… Gamemode Set",
        description=f"This server is now set to **{gamemode}**.",
        color=discord.Color.green()
    )
    await interaction.response.send_message(embed=embed, ephemeral=True)


# =========================================================
# COMMAND: SENDQUEUE
# =========================================================

@bot.tree.command(
    name="sendqueue",
    description="Post the queue embed for a region."
)
@discord.app_commands.describe(region="Select the region")
@discord.app_commands.choices(region=[
    discord.app_commands.Choice(name="AS", value="AS"),
    discord.app_commands.Choice(name="EU", value="EU"),
])
async def sendqueue(interaction: discord.Interaction, region: str):
    """Post the queue closed embed."""
    if not await utils.has_administrator_permission(interaction):
        return
    await interaction.response.defer(ephemeral=True)
    await send_queue_embed(interaction, region)


# =========================================================
# COMMAND: OPENQUEUE
# =========================================================

@bot.tree.command(
    name="openqueue",
    description="Open a queue for testing."
)
@discord.app_commands.describe(region="Select the region")
@discord.app_commands.choices(region=[
    discord.app_commands.Choice(name="AS", value="AS"),
    discord.app_commands.Choice(name="EU", value="EU"),
])
async def openqueue(interaction: discord.Interaction, region: str):
    """Open a queue."""
    if not await utils.has_tester_role(interaction):
        return
    await interaction.response.defer(ephemeral=True)
    await open_queue(interaction, region)