Files
bot.py
requirements.txt
Code
2 782
bot.py
import logging
import os
from datetime import datetime, timezone
from urllib.parse import urlparse
import aiosqlite
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_staff_bot")
DATABASE_PATH = os.getenv("DATABASE_PATH", "bot.db")
SERVER_NAME = os.getenv("SERVER_NAME", "ERLC Roleplay")
SERVER_CODE = os.getenv("SERVER_CODE", "Not configured")
PROMOTION_BANNER_URL = os.getenv("PROMOTION_BANNER_URL", "")
HIGH_COMMAND_ROLE_ID = int(os.getenv("HIGH_COMMAND_ROLE_ID", "0") or "0")
BLUE = discord.Color.blue()
RED = discord.Color.red()
GREEN = discord.Color.green()
async def initialize_database():
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.executescript(
"""
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 infractions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
staff_id INTEGER NOT NULL,
type TEXT NOT NULL,
reason TEXT NOT NULL,
appealable TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS promotions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
staff_id INTEGER NOT NULL,
action TEXT NOT NULL,
old_role_id INTEGER NOT NULL,
new_role_id INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
host_id INTEGER NOT NULL,
kind TEXT NOT NULL,
status TEXT NOT NULL,
channel_id INTEGER NOT NULL,
message_id INTEGER,
started_at TEXT NOT NULL,
ended_at TEXT
);
CREATE TABLE IF NOT EXISTS session_votes (
session_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
PRIMARY KEY (session_id, user_id)
);
"""
)
await db.commit()
async def get_setting(guild_id: int, key: str):
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute(
"SELECT value FROM settings WHERE guild_id = ? AND key = ?",
(guild_id, key),
) as cursor:
row = await cursor.fetchone()
return row[0] if row else None
async def set_setting(guild_id: int, key: str, value: str):
async with aiosqlite.connect(DATABASE_PATH) as db:
await db.execute(
"INSERT INTO settings (guild_id, key, value) VALUES (?, ?, ?) "
"ON CONFLICT(guild_id, key) DO UPDATE SET value = excluded.value",
(guild_id, key, value),
)
await db.commit()
async def configured_text_channel(guild: discord.Guild, key: str):
channel_id = await get_setting(guild.id, f"channel:{key}")
if not channel_id:
return None
channel = bot.get_channel(int(channel_id))
if channel is None:
try:
channel = await bot.fetch_channel(int(channel_id))
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
return None
return channel if isinstance(channel, discord.TextChannel) else None
async def log_action(guild: discord.Guild, title: str, description: str, color=BLUE):
channel = await configured_text_channel(guild, "staff_logs")
if channel is None:
return
try:
await channel.send(embed=discord.Embed(title=title, description=description, color=color))
except discord.HTTPException:
logger.exception("Unable to post an action to the staff log channel")
def has_role(member: discord.Member, role_id: int):
return bool(role_id and any(role.id == role_id for role in member.roles))
async def require_permission(interaction: discord.Interaction, command_key: str):
member = interaction.user
if not isinstance(member, discord.Member):
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return False
configured_role_id = await get_setting(interaction.guild_id, f"permission:{command_key}")
if configured_role_id and not has_role(member, int(configured_role_id)):
await interaction.response.send_message(
f"You need the configured role for `/{command_key.replace('_', ' ')}` to use this command.",
ephemeral=True,
)
return False
high_command = has_role(member, HIGH_COMMAND_ROLE_ID)
if command_key in ("promote", "demote"):
allowed = member.guild_permissions.manage_roles or high_command
elif command_key in ("infract", "infractions"):
allowed = member.guild_permissions.manage_messages or high_command
elif command_key in ("session_start", "session_end"):
allowed = member.guild_permissions.manage_guild or high_command
else:
allowed = True
if not allowed:
if command_key in ("promote", "demote"):
message = "You need Manage Roles or the configured High Command role to use this command."
elif command_key in ("infract", "infractions"):
message = "You need Manage Messages or the configured High Command role to use this command."
else:
message = "You need Manage Server or the configured High Command role to use this command."
await interaction.response.send_message(message, ephemeral=True)
return False
return True
async def get_member(guild: discord.Guild, user: discord.User):
member = guild.get_member(user.id)
if member is not None:
return member
try:
return await guild.fetch_member(user.id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
return None
async def send_dm(user: discord.abc.User, embed: discord.Embed):
try:
await user.send(embed=embed)
return True
except (discord.Forbidden, discord.HTTPException):
return False
async def notify_session_audience(guild_id: int, embed: discord.Embed, additional_user_ids=()):
async with aiosqlite.connect(DATABASE_PATH) as db:
async with db.execute(
"SELECT DISTINCT sv.user_id FROM session_votes sv "
"JOIN sessions s ON s.id = sv.session_id "
"WHERE s.guild_id = ? AND s.kind = 'vote' AND s.status = 'open'",
(guild_id,),
) as cursor:
user_ids = {row[0] for row in await cursor.fetchall()}
user_ids.update(additional_user_ids)
delivered = 0
for user_id in user_ids:
user = bot.get_user(user_id)
if user is None:
try:
user = await bot.fetch_user(user_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
continue
if await send_dm(user, embed):
delivered += 1