Bot Studio & Hosting

Discord bot hosting

Build a Discord bot.
Or bring your own.

Try your bot in the sample server below, or set up a free ticket desk in your own Discord. You run the starter on your computer. Hosted plans open later.

Choose your bot icon
Try features to add them to your bot

In your build Welcome

SparkBot

APP

Night Shift Sample server

Simulation

Discord activity

1 event
  1. SparkBotin #welcome

    Welcome aboard, @Mara.

    Gave Mara the Member role and pointed her to #rules.

Ready for a test event.
Set up a free ticket botOpen full workbench

Already have a bot? Bring your code. Hosting checkout opens later.

How setup works

From an idea to your server.

Try a bot here, or set up the free ticket desk in a Discord server you manage. Hosted plans are in preview.

Pick the jobs your bot handles.

Add tickets, welcome messages, roles or reminders. You can edit a reply and test what your members would see.

Open the workbench

Use a Discord application you own.

Name your bot in Discord. The starter opens the server picker. Then choose the channel for the ticket button and the role that handles requests.

See the Discord setup guide

Close your laptop. Keep your bot.

Planned hosting keeps one bot online with a dedicated memory allowance and daily backups. Review the limits before choosing a plan.

Compare hosting plans

Proposed hosting plans

One bot. Your choice of features.

Every plan uses the same library. Choose how many features you’ll run and how much memory your bot needs.

Starter fits up to 3 features.

3

Starter

$4.99 / month

Any 3 features · 512 MiB memory

3-day backup history

Choose Starter

Plus

$9.99 / month

Any 6 features · 1 GiB memory

7-day backup history

Choose Plus

Pro

$19.99 / month

Any 10 features · 2 GiB memory

14-day backup history

Choose Pro

At launch, each eligible account can try one Starter bot for 30 days. No card or automatic billing. Explore the trial

Free Discord ticket bot

Take the bot with you.

Give members a private channel with your support team. Download the Python source and run it on your computer using your own Discord application.

Inside the ZIP

6 files · 11.4 KiB
START-HERE.txtConnect your Discord app
RBDhub Ticket Desk
Set up one private-ticket bot for a Discord server you manage.

Open the step-by-step walkthrough on the computer that will run the bot:
https://rbdhub.com/get-a-bot/starter/#run
It shows one step at a time and remembers your place in that browser.

1. Create a new application at https://discord.com/developers/applications and name it.
   In Installation, enable Guild Install. On the Bot page, choose Reset Token and copy it.
   You do not need Administrator, privileged intents or Developer Mode.

2. Extract every file into one folder. Use Python 3.10 or newer.
   Windows: double-click Start Ticket Desk.cmd, or run py -3 start.py.
   macOS / Linux: open a terminal in the extracted folder and run python3 start.py.
   Press Enter at an empty token prompt for help creating your bot.
   Paste the token at the hidden local prompt. Use the Discord window that opens
   to authorize Add to Server. Return to the launcher and confirm the server by name.
   Already installed? Pick the server from the list. On a headless machine, open
   the printed link in a browser. The bot stays online while this program runs.

3. In Discord, send /setup. In its private picker, choose the channel and staff role,
   then press Post ticket desk. The private confirmation links to the posted panel.
   Repeating setup in the same channel updates its panel. Try the button, then use
   /resolve in the private ticket. The conversation stays in the resolved channel.

Optional: run /workbench in Discord to open the RBDhub feature editor with channels
you and the bot can post in. Customize the ticket panel, download its settings file,
then attach it to /setup in Discord. You can override the channel and role in the command.
A starter downloaded from the feature editor includes its replies in ticket-settings.json.
Only server managers can share a directory or post a panel. Keep the directory within
your team. Local role and channel choices are rechecked by the bot when you post.
Existing /desk commands still work in the current channel.

