Files
main.py
requirements.txt
Code
2 381
main.py
import json
import logging
import os
from pathlib import Path
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("erlc_server_bot")
DATA_FILE = Path("bot_data.json")
DEFAULT_LOW_PLAYER_THRESHOLD = 5
def load_data() -> dict:
try:
with DATA_FILE.open("r", encoding="utf-8") as data_file:
data = json.load(data_file)
return data if isinstance(data, dict) else {}
except FileNotFoundError:
return {}
except (json.JSONDecodeError, OSError):
logger.exception("Could not load bot_data.json; starting with empty settings")
return {}
def save_data() -> None:
temporary_file = DATA_FILE.with_suffix(".tmp")
with temporary_file.open("w", encoding="utf-8") as data_file:
json.dump(bot_data, data_file, indent=2)
temporary_file.replace(DATA_FILE)
bot_data = load_data()
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
def guild_data(guild_id: int) -> dict:
return bot_data.setdefault(str(guild_id), {"channels": {}, "session": {"active": False}})
def configured_text_channel(guild: discord.Guild, key: str) -> discord.TextChannel | None:
channel_id = guild_data(guild.id).get("channels", {}).get(key)
channel = guild.get_channel(channel_id) if channel_id else None
return channel if isinstance(channel, discord.TextChannel) else None
async def send_announcement(guild: discord.Guild, embed: discord.Embed) -> bool:
channel = configured_text_channel(guild, "announcements")
if channel is None:
return False
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
return True
def session_embed(title: str, description: str, color: discord.Color) -> discord.Embed:
return discord.Embed(title=title, description=description, color=color)
async def announce_player_conditions(guild: discord.Guild, session: dict) -> None:
players = session["players"]
maximum = session["max_players"]
settings = guild_data(guild.id)
threshold = settings.get("low_player_threshold", DEFAULT_LOW_PLAYER_THRESHOLD)
if players <= threshold and not session.get("low_alerted", False):
await send_announcement(
guild,
session_embed(
"Session player count is low",
f"There are **{players}/{maximum}** players in the server.",
discord.Color.orange(),
),
)
session["low_alerted"] = True
elif players > threshold:
session["low_alerted"] = False
if players >= maximum and not session.get("full_alerted", False):
await send_announcement(
guild,
session_embed(
"Session is full",
f"The server has reached **{players}/{maximum}** players.",
discord.Color.red(),
),
)
session["full_alerted"] = True
elif players < maximum:
session["full_alerted"] = False
class StaffFeedbackModal(discord.ui.Modal, title="Staff Feedback"):
staff_member = discord.ui.TextInput(
label="Staff member (name or mention)",
max_length=100,
required=True,
)
feedback = discord.ui.TextInput(
label="Your feedback",
style=discord.TextStyle.paragraph,
max_length=1000,
required=True,
)
async def on_submit(self, interaction: discord.Interaction) -> None:
if interaction.guild is None:
await interaction.response.send_message(
"Staff feedback can only be submitted in a server.", ephemeral=True
)
return
channel = configured_text_channel(interaction.guild, "feedback")
if channel is None:
await interaction.response.send_message(
"Staff feedback is not configured yet. Ask an administrator to run `/setup`.",
ephemeral=True,
)
return
embed = discord.Embed(title="New staff feedback", color=discord.Color.blurple())
embed.add_field(name="Staff member", value=str(self.staff_member), inline=False)
embed.add_field(name="Feedback", value=str(self.feedback), inline=False)
embed.set_footer(text=f"Submitted by {interaction.user} • {interaction.user.id}")
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
await interaction.response.send_message("Your feedback was sent to staff.", ephemeral=True)
@bot.event
async def on_ready() -> None:
try:
synced = await bot.tree.sync()
logger.info("Synced %s application commands", len(synced))
except discord.DiscordException:
logger.exception("Could not sync application commands")
logger.info("Connected as %s", bot.user)
print("KODARI_READY", flush=True)
@bot.event
async def on_member_join(member: discord.Member) -> None:
channel = configured_text_channel(member.guild, "welcome")
if channel is None:
return
member_count = member.guild.member_count or len(member.guild.members)
embed = discord.Embed(
title=f"Welcome to {member.guild.name}!",
description=f"Welcome {member.mention}! You are member **#{member_count}**.",
color=discord.Color.green(),
)
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions(users=True))
@bot.tree.command(name="setup", description="Configure the bot's channels and low-player alert threshold")
@app_commands.guild_only()
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.describe(
welcome_channel="Main chat channel for welcome messages",
announcements_channel="Channel for session announcements",
feedback_channel="Private staff channel for submitted feedback",
promotions_channel="Channel for staff promotion announcements",
low_player_threshold="Announce low players at or below this count (default: 5)",
)
async def setup(
interaction: discord.Interaction,
welcome_channel: discord.TextChannel | None = None,
announcements_channel: discord.TextChannel | None = None,
feedback_channel: discord.TextChannel | None = None,
promotions_channel: discord.TextChannel | None = None,
low_player_threshold: app_commands.Range[int, 0, 1000] | None = None,
) -> None:
if interaction.guild is None:
await interaction.response.send_message("Use this command in your server.", ephemeral=True)
return
settings = guild_data(interaction.guild.id)
channels = settings.setdefault("channels", {})
updated = []
for key, channel in (
("welcome", welcome_channel),
("announcements", announcements_channel),
("feedback", feedback_channel),
("promotions", promotions_channel),
):
if channel is not None:
channels[key] = channel.id
updated.append(f"{key}: {channel.mention}")
if low_player_threshold is not None:
settings["low_player_threshold"] = low_player_threshold