frosyu

I want to make a discord bot out of sessions in roblox erlc

Kodari AI
KodariNov 9 at 11:08 pm 1
ERLCDiscordBot
Creates a Discord bot that integrates with Roblox ERLC (Emergency Response: Liberty County) game sessions. The bot connects to ERLC game servers via their API, allowing Discord users to view live server status, player counts, and active emergency calls. Features include command-based queries for server information, automated role assignment for verified players, and real-time notifications for server events like new dispatches or player joins. The bot uses Discord.js for interaction handling and REST API calls to ERLC servers, with configurable server connection settings and permission-based command access.

This is a Minecraft plugin project. Kodari supports Discord bots, so you can build your ERLC sessions bot in a Discord bot project.

Switch to Discord bot

frosyu

Token <redacted>

Kodari AI
KodariNov 9 at 11:14 pm 2

I’ll build a slash-command ERLC session manager with persistent session records, announcements, and join/leave buttons. The token you posted is exposed; reset it in the Discord Developer Portal and use the new token in .env.

Built an ERLC session bot with /session start, end, status, and attendees, plus persistent join/leave buttons. Starting and ending sessions requires Manage Server permission.

Reset the exposed token, then put the new one in .env. The bot tracks Discord attendance; it does not connect to ERLC or verify in-game players.

frosyu

Can you make a dexcription for the session start?

Kodari AI
KodariNov 9 at 11:28 pm 1

Yes—when you use /session start, fill in the optional description field. It appears in the session announcement.

Example: “Patrol session starting now! Join the private server and follow staff instructions.”

frosyu

Add session vote

Kodari AI
KodariNov 9 at 11:33 pm 1
  • Add /session vote to post a session-interest poll.

  • Keep votes and buttons working across bot restarts.

Added /session vote with an optional description and Yes/No buttons. Members can change their vote, and votes persist across restarts. Posting a vote requires Manage Server permission.

frosyu

make it alwasy ping everyone

Kodari AI
KodariNov 9 at 11:33 pm 1

I’ll add an @everyone ping to each new session vote.

Session votes now ping @everyone. The bot needs the Mention @everyone, @here, and All Roles permission in the channel.

frosyu

add /session vote and then options are number of votes and then description

Kodari AI
KodariNov 10 at 11:18 pm 1

The generation was stopped before any content could be produced.

frosyu

when session starts make sure to ping everyone

Kodari AI
KodariNov 10 at 11:20 pm 1

Session start announcements now ping @everyone. The bot needs permission to mention @everyone in the channel.

frosyu

try now

Kodari AI
KodariNov 10 at 11:22 pm 1

I’ll add a vote target and description to /session vote, while keeping the @everyone ping.

/session vote now requires a number of yes votes and a description. The poll shows progress toward the target and still pings @everyone.

frosyu

i cant see sesion vote in commands list and it dosent ping @everyone

Kodari AI
KodariNov 10 at 11:24 pm 1
  1. Make command sync visible in the bot logs.

  2. Warn when Discord channel permissions prevent the @everyone ping.

Updated the bot to log slash-command sync and warn you if it lacks permission to ping @everyone.

Restart the bot, then look for /session vote under /session. Global commands can take time to appear. For the ping, grant the bot Mention @everyone, @here, and All Roles in the announcement channel.

frosyu
Kodari AI
KodariNov 10 at 11:32 pm 1

Discord is showing an outdated version of /session start. The bot already syncs its commands when it starts.

Restart the bot and check its logs for “Synced global slash commands”, then wait a few minutes and select /session start again from the command list. Global command updates can take time to propagate. If it still happens after an hour, share the startup logs.

Kodari can make mistakes. Review important code before using.
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")