Use a dedicated application. Keep the token on your computer. Server and panel choices
are kept in ticket-desk.sqlite3 next to the starter. Keep this file when upgrading or
moving the bot. Run a single copy per application. To run unattended, supply DISCORD_TOKEN
through your local environment. Set DISCORD_GUILD_ID only to explicitly select another
installed server. For the illustrated setup guide visit https://rbdhub.com/get-a-bot/starter/
Start Ticket Desk.cmdWindows launcher
@echo off
setlocal
cd /d "%~dp0"
where py >nul 2>nul
if errorlevel 1 goto python
py -3 start.py
goto done
:python
where python >nul 2>nul
if errorlevel 1 goto missing
python start.py
goto done
:missing
echo Install Python 3.10 or newer from https://www.python.org/downloads/ and open this file again.
:done
pause
onboarding.pyChoose a server and save settings
"""Local setup for one customer-owned Discord application."""
import asyncio
import getpass
import json
import re
import sqlite3
import sys
import webbrowser
from urllib.parse import urlencode

import discord


GUIDE = "https://rbdhub.com/get-a-bot/starter/"


def prompt_token(*, ask=getpass.getpass, browse=webbrowser.open, interactive=None):
    if interactive is None:
        interactive = sys.stdin.isatty()
    if not interactive:
        raise SystemExit("Open the starter in a terminal, or set DISCORD_TOKEN for unattended use.")
    print("Need a bot token? Press Enter at the empty prompt to open the setup walkthrough.")
    opened = False
    while True:
        try:
            token = ask("Paste the bot token from Discord (hidden on this computer): ").strip()
        except (EOFError, KeyboardInterrupt):
            raise SystemExit("Setup closed. Open the launcher again to continue.") from None
        if token:
            return token
        print("Create your Discord application, then return to this window to enter its token.\n" + GUIDE + "#create-app")
        if not opened:
            opened = True
            try:
                browse(GUIDE + "#create-app")
            except (OSError, webbrowser.Error):
                pass  # The printed link works from a different browser.


def snowflake(value):
    return isinstance(value, str) and re.fullmatch(r"[1-9][0-9]{16,19}", value) and int(value) < 2**64


class DeskState:
    """Only server choices, posted panel IDs and their display settings go on disk."""
    def __init__(self, path):
        self.db = sqlite3.connect(path)
        self.db.executescript("""
            CREATE TABLE IF NOT EXISTS binding (app TEXT PRIMARY KEY, guild TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS panel (
                app TEXT, guild TEXT, channel TEXT, message TEXT NOT NULL, config TEXT NOT NULL,
                PRIMARY KEY (app, guild, channel)
            );
        """)

    def guild_for(self, app):
        row = self.db.execute("SELECT guild FROM binding WHERE app=?", (str(app),)).fetchone()
        return int(row[0]) if row else None

    def bind(self, app, guild):
        with self.db:
            self.db.execute("INSERT OR REPLACE INTO binding VALUES (?,?)", (str(app), str(guild)))

    def panel(self, app, guild, channel):
        row = self.db.execute("SELECT message, config FROM panel WHERE app=? AND guild=? AND channel=?",
                              tuple(map(str, (app, guild, channel)))).fetchone()
        return (int(row[0]), json.loads(row[1])) if row else (None, {})

    def save_panel(self, app, guild, channel, message, config):
        with self.db:
            self.db.execute("INSERT OR REPLACE INTO panel VALUES (?,?,?,?,?)",
                            (*map(str, (app, guild, channel, message)), json.dumps(config)))


def install_url(app_id):
    return "https://discord.com/oauth2/authorize?" + urlencode({
        "client_id": str(app_id), "scope": "bot applications.commands",
        "permissions": "68624", "integration_type": "0",
    })


