Files
bot.py
requirements.txt
Code
2 309
bot.py
import asyncio
import logging
import os
import sqlite3
from datetime import datetime, timezone
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("erlc_sessions")
db = sqlite3.connect("sessions.db")
db.execute("PRAGMA foreign_keys = ON")
db.executescript("""
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
host_id INTEGER NOT NULL,
server_name TEXT NOT NULL,
join_code TEXT NOT NULL,
description TEXT NOT NULL,
status TEXT NOT NULL,
channel_id INTEGER NOT NULL,
message_id INTEGER,
created_at TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS one_active_session_per_guild
ON sessions(guild_id) WHERE status = 'active';
CREATE TABLE IF NOT EXISTS participants (
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL,
PRIMARY KEY(session_id, user_id)
);
CREATE TABLE IF NOT EXISTS session_polls (
message_id INTEGER PRIMARY KEY,
guild_id INTEGER NOT NULL,
host_id INTEGER NOT NULL,
description TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS session_votes (
message_id INTEGER NOT NULL REFERENCES session_polls(message_id) ON DELETE CASCADE,
user_id INTEGER NOT NULL,
choice TEXT NOT NULL,
PRIMARY KEY(message_id, user_id)
);
""")
if "vote_target" not in {row[1] for row in db.execute("PRAGMA table_info(session_polls)")}:
db.execute("ALTER TABLE session_polls ADD COLUMN vote_target INTEGER")
db.commit()
def active_session(guild_id: int):
return db.execute(
"SELECT id, host_id, server_name, join_code, description, status, channel_id, message_id, created_at "
"FROM sessions WHERE guild_id = ? AND status = 'active'", (guild_id,)
).fetchone()
def session_embed(session):
session_id, host_id, server_name, join_code, description, status, _, _, created_at = session
count = db.execute("SELECT COUNT(*) FROM participants WHERE session_id = ?", (session_id,)).fetchone()[0]
embed = discord.Embed(
title=f"ERLC Session: {server_name}",
description=description or "Join the session using the code below!",
color=discord.Color.green() if status == "active" else discord.Color.red(),
timestamp=datetime.fromisoformat(created_at),
)
embed.add_field(name="Status", value=status.title(), inline=True)
embed.add_field(name="Host", value=f"<@{host_id}>", inline=True)
embed.add_field(name="Attending", value=str(count), inline=True)
embed.add_field(name="Private server code", value=join_code, inline=False)
embed.set_footer(text=f"Session #{session_id}")
return embed
class SessionView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
async def update_attendance(self, interaction: discord.Interaction, joining: bool):
if interaction.guild_id is None or interaction.message is None:
await interaction.response.send_message("This button only works in a server.", ephemeral=True)
return
session = active_session(interaction.guild_id)
if not session or session[7] != interaction.message.id:
await interaction.response.send_message("This session is no longer active.", ephemeral=True)
return
if joining:
cursor = db.execute("INSERT OR IGNORE INTO participants VALUES (?, ?)", (session[0], interaction.user.id))
message = "You're marked as attending!" if cursor.rowcount else "You're already attending."
else:
cursor = db.execute("DELETE FROM participants WHERE session_id = ? AND user_id = ?", (session[0], interaction.user.id))
message = "You've left the attendance list." if cursor.rowcount else "You weren't on the attendance list."
db.commit()
await interaction.response.send_message(message, ephemeral=True)
try:
await interaction.message.edit(embed=session_embed(session), view=self)
except discord.HTTPException:
log.exception("Could not update session announcement")
@discord.ui.button(label="Join", style=discord.ButtonStyle.success, custom_id="erlc_session:join")
async def join(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.update_attendance(interaction, True)
@discord.ui.button(label="Leave", style=discord.ButtonStyle.secondary, custom_id="erlc_session:leave")
async def leave(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.update_attendance(interaction, False)
def vote_embed(message_id: int, host_id: int, description: str, vote_target: int | None = None):
counts = dict(db.execute(
"SELECT choice, COUNT(*) FROM session_votes WHERE message_id = ? GROUP BY choice",
(message_id,),
).fetchall())
embed = discord.Embed(
title="ERLC Session Vote",
description=description or "Would you attend an ERLC session?",
color=discord.Color.blue(),
)
yes_count = counts.get("yes", 0)
embed.add_field(name="Yes", value=f"{yes_count} / {vote_target}" if vote_target else str(yes_count))
embed.add_field(name="No", value=str(counts.get("no", 0)))
embed.set_footer(text=f"Started by {host_id} • You can change your vote")
return embed
class SessionVoteView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
async def cast_vote(self, interaction: discord.Interaction, choice: str):
if interaction.guild_id is None or interaction.message is None:
await interaction.response.send_message("This vote only works in a server.", ephemeral=True)
return
poll = db.execute(
"SELECT host_id, description, vote_target FROM session_polls WHERE message_id = ? AND guild_id = ?",
(interaction.message.id, interaction.guild_id),
).fetchone()
if not poll:
await interaction.response.send_message("This vote is no longer available.", ephemeral=True)
return
db.execute(
"INSERT INTO session_votes (message_id, user_id, choice) VALUES (?, ?, ?) "
"ON CONFLICT(message_id, user_id) DO UPDATE SET choice = excluded.choice",
(interaction.message.id, interaction.user.id, choice),
)
db.commit()
await interaction.response.edit_message(embed=vote_embed(interaction.message.id, *poll), view=self)
@discord.ui.button(label="Yes", style=discord.ButtonStyle.success, custom_id="erlc_vote:yes")
async def yes(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.cast_vote(interaction, "yes")
@discord.ui.button(label="No", style=discord.ButtonStyle.danger, custom_id="erlc_vote:no")
async def no(self, interaction: discord.Interaction, button: discord.ui.Button):
await self.cast_vote(interaction, "no")
class SessionBot(commands.Bot):
async def setup_hook(self):
self.add_view(SessionView())
self.add_view(SessionVoteView())
synced = await self.tree.sync()
log.info("Synced global slash commands: %s", ", ".join(command.name for command in synced))
async def on_ready(self):
log.info("Logged in as %s", self.user)
print("KODARI_READY", flush=True)
bot = SessionBot(command_prefix="!", intents=discord.Intents.default())
session_group = app_commands.Group(name="session", description="Manage ERLC roleplay sessions", guild_only=True)
@session_group.command(name="vote", description="Start a vote for an ERLC session")
@app_commands.checks.has_permissions(manage_guild=True)
@app_commands.describe(number_of_votes="Number of yes votes needed", description="Details about the proposed session")
async def vote(interaction: discord.Interaction, number_of_votes: app_commands.Range[int, 1], description: app_commands.Range[str, 1, 1000]):
if not interaction.app_permissions.mention_everyone:
await interaction.response.send_message("I need the Mention @everyone, @here, and All Roles permission in this channel to ping everyone.", ephemeral=True)
return
await interaction.response.defer(ephemeral=True)
try:
message = await interaction.channel.send(
content="@everyone",
embed=vote_embed(0, interaction.user.id, description, number_of_votes),
allowed_mentions=discord.AllowedMentions(everyone=True, users=False, roles=False),
)
db.execute(
"INSERT INTO session_polls (message_id, guild_id, host_id, description, vote_target) VALUES (?, ?, ?, ?, ?)",
(message.id, interaction.guild_id, interaction.user.id, description, number_of_votes),
)
db.commit()
await message.edit(view=SessionVoteView())
except discord.HTTPException:
log.exception("Could not post session vote")