._venuzdonoa

Roblox Verification & Discord Nickname System

  1. Verification Setup Command

Create a single slash command:

"/setup-verify"

When an administrator executes this command, the bot must start an interactive setup process.

Setup Process

  1. Ask the administrator which Discord channel should receive the verification panel.
  2. Allow the administrator to select a channel using a Discord channel selector.
  3. Display the current configuration, including:

- Roblox Community ID - Verification Channel ID - Basic Discord Role ID - Army Discord Role IDs - Roblox Role IDs - Discord Role IDs - Rank mappings - Position mappings

  1. Allow administrators to edit, replace, or update any configured ID.
  2. Allow administrators to add or remove Roblox Role ID and Discord Role ID mappings.
  3. Provide a confirmation button before saving changes.
  4. Save all settings permanently so they remain after bot restarts.
  5. Send the verification panel to the selected channel after setup is confirmed.

Default Configuration Behavior

When an administrator runs "/setup-verify", the bot must automatically load all predefined default IDs.

  • If the administrator does not change any IDs, use all predefined default values.
  • If the administrator changes an ID, use the newly configured value.
  • Allow administrators to modify individual IDs without affecting other settings.
  • If an ID field is left empty, retain its existing value.
  • Provide a "Use Default Settings" button to restore all original default IDs.
  • Provide a "Confirm & Save" button to save the configuration.
  • Display the final configuration before confirmation.
  • Do not require administrators to manually enter IDs that are already predefined.

Running "/setup-verify" without making any ID changes must work immediately using the predefined configuration.

  1. Automatic Discord Nickname System

After successful Roblox verification, the bot must automatically change the member's Discord nickname according to their actual Roblox rank and position.

Nickname Format

"{Rank Classification}, {Rank Abbreviation} {Position Abbreviation} | {Roblox Username}"

Example

"OF-9, GEN COS | Player123"

Meaning:

  • "OF-9" = Officer Rank Classification.
  • "GEN" = Rank Abbreviation (General).
  • "COS" = Position Abbreviation (Chief of Staff).
  • "{Roblox Username}" = Actual Roblox Username.

Rank Classification

Use the following classifications according to the configured Roblox Role ID mapping:

  • OF-10
  • OF-9
  • OF-8
  • OF-7
  • OF-5
  • OF-4
  • OF-3
  • OF-2
  • OF-1b
  • OF-1a
  • OR-8
  • OR-7
  • OR-6
  • OR-5
  • OR-4
  • OR-3
  • OR-D
  • OR-1

Nickname Requirements

  1. All nickname text must be in English.
  2. Rank abbreviations must not exceed 4 letters.
  3. Position abbreviations must not exceed 4 letters.
  4. Automatically determine the correct rank classification from the member's Roblox Role ID.
  5. Automatically determine the correct rank abbreviation from the member's Roblox rank.
  6. Automatically determine the correct position abbreviation from the member's assigned Roblox position.
  7. Use the actual Roblox username, not the display name.
  8. Preserve all commas, spaces, and separators exactly as specified.
  9. Never remove or replace the comma after the rank classification.
  10. Never invent rank or position abbreviations.
  11. If no position is assigned, leave the position field empty while preserving the nickname format.
  12. Automatically update the Discord nickname whenever the member's Roblox rank or position changes.
  13. Apply the nickname immediately after successful verification.
  14. If the bot cannot change the nickname, report the error clearly.
  1. Integration Requirements
  • Integrate the verification system and nickname system into one bot.
  • Use the Roblox Community ID "846660383" as the default Community ID.
  • Use all predefined Roblox Role IDs and Discord Role IDs provided in the configuration.
  • Use the default IDs unless an administrator changes them through "/setup-verify".
  • Apply configuration changes automatically to both verification and nickname systems.
  • Store configuration persistently using a database.
  • Restrict "/setup-verify" to authorized administrators.
  • Validate all IDs before saving.
  • Never generate, guess, or invent IDs.
  • Handle Roblox API errors and Discord permission errors properly.

Important: The bot must be fully functional, not a static demonstration. All buttons, dropdown menus, modals, verification checks, role assignments, nickname updates, and configuration changes must work correctly.

Kodari AI
KodariTue at 12:43 am 3
RobloxVerifyNickname
A Discord bot that verifies Roblox users and automatically updates their Discord nicknames based on their Roblox rank and position. Features an interactive /setup-verify command with channel selection, ID configuration, and persistent storage. The bot maps Roblox Role IDs to rank classifications and abbreviations, then formats nicknames as "OF-9, GEN COS | Username". Includes default configuration, validation, error handling, and automatic nickname updates when ranks change.