async def choose_server(client, preferred, *, ask=input, browse=webbrowser.open, interactive=None):
    app_id = client.application_id
    saved = client.state.guild_for(app_id)
    if interactive is None:
        interactive = sys.stdin.isatty()
    url = install_url(app_id)

    async def servers():
        return sorted([g async for g in client.fetch_guilds(limit=None, with_counts=False)],
                      key=lambda g: (g.name.casefold(), g.id))

    guilds = await servers()
    if preferred:
        if any(g.id == preferred for g in guilds):
            return preferred
        raise RuntimeError(f"The bot is not installed in DISCORD_GUILD_ID. Install it here and restart: {url}")
    if saved and any(g.id == saved for g in guilds):
        return saved
    if not interactive:
        raise RuntimeError("Run the starter in a terminal to choose your server, or set DISCORD_GUILD_ID.")

    while True:
        if guilds:
            print("\nWhich server should run this ticket desk?")
            for index, guild in enumerate(guilds, 1):
                print(f"  {index}. {guild.name} ({guild.id})")
            prompt = "Press Enter for the only server, " if len(guilds) == 1 else ""
            answer = (await asyncio.to_thread(ask, prompt + "pick a number, or type + to add another: ")).strip()
            if not answer and len(guilds) == 1:
                answer = "1"
            if answer.isascii() and answer.isdigit() and len(answer) <= 6 and 1 <= int(answer) <= len(guilds):
                return guilds[int(answer) - 1].id
            if answer != "+":
                continue
        print("\nIn Discord, choose Add to Server and authorize your own bot.\n" + url)
        try:
            await asyncio.to_thread(browse, url)
        except (OSError, webbrowser.Error):
            pass  # A headless machine can use the printed link.
        await asyncio.to_thread(ask, "After authorizing in Discord, press Enter here to refresh the server list. ")
        guilds = await servers()
        if not guilds:
            print("Discord has not listed an installation yet. Make sure you chose Add to Server.")


DEFAULTS = {
    "title": "Need a hand?",
    "message": "Use {trigger} to open a private channel with {role}.",
    "button": "Open a ticket",
    "prefix": "ticket",
    "opening": "Hi {member}. You’re in {room}. Someone from {role} will be with you shortly.",
    "followup": "You already have a ticket, {member}. Pick up the conversation in {room}.",
}
LIMITS = {"title": 80, "message": 280, "button": 50, "prefix": 32, "opening": 200, "followup": 200}


def parse_preferences(raw, guild_id):
    if not isinstance(raw, dict) or type(raw.get("version")) is not int or raw["version"] != 1 or raw.get("kind") != "rbdhub.ticket-panel":
        raise ValueError("Attach the ticket settings JSON downloaded from the RBDhub workbench.")
    guild = raw.get("guild")
    if guild is not None and guild != str(guild_id):
        raise ValueError("Those settings belong to another server. Export this server’s settings or choose its channel and role directly.")
    for key in ("channel", "staff"):
        if key in raw and (not guild or not snowflake(raw[key])):
            raise ValueError("Choose the channel and staff role again in the workbench.")
    fields = raw.get("replies", {})
    if not isinstance(fields, dict):
        raise ValueError("The ticket settings file is missing its replies.")
    result = DEFAULTS.copy()
    for key, limit in LIMITS.items():
        if key in fields:
            value = fields[key]
            if not isinstance(value, str) or not value.strip() or len(value) > limit:
                raise ValueError(f"Check the {key} field in the workbench and download the settings again.")
            result[key] = value.strip()
    if not re.fullmatch(r"[a-z0-9][a-z0-9-]{0,31}", result["prefix"]):
        raise ValueError("Choose a ticket channel prefix with lowercase letters, numbers or hyphens.")
    return result, int(raw.get("channel", 0)), int(raw.get("staff", 0))


def render_reply(template, member, guild, channel, role, button):
    values = {"member": member.mention if member else "you", "server": guild.name, "channel": channel.mention,
              "bot": guild.me.display_name, "role": role.mention, "room": channel.mention if member else "your ticket",
              "trigger": button}
    return re.sub(r"\{([a-z]+)\}", lambda m: values.get(m[1], m[0]), template)[:1900]


