Files
bot.py
requirements.txt
Code
2 636
bot.py
import asyncio
import logging
import os
from dataclasses import dataclass
from typing import Optional
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("ticket-bot")
TOKEN = os.getenv("DISCORD_TOKEN")
HELPER_ROLE_ID = int(os.getenv("HELPER_ROLE_ID", "1531737655857905734"))
STAFF_ROLE_ID = int(os.getenv("STAFF_ROLE_ID", "1531737655837196404"))
TICKET_CATEGORY_ID = int(os.getenv("TICKET_CATEGORY_ID", "0"))
TICKET_CHANNELS = {
"report": 1531737657506533522,
"support": 1531737657506533523,
"ban": 1531737657716244600,
"bug": 1531737657506533525,
"media": 1531737657716244602,
}
APPLICATION_CHANNEL_ID = 1531737657506533518
ACCEPTED_CHANNEL_ID = 1531737657506533519
DECLINED_CHANNEL_ID = 1531737657506533520
PANEL_MARKER = "Kodari ticket panel"
APPLICATION_PANEL_MARKER = "Kodari application panel"
APPLICATION_QUESTIONS = [
"What is your Minecraft username and Discord username?",
"How old are you?",
"What time zone are you in?",
"How long have you played on our Minecraft server?",
"How many hours per week can you be active as a Helper?",
"Have you held staff on another server? If so, what did you do?",
"Why do you want to become a Helper on our server?",
"What qualities would make you a good Helper?",
"What do you think the main responsibility of a Helper is?",
"How would you respond to a player who is being rude to you?",
"How would you handle two players arguing in chat?",
"What would you do if a friend broke a server rule?",
"How would you deal with a player who is spamming?",
"What would you do if you were unsure whether a player was cheating?",
"How would you handle confidential staff information?",
"How do you respond to constructive criticism?",
"What would you do if you disagreed with another staff member?",
"Are you familiar with our server rules and willing to enforce them fairly?",
"Is there anything else you would like us to know about you?",
"Do you agree to follow staff guidelines and represent the server respectfully?",
]
@dataclass
class ApplicationSession:
user_id: int
guild_id: int
active_applications: dict[int, ApplicationSession] = {}
panel_lock = asyncio.Lock()
def get_channel(guild: discord.Guild, channel_id: int) -> Optional[discord.TextChannel]:
channel = guild.get_channel(channel_id)
return channel if isinstance(channel, discord.TextChannel) else None
async def fetch_text_channel(guild: discord.Guild, channel_id: int) -> Optional[discord.TextChannel]:
channel = get_channel(guild, channel_id)
if channel:
return channel
try:
channel = await guild.fetch_channel(channel_id)
except (discord.Forbidden, discord.NotFound, discord.HTTPException):
return None
return channel if isinstance(channel, discord.TextChannel) else None
def is_staff(member: discord.Member) -> bool:
if member.guild_permissions.administrator or member.guild_permissions.manage_guild:
return True
return bool(STAFF_ROLE_ID and any(role.id == STAFF_ROLE_ID for role in member.roles))
def truncate(value: str, length: int = 1000) -> str:
value = value.strip()
return value if len(value) <= length else f"{value[: length - 3]}..."
class TicketCloseView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
button = discord.ui.Button(
label="Close ticket",
style=discord.ButtonStyle.danger,
emoji="🔒",
custom_id="ticket_close",
)
button.callback = self.close_ticket
self.add_item(button)
async def close_ticket(self, interaction: discord.Interaction):
if not isinstance(interaction.channel, discord.TextChannel):
await interaction.response.send_message("This is not a ticket channel.", ephemeral=True)
return
topic = interaction.channel.topic or ""
owner_id = next(
(int(part.removeprefix("user=")) for part in topic.split(";") if part.startswith("user=")),
0,
)
member = interaction.guild.get_member(interaction.user.id) if interaction.guild else None
if interaction.user.id != owner_id and (not member or not is_staff(member)):
await interaction.response.send_message("Only the ticket owner or staff can close this ticket.", ephemeral=True)
return
await interaction.response.send_message("This ticket will be closed in 5 seconds.")
await asyncio.sleep(5)
try:
await interaction.channel.delete(reason=f"Ticket closed by {interaction.user}")
except discord.Forbidden:
logger.exception("The bot could not delete ticket channel %s", interaction.channel.id)
class TicketTypeSelect(discord.ui.Select):
def __init__(self):
super().__init__(
placeholder="Choose a ticket type...",
min_values=1,
max_values=1,
custom_id="ticket_type_select",
options=[
discord.SelectOption(label="Report a player", value="report", emoji="🚨"),
discord.SelectOption(label="Get support", value="support", emoji="🛠️"),
discord.SelectOption(label="Ban appeal", value="ban", emoji="⚖️"),
discord.SelectOption(label="Report a bug", value="bug", emoji="🐛"),
discord.SelectOption(label="Media request", value="media", emoji="🎬"),
],
)
async def callback(self, interaction: discord.Interaction):
await create_ticket(interaction, self.values[0])
class TicketPanelView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(TicketTypeSelect())
class ApplicationPanelView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
button = discord.ui.Button(
label="Apply for Helper",
style=discord.ButtonStyle.success,
emoji="📋",
custom_id="helper_application:start",
)
button.callback = self.start_application
self.add_item(button)
async def start_application(self, interaction: discord.Interaction):
if not interaction.guild:
await interaction.response.send_message("Applications must be started from the server.", ephemeral=True)
return
if interaction.user.id in active_applications:
await interaction.response.send_message("You already have an application in progress.", ephemeral=True)
return
try:
await interaction.user.send(
"Your Helper application is starting. I will ask 20 questions one at a time. "
"Reply to each question in this DM. Type `cancel` at any time to stop."
)
except discord.Forbidden:
await interaction.response.send_message(
"I could not DM you. Please enable direct messages from this server and try again.",
ephemeral=True,
)
return
await interaction.response.send_message("I sent the application questions to your DMs.", ephemeral=True)
asyncio.create_task(run_application(interaction.user, interaction.guild.id))