I’ll build the setup panel, Roblox ownership verification, persistent configuration and automatic role/nickname updates. The only default ID supplied is the community ID, so the other IDs and rank mappings will need to be configured before verification can apply them.

Built the verification bot with persistent SQLite settings, Roblox profile ownership checks, role synchronization, and nickname updates every five minutes.

Set DISCORD_TOKEN in .env, then run /setup-verify as an administrator. The community ID defaults to 846660383; no other predefined IDs were supplied, so those and the rank mappings must be entered before they can be applied.

Position mappings use Roblox roles in the configured community. Grant the bot Manage Roles and Manage Nicknames, and place its Discord role above the roles and members it needs to manage.

Kodari can make mistakes. Review important code before using.
Files
bot.py
requirements.txt
Code
2 439
bot.py
import asyncio
import copy
import io
import json
import logging
import os
import re
import secrets
import sqlite3
import time

import aiohttp
import discord
from discord import app_commands
from discord.ext import commands, tasks
from dotenv import load_dotenv

load_dotenv()
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("verify")

DEFAULTS = {
    "community_id": "846660383",
    "channel_id": "",
    "basic_role_id": "",
    "army_role_ids": [],
    "role_mappings": {},
    "rank_mappings": {},
    "position_mappings": {},
}
CLASSIFICATIONS = {"OF-10", "OF-9", "OF-8", "OF-7", "OF-5", "OF-4", "OF-3", "OF-2", "OF-1b", "OF-1a", "OR-8", "OR-7", "OR-6", "OR-5", "OR-4", "OR-3", "OR-D", "OR-1"}
ID = re.compile(r"^[1-9][0-9]{0,19}$")
ABBR = re.compile(r"^[A-Za-z]{1,4}$")

db = sqlite3.connect("verification.sqlite3")
db.execute("CREATE TABLE IF NOT EXISTS settings (guild_id INTEGER PRIMARY KEY, data TEXT NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS verified (guild_id INTEGER NOT NULL, discord_id INTEGER NOT NULL, roblox_id TEXT NOT NULL, managed_roles TEXT NOT NULL DEFAULT '[]', PRIMARY KEY(guild_id, discord_id), UNIQUE(guild_id, roblox_id))")
db.commit()


def get_config(guild_id):
    row = db.execute("SELECT data FROM settings WHERE guild_id = ?", (guild_id,)).fetchone()
    return json.loads(row[0]) if row else copy.deepcopy(DEFAULTS)


def check_id(value, label, required=True):
    if not value and not required:
        return
    if not isinstance(value, str) or not ID.fullmatch(value):
        raise ValueError(f"{label} must be a positive numeric ID.")


def validate_config(config, guild):
    check_id(config["community_id"], "Community ID")
    check_id(config["channel_id"], "Verification channel ID")
    channel = guild.get_channel(int(config["channel_id"]))
    if not isinstance(channel, discord.TextChannel):
        raise ValueError("Choose a text channel in this server.")
    check_id(config["basic_role_id"], "Basic role ID", False)
    if not isinstance(config["army_role_ids"], list):
        raise ValueError("Army role IDs must be a JSON array of ID strings.")
    discord_ids = list(config["army_role_ids"])
    if config["basic_role_id"]:
        discord_ids.append(config["basic_role_id"])
    for key in ("role_mappings", "rank_mappings", "position_mappings"):
        if not isinstance(config[key], dict):
            raise ValueError(f"{key} must be a JSON object.")
        for role_id in config[key]:
            check_id(role_id, "Roblox role ID")
    for role_ids in config["role_mappings"].values():
        if not isinstance(role_ids, list):
            raise ValueError("Each role mapping must contain an array of Discord role ID strings.")
        discord_ids.extend(role_ids)
    for role_id in discord_ids:
        check_id(role_id, "Discord role ID")
        role = guild.get_role(int(role_id))
        if role is None or role.is_default() or role.managed:
            raise ValueError(f"Discord role {role_id} does not exist or cannot be assigned.")
        if guild.me and role >= guild.me.top_role:
            raise ValueError(f"Discord role {role_id} must be below the bot's highest role.")
    for rank in config["rank_mappings"].values():
        if not isinstance(rank, dict) or set(rank) != {"classification", "abbreviation"} or rank["classification"] not in CLASSIFICATIONS or not isinstance(rank["abbreviation"], str) or not ABBR.fullmatch(rank["abbreviation"]):
            raise ValueError("Each rank mapping needs a valid classification and a 1–4 letter English abbreviation.")
    for position in config["position_mappings"].values():
        if not isinstance(position, str) or not ABBR.fullmatch(position):
            raise ValueError("Position abbreviations must be 1–4 English letters.")