def can_manage(interaction):
    guild, member, server = interaction.guild, interaction.user, interaction.client.server
    return bool(guild and server and guild.id == server.id and isinstance(member, discord.Member)
                and member.guild_permissions.manage_guild and interaction.permissions.manage_guild)


def can_post(channel, member, bot):
    if not isinstance(channel, discord.TextChannel) or channel.type != discord.ChannelType.text or bot is None:
        return False
    return all(p.view_channel and p.send_messages
               for p in (channel.permissions_for(member), channel.permissions_for(bot)))


def usable_role(role, guild):
    return role is not None and role.guild.id == guild.id and not role.is_default() and not role.managed


def directory(guild, member):
    channels = [[str(ch.id), ch.name, ch.category.name if ch.category else ""]
                for ch in guild.text_channels if can_post(ch, member, guild.me)]
    roles = [[str(role.id), role.name] for role in reversed(guild.roles) if usable_role(role, guild)]
    return {"version": 1, "kind": "rbdhub.discord-directory", "guild": [str(guild.id), guild.name],
            "channels": channels, "roles": roles}
start.pyInstall and start the bot
"""Create a project-local environment, then start the Discord ticket bot."""
from pathlib import Path
import os
import subprocess
import sys
import venv

base = Path(__file__).resolve().parent
if sys.version_info < (3, 10):
    raise SystemExit("Install Python 3.10 or newer from python.org, then run this file again.")
os.chdir(base)
env_dir = base / ".venv"
python = env_dir / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
if not python.exists():
    print("Preparing an environment for this bot…", flush=True)
    venv.EnvBuilder(with_pip=True).create(env_dir)
requirement = (base / "requirements.txt").read_text().strip()
version = requirement.removeprefix("discord.py==")
probe = subprocess.run([str(python), "-c", "from importlib.metadata import version; print(version('discord.py'))"],
                       capture_output=True, text=True)
if probe.stdout.strip() != version:
    subprocess.run([str(python), "-m", "pip", "install", "--requirement", "requirements.txt"], check=True)
raise SystemExit(subprocess.call([str(python), "bot.py"]))
bot.pyOpen and resolve tickets
"""A small, single-server Discord ticket desk. Run through start.py."""
import asyncio
import base64
from hashlib import blake2s
import io
import json
import os
import re
from pathlib import Path

import discord
from discord import app_commands

from onboarding import (DEFAULTS, GUIDE, DeskState, can_manage, can_post, choose_server, directory,
                        parse_preferences, prompt_token, render_reply, snowflake, usable_role)


def open_topic(bot_id, member_id, role_id):
    return f"rbdhub-ticket:{bot_id}:{member_id}:{role_id}:open"


def ticket_owner(topic, bot_id):
    parts = (topic or "").split(":")
    if len(parts) != 5 or parts[:2] != ["rbdhub-ticket", str(bot_id)] or parts[4] != "open":
        return None
    if not all(field.isascii() and field.isdecimal() for field in parts[2:4]):
        return None
    return int(parts[2]), int(parts[3])


def private_access(guild, member, staff):
    access = discord.PermissionOverwrite(view_channel=True, send_messages=True, read_message_history=True)
    return {
        guild.default_role: discord.PermissionOverwrite(view_channel=False),
        member: access,
        staff: access,
        guild.me: access,
    }


