Public
Discord ticket bot with dropdown, private threads, claim/close
botdiscordsqliteticketswebhook
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.

Discord ticket bot (dropdown → private thread)

A complete, working Discord ticket bot hosted on Val Town. Users pick a category from a dropdown with custom emojis and the bot creates a thread inside one support channel — never a new channel. Staff can claim, close, reopen and delete tickets, and every ticket is recorded in SQLite so it survives restarts.

Open the running val · Health & diagnostics

Why it is built this way

Val Town is a request-based runtime: each HTTP request gets a short-lived process, and there is no way to hold the persistent WebSocket gateway connection that discord.js and similar libraries need. Discord's HTTP interactions endpoint is therefore the supported architecture, and it is a first-class Discord feature. Consequences:

  • No gateway library. All Discord calls are plain fetch against https://discord.com/api/v10.
  • Signatures are verified on every request. Discord signs each interaction with Ed25519; the endpoint checks X-Signature-Ed25519 against the raw body before parsing it. Unsigned requests get 401 and never reach any handler.
  • Long work is deferred. Discord requires an acknowledgement within ~3 seconds or it shows "The application did not respond". Creating a thread, adding members and posting messages can exceed that, so the endpoint immediately returns a deferred ephemeral acknowledgement and hands the real work to a second, HMAC-signed request on the same val (Val Town's documented early-return pattern — there is no waitUntil). The user then sees the result when the deferred reply is edited.
Rendering mermaid diagram...

Files

FileRole
main.tsHTTP endpoint: signature verification, PING handshake, deferred dispatch, worker route, health page
config.tsAll configuration: env vars, categories, emoji markup parsing, message templates
verify.tsEd25519 interaction verification + HMAC signing/verification of internal jobs
discord.tsMinimal Discord REST client (rate-limit aware), permission bits, channel types
db.tsSQLite schema + queries; atomic duplicate-ticket guard
tickets.tsTicket lifecycle: open, claim, close, reopen, delete, transcripts
panel.tsPanel, ticket card and closing card builders; custom_id parsing
commands.tsSlash-command definitions and registration
types.tsThe Discord interaction payload subset used here
log.tsStructured JSON logging with secret redaction
scripts/setup.tsRegisters commands and posts the panel
scripts/discover-ids.tsPrints your server/channel/role ids
scripts/selftest.ts60 automated checks (crypto, parsing, DB, live credentials)

Quick start

1. Credentials

Already stored for this val as encrypted environment variables:

  • DISCORD_BOT_TOKEN — rotate this. The token was shared in plain text, so treat it as compromised: Discord Developer Portal → your app → Bot → Reset Token, then update the variable below.
  • DISCORD_PUBLIC_KEY — from General Information.
  • DISCORD_APPLICATION_ID — from General Information.

⚠️ Rotate DISCORD_BOT_TOKEN now: 👉 https://www.val.town/x/oplva9tkpco/discord-ticket-bot/environment-variables?key=DISCORD_BOT_TOKEN

2. Invite the bot

Use this URL (the permission integer is explained below):

https://discord.com/oauth2/authorize?client_id=1558392102923014255&scope=bot%20applications.commands&permissions=395137338368

3. Find your ids

Run the id discovery script from the val editor. It prints every server the bot is in, with the text channels you can use and your roles.

4. Configure

Set these environment variables (backticked names below are clickable links to the prefilled editor; the Required ones are the ones you must fill in):

VariableRequiredMeaning
DISCORD_GUILD_IDrecommendedYour server id. Commands then register instantly; without it they are global and can take up to an hour to appear.
TICKET_PARENT_CHANNEL_IDyesThe text channel that ticket threads are created inside.
TICKET_PANEL_CHANNEL_IDrecommendedWhere /ticket-setup posts the panel (you can also pass channel to the command).
TICKET_STAFF_ROLE_IDSyesComma-separated support role ids.
TICKET_LOG_CHANNEL_IDoptionalReceives ticket open/claim/close/delete logs (and transcripts).
TICKET_THREAD_PRIVACYoptionalprivate (default) or public.
TICKET_CLOSE_BEHAVIORoptionalarchive+lock (default), archive, lock, delete.
TICKET_MAX_OPEN_PER_USERoptionalDefault 1. Prevents duplicate tickets.
TICKET_NAME_FORMAToptionalDefault ticket-{username}-{category}. Placeholders: {username} {displayname} {category} {categoryLabel} {number} {id} {user} {server}.
TICKET_WELCOME_MESSAGEoptionalFirst message in the thread. Same placeholders, plus {status}.
TICKET_INSTRUCTIONSoptionalLine under the panel description.
TICKET_CATEGORIESoptionalJSON array that replaces the built-in categories — see below.
TICKET_PANEL_TITLE / _DESCRIPTION / _FOOTER / _PLACEHOLDERoptionalPanel text.
TICKET_PANEL_COLORoptionalDecimal colour, e.g. 5793266.
TICKET_PANEL_THUMBNAIL / _IMAGEoptionalImage URLs for the panel embed.
TICKET_THREAD_INVITABLEoptionalfalse (default). Whether regular members may invite others in.
TICKET_AUTO_ARCHIVE_MINUTESoptional60, 1440 (default), 4320 or 10080.
TICKET_ADD_STAFF_TO_THREADSoptionalfalse (default). See privacy below before enabling.
TICKET_MAX_STAFF_ADDEDoptionalCap on staff added per thread (default 10).
TICKET_STAFF_ALLOW_PERMISSIONSoptionaltrue (default): Administrator / Manage Threads also count as staff.
TICKET_CLAIM_MODEoptionalstaff (default) or anyone (owner may claim too).
TICKET_TRANSCRIPTSoptionalfalse (default). Save a .txt transcript to the log channel and blob storage.

5. Point Discord at this val

Discord Developer Portal → your application → General Information → Interactions Endpoint URL:

https://discord-ticket-bot.val.run/

Discord sends a signed PING immediately. If the endpoint verifies it, the URL saves; if not, you will get an error and a interaction.bad_signature entry in the val's logs.

6. Register commands and post the panel

Run the setup script, then in Discord use /ticket-setup (staff only) — optionally with a channel. The panel is a permanent message with the category dropdown.

Required Discord permissions

The invite link above requests exactly what the bot uses:

PermissionWhy
View Channelsee the panel and support channels
Send Messagespost the panel, replies and log entries
Embed Linksrender the ticket embeds
Read Message Historytranscripts and ticket history
Manage Threadsarchive, lock, reopen and unarchive threads
Send Messages in Threadstalk inside tickets
Create Private Threadsopen private ticket threads
Create Public Threadsopen public threads when TICKET_THREAD_PRIVACY=public
Use External Emojiscustom emojis hosted on another server

That is permission integer 395137338368, with the bot and applications.commands scopes.

Custom emojis on dropdown options

Both standard Unicode emojis and Discord custom-emoji markup are supported. Markup is parsed into a proper component emoji object ({ id, name, animated }) — it is never displayed as literal text:

// TICKET_CATEGORIES — the JSON array that defines the dropdown. [ { "value": "general", "label": "General Support", "description": "Questions about the server", "emoji": "🎫" // standard Unicode }, { "value": "billing", "label": "Billing Support", "description": "Payments, refunds and subscriptions", "emoji": "<:support:123456789012345678>" // custom emoji }, { "value": "report", "label": "Report a User", "description": "Privately report rule-breaking behaviour", "emoji": "<a:alert:987654321098765432>" // animated custom emoji } ]

Notes:

  • Copy a custom emoji's markup by typing \:name: in Discord.
  • Up to 25 options, matching Discord's select-menu limit.
  • value is the stable internal id stored on tickets; change label/description/emoji freely.
  • Custom emojis hosted on another server need the Use External Emojis permission.
  • To edit the built-in list in code instead, see DEFAULT_CATEGORIES in config.ts.

Ticket privacy — read this before claiming tickets are private

Tickets default to private threads (type: 12), created with POST /channels/{parent}/threads — never POST /guilds/{guild}/channels. Discord's rules for private threads, reproduced accurately:

A PRIVATE_THREAD is "only viewable by those invited and those with the MANAGE_THREADS permission".

So, concretely:

  • ✅ Regular members cannot see other people's tickets.
  • ✅ The ticket owner is explicitly added to the thread (PUT /channels/{thread}/thread-members/{user}). Creating a private thread adds nobody — not even its creator — so this step is required, and a failure here is reported to the user instead of leaving them with an invisible ticket.
  • ⚠️ Anyone holding Manage Threads on the parent channel can see every private thread in it. That is a Discord limitation, not a setting this bot can override. To make a ticket genuinely visible only to staff, make sure the staff role is the only role with Manage Threads on the support channel. If you grant Manage Threads to @everyone, "private" threads stop being private.
  • ⚠️ By default staff are not added as thread members; they reach tickets through Manage Threads (above). Setting TICKET_ADD_STAFF_TO_THREADS=true additionally adds each staff member explicitly — but the enumeration uses GET /guilds/{id}/members, which requires the privileged GUILD_MEMBERS intent to be enabled in the Developer Portal (Bot → Privileged Gateway Intents). Without it the add is skipped and a warning is logged; nothing breaks.
  • Private threads exist only in regular text channels. Pointing TICKET_PARENT_CHANNEL_ID at an announcement, forum or media channel produces a clear error explaining this rather than a silent fallback to a public thread. TICKET_THREAD_PRIVACY=public is available if you accept public tickets.

Ticket management

  • Claim Ticket — staff only. Atomic (fails if someone else claimed first) and refreshes the ticket card.
  • Close Ticket — the owner or staff. Records who/when/why, posts a closing card, then applies TICKET_CLOSE_BEHAVIOR. Ticket history is never deleted on close — the thread (and its DB row) are kept.
  • Reopen Ticket — staff only, from the closing card or /ticket-reopen <id|link>. Unarchives and unlocks the thread. Because a locked thread needs Manage Threads to unarchive, the slash command is the reliable fallback if a button click is refused.
  • Delete Ticket — staff only, destructive and irreversible; takes a transcript first when TICKET_TRANSCRIPTS=true.

All four are verified server-side on every click against TICKET_STAFF_ROLE_IDS (and optionally Administrator / Manage Threads). Button visibility is never used as security — Discord cannot hide a component from some users, so the buttons are visible to everyone in the thread and the checks live in code.

Also included: /ticket-status (configuration, counters, warnings, and whether you count as staff) and /ticket-help.

Persistence and duplicate prevention

Tickets live in this val's SQLite database (.db.ts), in two tables:

  • tickets — id, thread_id, guild_id, parent_channel_id, message_id, owner_id, owner_username, category, category_label, status (creating/open/closed/deleted), claimed_by, claimed_at, created_at, updated_at, closed_at, closed_by, closed_reason, close_behavior.
  • processed_interactions — interaction_id primary key, for idempotency.

Nothing important is kept in memory. Duplicate tickets are prevented at two levels, both inside a single atomic SQL batch so parallel dropdown clicks cannot interleave:

  1. INSERT OR IGNORE INTO processed_interactions — Discord's duplicate deliveries of the same interaction id are swallowed.
  2. A conditional INSERT … SELECT … WHERE (SELECT COUNT(*) …) < TICKET_MAX_OPEN_PER_USER — the row only lands while the user is under the cap for that server. The ticket id is reserved before Discord is touched, which is also what lets {number} appear in the thread name.

If thread creation fails, the reservation is rolled back and any half-created thread is deleted, so a failure never silently consumes a user's ticket slot.

Testing checklist

scripts/selftest.ts runs 60 checks, including live calls to Discord:

  1. Ed25519 verification accepts a valid signature and rejects tampered bodies, replayed timestamps and wrong keys; the configured public key is well-formed.
  2. Internal worker HMAC signing round-trips, and rejects wrong secrets, tampered bodies and expired timestamps.
  3. Emoji parsing: <:name:id>, <a:name:id> and Unicode all produce correct component payloads.
  4. custom_id parsing rejects garbage, empty, zero and SQL-ish values.
  5. Panel/card shapes, option limits, and that custom_ids match the parser.
  6. The full ticket lifecycle in the database plus the duplicate-interaction and per-user cap guards.
  7. The live bot token: GET /users/@me, GET /applications/@me.

Then, in Discord:

  • /ticket-status reports the parent channel and that you are recognised as staff.
  • /ticket-setup posts the panel; each dropdown option shows its emoji.
  • Selecting a category replies ephemerally with a clickable thread link.
  • The thread appears inside the support channel (Manage Threads holders only), and the owner can see and post in it.
  • A non-staff member cannot see the thread in the channel list.
  • Selecting again returns a link to the existing ticket instead of creating a second one.
  • A non-staff member clicking Claim is refused.
  • Claim shows the claimer on the card; Close archives/locks per configuration.
  • /ticket-reopen restores the thread and the owner can type again.
  • The log channel receives open/claim/close entries.
  • Re-running the val (or a redeploy) leaves the ticket rows intact.

Troubleshooting

SymptomCause and fix
Endpoint URL won't save in the PortalSignature verification failed → check DISCORD_PUBLIC_KEY matches General Information exactly. Look for interaction.bad_signature in the logs.
"The application did not respond"The deferred response did not reach Discord. Check the logs for worker.dispatch_failed / worker.unauthorized.
⚠️ I could not reach my own worker endpointThe self-call failed — usually a temporarily unreachable val. Try again.
Discord refused to open the ticket thread … Create Private ThreadsGrant Manage Threads, Send Messages in Threads, View Channel and Create Private Threads to the bot on the parent channel (channel overwrites beat role permissions).
I created the ticket thread but could not add you to itSame permission family; most often the thread is already archived, or the channel blocks the bot.
Panel posts but the dropdown does nothingThe panel was posted by an older build → re-run /ticket-setup so the custom_id matches.
Slash commands don't appearGlobal commands can take up to an hour. Set DISCORD_GUILD_ID and re-run setup for instant guild commands.
Close reports it could not archiveThe bot lacks Manage Threads on the parent channel; the DB record is still closed.
Reopen is refusedA locked thread needs Manage Threads to unarchive — grant it, or use /ticket-reopen.
TICKET_PARENT_CHANNEL_ID points at … errorPrivate threads need a regular text channel. Change the channel or set TICKET_THREAD_PRIVACY=public.
Staff can't see any ticketsThey need a role in TICKET_STAFF_ROLE_IDS, or Manage Threads; see the privacy section.
Rate limitsBots are rate-limited per-route; the client retries automatically after Discord's retry_after (logged as discord.rate_limited).

Security notes

  • The bot token is only ever read from the environment; it is never written into source, messages, embeds or logs. The logger redacts any field whose key looks like a token, secret or signature.
  • Every Discord request is signature-verified before parsing. The internal worker route is unreachable without an HMAC signature derived from the bot token, valid for 5 minutes.
  • Every staff action re-checks roles server-side; the internal route re-derives all state from the verified interaction rather than trusting any client-supplied field.
  • parseCustomId accepts only the exact ids this bot mints, and all SQL uses parameterised queries.

Known limitations

  • Reopening from a button in an archived thread. Discord permits button interactions in archived threads, but if a click is ever refused there, /ticket-reopen is the supported path — it is deliberately included for exactly this case.
  • TICKET_ADD_STAFF_TO_THREADS needs the privileged GUILD_MEMBERS intent, which is why it is off by default.
  • Thread member limits. Discord caps members per thread and active threads per guild; hitting those returns a clear error rather than failing silently.
  • One panel per post. /ticket-setup posts a new panel each time; delete the old message in Discord.
  • Like any HTTP-interaction bot, the val must be reachable — Discord retries failed deliveries, and the idempotency table makes those retries safe.