async def api_json(method, url, **kwargs):
    async with bot.http_session.request(method, url, timeout=aiohttp.ClientTimeout(total=15), **kwargs) as response:
        if response.status != 200:
            raise RuntimeError(f"Roblox API returned HTTP {response.status}. Please try again later.")
        return await response.json()


async def roblox_roles(user_id):
    data = await api_json("GET", f"https://groups.roblox.com/v1/users/{user_id}/groups/roles")
    return data.get("data", [])


def config_file(config):
    data = json.dumps(config, indent=2, ensure_ascii=True).encode()
    return discord.File(io.BytesIO(data), filename="configuration.json")


def setup_text(config):
    return ("**Verification configuration** — the attached JSON shows every current ID and mapping. "
            "Select a channel, edit any settings, then confirm. Empty modal fields retain their values.\n"
            f"Community: `{config['community_id']}` · Channel: `{config['channel_id'] or 'not selected'}`\n"
            "Mappings use Roblox role ID keys. Rank: `{'classification': 'OF-9', 'abbreviation': 'GEN'}`; "
            "position: abbreviation; Discord roles: array of IDs. Use JSON with double quotes.")


class CoreModal(discord.ui.Modal, title="Edit IDs"):
    community = discord.ui.TextInput(label="Roblox Community ID", required=False, max_length=20)
    basic = discord.ui.TextInput(label="Basic Discord Role ID", required=False, max_length=20)
    army = discord.ui.TextInput(label="Army Discord Role IDs (JSON array)", required=False, style=discord.TextStyle.paragraph, max_length=2000)

    def __init__(self, view):
        super().__init__()
        self.setup_view = view

    async def on_submit(self, interaction):
        config = copy.deepcopy(self.setup_view.config)
        try:
            if self.community.value.strip():
                config["community_id"] = self.community.value.strip()
            if self.basic.value.strip():
                config["basic_role_id"] = self.basic.value.strip()
            if self.army.value.strip():
                config["army_role_ids"] = json.loads(self.army.value)
            check_id(config["community_id"], "Community ID")
            check_id(config["basic_role_id"], "Basic role ID", False)
            if not isinstance(config["army_role_ids"], list):
                raise ValueError("Army roles must be a JSON array.")
            for role_id in config["army_role_ids"]:
                check_id(role_id, "Army role ID")
        except (ValueError, TypeError) as exc:
            await interaction.response.send_message(f"Invalid input: {exc}", ephemeral=True)
            return
        self.setup_view.config = config
        await self.setup_view.refresh(interaction)


class MappingModal(discord.ui.Modal):
    data = discord.ui.TextInput(label="Full JSON object (empty keeps existing)", required=False, style=discord.TextStyle.paragraph, max_length=4000)

    def __init__(self, view, key, title):
        super().__init__(title=title)
        self.setup_view = view
        self.key = key
        current = json.dumps(view.config[key], ensure_ascii=True)
        if len(current) <= 4000:
            self.data.default = current

    async def on_submit(self, interaction):
        if self.data.value.strip():
            try:
                value = json.loads(self.data.value)
                if not isinstance(value, dict):
                    raise ValueError("Expected a JSON object.")
            except (ValueError, TypeError) as exc:
                await interaction.response.send_message(f"Invalid mapping: {exc}", ephemeral=True)
                return
            self.setup_view.config[self.key] = value
        await self.setup_view.refresh(interaction)


class ChannelSelect(discord.ui.ChannelSelect):
    def __init__(self):
        super().__init__(placeholder="Select the verification channel", channel_types=[discord.ChannelType.text])

    async def callback(self, interaction):
        self.view.config["channel_id"] = str(self.values[0].id)
        await self.view.refresh(interaction)


class SetupView(discord.ui.View):
    def __init__(self, owner_id, config):
        super().__init__(timeout=900)
        self.owner_id = owner_id
        self.config = config
        self.add_item(ChannelSelect())

    async def interaction_check(self, interaction):
        if interaction.user.id != self.owner_id or not interaction.user.guild_permissions.administrator:
            await interaction.response.send_message("Only the administrator who started setup can use this panel.", ephemeral=True)
            return False
        return True

    async def refresh(self, interaction):
        await interaction.response.edit_message(content=setup_text(self.config), attachments=[config_file(self.config)], view=self)

    @discord.ui.button(label="Edit IDs", style=discord.ButtonStyle.primary, row=1)
    async def edit_ids(self, interaction, button):
        await interaction.response.send_modal(CoreModal(self))

    @discord.ui.button(label="Discord role mappings", row=1)
    async def roles(self, interaction, button):
        await interaction.response.send_modal(MappingModal(self, "role_mappings", "Discord role mappings"))