class OpenTicket(discord.ui.DynamicItem[discord.ui.Button], template=r"rbdhub:open:(?P<role>[0-9]{1,20})"):
    def __init__(self, role_id, label="Open a ticket"):
        self.role_id = role_id
        super().__init__(discord.ui.Button(label=label, style=discord.ButtonStyle.primary,
                                           custom_id=f"rbdhub:open:{role_id}"))

    @classmethod
    async def from_custom_id(cls, interaction, item, match: re.Match):
        return cls(int(match["role"]))

    async def callback(self, interaction):
        client, member, guild = interaction.client, interaction.user, interaction.guild
        if not guild or guild.id != client.server.id or not isinstance(member, discord.Member):
            await interaction.response.send_message("Open this panel inside the configured server.", ephemeral=True)
            return
        await interaction.response.defer(ephemeral=True, thinking=True)
        staff = guild.get_role(self.role_id)
        if not staff or staff.is_default() or staff.managed or guild.me is None:
            await interaction.followup.send("Ask a moderator to post a new /desk with a current staff role.", ephemeral=True)
            return
        _, custom = client.state.panel(client.user.id, guild.id, interaction.channel_id)
        config = {**DEFAULTS, **custom}
        async with client.ticket_lock:
            try:
                channels = await guild.fetch_channels()
                channel = None
                for candidate in channels:
                    if isinstance(candidate, discord.TextChannel):
                        owner = ticket_owner(candidate.topic, client.user.id)
                        if owner and owner[0] == member.id:
                            channel = candidate
                            break
                already_open = channel is not None
                if not already_open:
                    channel = await guild.create_text_channel(
                        f"{config['prefix']}-{member.id}", topic=open_topic(client.user.id, member.id, staff.id),
                        overwrites=private_access(guild, member, staff), reason="Member opened a support ticket",
                    )
                    try:
                        await channel.send(render_reply(config["opening"], member, guild, channel, staff, config["button"]))
                    except discord.HTTPException:
                        pass  # The private room exists and the member can still open it.
                message = (render_reply(config["followup"], member, guild, channel, staff, config["button"])
                           if already_open else f"Your private support channel is {channel.mention}. Use /resolve there when you’re finished.")
            except discord.Forbidden:
                message = "The bot needs Manage Channels, View Channels, Send Messages and Read Message History. Ask your server owner to check its permissions."
            except discord.HTTPException:
                message = "Discord couldn’t finish opening the ticket. Try the button again."
        await interaction.followup.send(message, ephemeral=True)


async def preferences(settings, guild_id):
    if settings:
        if settings.size > 16384 or not settings.filename.lower().endswith(".json"):
            raise ValueError("Attach the small ticket settings JSON from the RBDhub workbench.")
        data = await settings.read()
    else:
        bundled = Path(__file__).with_name("ticket-settings.json")
        if not bundled.is_file():
            return None, 0, 0
        if bundled.stat().st_size > 16384:
            raise ValueError("Download a fresh copy of your configured ticket bot from the workbench.")
        data = bundled.read_bytes()
    try:
        return parse_preferences(json.loads(data), guild_id)
    except (UnicodeError, json.JSONDecodeError):
        raise ValueError("The file could not be read. Download a fresh copy of the ticket settings from the workbench.") from None


async def post_panel(interaction, channel=None, staff=None, settings=None, prepared=None):
    if not can_manage(interaction):
        await interaction.response.send_message("A member with Manage Server can set up tickets in the configured server.", ephemeral=True)
        return
    await interaction.response.defer(ephemeral=True, thinking=True)
    guild, client = interaction.guild, interaction.client
    posted = False
    try:
        config, saved_channel, saved_staff = prepared or await preferences(settings, guild.id)
        target = channel or (guild.get_channel(saved_channel) if saved_channel else interaction.channel)
        if target is None or getattr(target, "guild", None) != guild or not can_post(target, interaction.user, guild.me):
            raise ValueError("Choose a text channel where both you and the bot can view and send messages.")
        perms = guild.me.guild_permissions
        if not all((perms.manage_channels, perms.view_channel, perms.send_messages, perms.read_message_history)):
            raise ValueError("Give the bot Manage Channels, View Channels, Send Messages and Read Message History so it can open private tickets.")
        if not target.permissions_for(guild.me).read_message_history:
            raise ValueError("Allow the bot to read message history in that channel so it can update its panel.")
        async with client.panel_lock:
            message_id, prior = client.state.panel(client.user.id, guild.id, target.id)
            prior_staff = prior.get("staff_id", 0)
            staff = staff or guild.get_role(saved_staff if settings else (prior_staff or saved_staff))
            if not usable_role(staff, guild):
                raise ValueError("Choose a staff role from this server. Leave out @everyone and roles controlled by apps.")
            if settings is None and prior:
                config = {**DEFAULTS, **prior}
            config = {**(config or DEFAULTS), "staff_id": staff.id}
            content = render_reply("**" + config["title"] + "**\n" + config["message"], None, guild, target, staff, config["button"])
            view = discord.ui.View(timeout=None)
            view.add_item(OpenTicket(staff.id, config["button"]))
            message = None
            if message_id:
                try:
                    message = await target.get_partial_message(message_id).edit(content=content, view=view)
                except discord.NotFound:
                    pass
            if message is None:
                nonce = blake2s(f"{target.id}:{message_id}".encode(), digest_size=10).hexdigest()
                message = await target.send(content, view=view, nonce=nonce)
            client.state.save_panel(client.user.id, guild.id, target.id, message.id, config)
        posted = True
        reply = f"Your ticket desk is ready in {target.mention}. {staff.mention} can see new tickets. [Open the panel](<{message.jump_url}>) and press its button to try a private ticket."
    except ValueError as error:
        reply = str(error)
    except discord.Forbidden:
        reply = "Discord denied the change. Check the bot’s channel permissions, then run /setup again."
    except discord.HTTPException:
        reply = "Discord could not confirm the change. Run /setup again in the same channel."
    await interaction.followup.send(reply, ephemeral=True)
    return posted


class SetupPicker(discord.ui.View):
    def __init__(self, origin, channel, staff, settings, prepared):
        super().__init__(timeout=300)
        self.origin, self.owner = origin, origin.user.id
        self.target, self.staff = channel, staff
        self.settings, self.prepared = settings, prepared
        self.update_fields()

    def update_fields(self):
        self.channel_field.default_values = [self.target] if self.target else []
        self.staff_field.default_values = [self.staff] if self.staff else []
        self.post.disabled = not (self.target and self.staff)

    def instructions(self):
        if not self.target:
            return "First, choose the text channel where members should see the ticket button."
        if not self.staff:
            return f"The button will go in {self.target.mention}. Next, choose the staff role that handles tickets."
        return (f"The button will go in {self.target.mention}. {self.staff.mention} will handle private tickets. "
                "Press **Post ticket desk** when you’re ready.")

    async def interaction_check(self, interaction):
        if interaction.user.id == self.owner and can_manage(interaction):
            return True
        await interaction.response.send_message("Open /setup as a server manager to make your own selection.", ephemeral=True)
        return False

    @discord.ui.select(cls=discord.ui.ChannelSelect, channel_types=[discord.ChannelType.text],
                       placeholder="Choose the channel for the ticket button", row=0)
    async def channel_field(self, interaction, select):
        target = interaction.guild.get_channel(select.values[0].id)
        if not can_post(target, interaction.user, interaction.guild.me):
            await interaction.response.send_message("Choose a channel where both you and the bot can post.", ephemeral=True)
            return
        self.target = target
        self.update_fields()
        await interaction.response.edit_message(content=self.instructions(), view=self)

    @discord.ui.select(cls=discord.ui.RoleSelect, placeholder="Choose the role that handles tickets", row=1)
    async def staff_field(self, interaction, select):
        staff = interaction.guild.get_role(select.values[0].id)
        if not usable_role(staff, interaction.guild):
            await interaction.response.send_message("Choose a staff role assigned to people in this server.", ephemeral=True)
            return
        self.staff = staff
        self.update_fields()
        await interaction.response.edit_message(content=self.instructions(), view=self)

    @discord.ui.button(label="Post ticket desk", style=discord.ButtonStyle.primary, row=2)
    async def post(self, interaction, button):
        guild = interaction.guild
        target = guild.get_channel(self.target.id) if self.target else None
        staff = guild.get_role(self.staff.id) if self.staff else None
        if not target or not staff:
            await interaction.response.send_message("That channel or role is no longer available. Choose another.", ephemeral=True)
            return
        if await post_panel(interaction, target, staff, self.settings, self.prepared):
            self.stop()
            await self.origin.edit_original_response(content="Ticket desk published. Your private confirmation links to the panel.", view=None)

    async def on_timeout(self):
        try:
            await self.origin.edit_original_response(content="This setup picker expired. Run /setup to open it again.", view=None)
        except discord.HTTPException:
            pass


@app_commands.command(name="setup", description="Choose a real channel and staff role and publish your ticket desk")
@app_commands.describe(channel="Channel for the button (defaults to this channel or your settings file)",
                       staff="The role that should see tickets; leave blank to choose in the private picker",
                       settings="Optional ticket settings JSON from the RBDhub workbench")
@app_commands.default_permissions(manage_guild=True)
async def setup(interaction: discord.Interaction, channel: discord.TextChannel | None = None,
                staff: discord.Role | None = None, settings: discord.Attachment | None = None):
    if channel and staff:
        await post_panel(interaction, channel, staff, settings)
        return
    if not can_manage(interaction):
        await interaction.response.send_message("A member with Manage Server can set up tickets in the configured server.", ephemeral=True)
        return
    await interaction.response.defer(ephemeral=True, thinking=True)
    guild, client = interaction.guild, interaction.client
    try:
        prepared = await preferences(settings, guild.id)
    except ValueError as error:
        await interaction.followup.send(str(error), ephemeral=True)
        return
    except discord.HTTPException:
        await interaction.followup.send("Discord couldn’t read that attachment. Try the settings file again.", ephemeral=True)
        return
    _, saved_channel, saved_staff = prepared
    target = channel or (guild.get_channel(saved_channel) if saved_channel else interaction.channel)
    if not can_post(target, interaction.user, guild.me):
        target = None
    prior = client.state.panel(client.user.id, guild.id, target.id)[1] if target else {}
    role = staff or guild.get_role(saved_staff if settings else (prior.get("staff_id") or saved_staff))
    picker = SetupPicker(interaction, target, role if usable_role(role, guild) else None, settings, prepared)
    await interaction.edit_original_response(content=picker.instructions(), view=picker)


@app_commands.command(name="desk", description="Post or update the ticket button in this channel")
@app_commands.describe(staff="The moderator role that should see private tickets")
@app_commands.default_permissions(manage_guild=True)
async def desk(interaction: discord.Interaction, staff: discord.Role):
    await post_panel(interaction, interaction.channel, staff)


@app_commands.command(name="workbench", description="Open your RBDhub feature editor with this server’s channels and staff roles")
@app_commands.default_permissions(manage_guild=True)
@app_commands.describe(channel="Optional: share only this channel, useful for a large server or an open draft")
async def workbench(interaction: discord.Interaction, channel: discord.TextChannel | None = None):
    if not can_manage(interaction):
        await interaction.response.send_message("Only a member with Manage Server can share this server’s channel list.", ephemeral=True)
        return
    data = directory(interaction.guild, interaction.user)
    if channel:
        data["channels"] = [row for row in data["channels"] if row[0] == str(channel.id)]
        if not data["channels"]:
            await interaction.response.send_message("Choose a channel where you and the bot can post.", ephemeral=True)
            return
        data["partial"] = True
        data["roles"] = []  # Pick the staff role inside Discord when publishing.
    payload = json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode()
    route = "https://rbdhub.com/get-a-bot/#discord"
    encoded = base64.urlsafe_b64encode(payload).decode().rstrip("=")
    if len(encoded) <= 1450:
        content = f"[Choose channels in the workbench](<{route}={encoded}>). For an open build, you can also import the attached file."
    else:
        content = f"[Open the workbench](<{route}>) and import the attached channel list."
    note = " This directory is for your team."
    try:
        await interaction.response.send_message(content + note,
                                               file=discord.File(io.BytesIO(payload), filename="rbdhub-discord.json"),
                                               ephemeral=True, suppress_embeds=True)
    except discord.Forbidden:
        fallback = (f"[Open the channel picker](<{route}={encoded}>)." + note if len(encoded) <= 1450 else
                    "Discord blocked the directory attachment. Run /workbench with just the channel you want to share.")
        await interaction.response.send_message(fallback, ephemeral=True, suppress_embeds=True)


@app_commands.command(name="resolve", description="Mark this ticket resolved and keep its conversation")
async def resolve(interaction: discord.Interaction):
    channel, client, member = interaction.channel, interaction.client, interaction.user
    owner = ticket_owner(getattr(channel, "topic", None), client.user.id)
    if (not interaction.guild or interaction.guild.id != client.server.id or not owner
            or not isinstance(channel, discord.TextChannel) or not isinstance(member, discord.Member)):
        await interaction.response.send_message("Use this command inside an open ticket.", ephemeral=True)
        return
    owner_id, role_id = owner
    if member.id != owner_id and not member.guild_permissions.manage_guild and not member.get_role(role_id):
        await interaction.response.send_message("Only the member or the support team can resolve this ticket.", ephemeral=True)
        return
    await interaction.response.defer(ephemeral=True, thinking=True)
    async with client.ticket_lock:
        try:
            await channel.edit(name=f"resolved-{channel.id}", topic=channel.topic.removesuffix(":open") + ":resolved",
                               reason="Ticket marked resolved")
            message = "Marked resolved. This private channel keeps the conversation."
        except discord.HTTPException:
            message = "Discord couldn’t update the channel. Check Manage Channels and try again."
    await interaction.followup.send(message, ephemeral=True)


class TicketBot(discord.Client):
    def __init__(self, guild_id=None, state=None):
        super().__init__(intents=discord.Intents(guilds=True), allowed_mentions=discord.AllowedMentions.none())
        self.preferred = guild_id
        self.server = None
        self.state = state or DeskState(Path(__file__).with_name("ticket-desk.sqlite3"))
        self.tree = app_commands.CommandTree(self)
        self.ticket_lock = asyncio.Lock()
        self.panel_lock = asyncio.Lock()

    async def setup_hook(self):
        if self.application.interactions_endpoint_url:
            raise RuntimeError("Use a fresh Discord application with an empty Interactions Endpoint URL for this starter.")
        self.server = discord.Object(id=await choose_server(self, self.preferred))
        self.add_dynamic_items(OpenTicket)
        commands = (setup, desk, workbench, resolve)
        existing = await self.tree.fetch_commands(guild=self.server)
        if any((cmd.name, cmd.type) not in {(c.name, discord.AppCommandType.chat_input) for c in commands} for cmd in existing):
            raise RuntimeError("This application has other server commands. Choose a dedicated Discord application for the starter.")
        for command in commands:
            self.tree.add_command(command, guild=self.server)
        await self.tree.sync(guild=self.server)
        self.state.bind(self.application_id, self.server.id)

    async def on_ready(self):
        guild = self.get_guild(self.server.id)
        if guild:
            print(f"{self.user} is online in {guild.name}. Open Discord, type /setup, then pick your channel and staff role.")
            print("Walk through posting your ticket button: " + GUIDE + "#post")
            print("Keep this window open to keep your bot online.")


if __name__ == "__main__":
    server = os.environ.get("DISCORD_GUILD_ID")
    if server and not snowflake(server):
        raise SystemExit("DISCORD_GUILD_ID must be a valid Discord server ID. Leave it unset to choose a server by name.")
    token = os.environ.get("DISCORD_TOKEN") or prompt_token()
    try:
        TicketBot(int(server) if server else None).run(token)
    except discord.LoginFailure:
        raise SystemExit("Discord rejected the token. Use the current token from your application’s Bot page.")
    except discord.Forbidden:
        raise SystemExit("Discord denied access. Enable Guild Install for this app and use the starter’s Add to Server link.")
    except RuntimeError as error:
        raise SystemExit(str(error))
requirements.txtDiscord library version
discord.py==2.7.1