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
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
fetchagainsthttps://discord.com/api/v10. - Signatures are verified on every request. Discord signs each interaction with Ed25519; the
endpoint checks
X-Signature-Ed25519against the raw body before parsing it. Unsigned requests get401and 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...
| File | Role |
|---|---|
main.ts | HTTP endpoint: signature verification, PING handshake, deferred dispatch, worker route, health page |
config.ts | All configuration: env vars, categories, emoji markup parsing, message templates |
verify.ts | Ed25519 interaction verification + HMAC signing/verification of internal jobs |
discord.ts | Minimal Discord REST client (rate-limit aware), permission bits, channel types |
db.ts | SQLite schema + queries; atomic duplicate-ticket guard |
tickets.ts | Ticket lifecycle: open, claim, close, reopen, delete, transcripts |
panel.ts | Panel, ticket card and closing card builders; custom_id parsing |
commands.ts | Slash-command definitions and registration |
types.ts | The Discord interaction payload subset used here |
log.ts | Structured JSON logging with secret redaction |
scripts/setup.ts | Registers commands and posts the panel |
scripts/discover-ids.ts | Prints your server/channel/role ids |
scripts/selftest.ts | 60 automated checks (crypto, parsing, DB, live 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
Use this URL (the permission integer is explained below):
https://discord.com/oauth2/authorize?client_id=1558392102923014255&scope=bot%20applications.commands&permissions=395137338368
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.
Set these environment variables (backticked names below are clickable links to the prefilled editor; the Required ones are the ones you must fill in):
| Variable | Required | Meaning |
|---|---|---|
DISCORD_GUILD_ID | recommended | Your server id. Commands then register instantly; without it they are global and can take up to an hour to appear. |
TICKET_PARENT_CHANNEL_ID | yes | The text channel that ticket threads are created inside. |
TICKET_PANEL_CHANNEL_ID | recommended | Where /ticket-setup posts the panel (you can also pass channel to the command). |
TICKET_STAFF_ROLE_IDS | yes | Comma-separated support role ids. |
TICKET_LOG_CHANNEL_ID | optional | Receives ticket open/claim/close/delete logs (and transcripts). |
TICKET_THREAD_PRIVACY | optional | private (default) or public. |
TICKET_CLOSE_BEHAVIOR | optional | archive+lock (default), archive, lock, delete. |
TICKET_MAX_OPEN_PER_USER | optional | Default 1. Prevents duplicate tickets. |
TICKET_NAME_FORMAT | optional | Default ticket-{username}-{category}. Placeholders: {username} {displayname} {category} {categoryLabel} {number} {id} {user} {server}. |
TICKET_WELCOME_MESSAGE | optional | First message in the thread. Same placeholders, plus {status}. |
TICKET_INSTRUCTIONS | optional | Line under the panel description. |
TICKET_CATEGORIES | optional | JSON array that replaces the built-in categories — see below. |
TICKET_PANEL_TITLE / _DESCRIPTION / _FOOTER / _PLACEHOLDER | optional | Panel text. |
TICKET_PANEL_COLOR | optional | Decimal colour, e.g. 5793266. |
TICKET_PANEL_THUMBNAIL / _IMAGE | optional | Image URLs for the panel embed. |
TICKET_THREAD_INVITABLE | optional | false (default). Whether regular members may invite others in. |
TICKET_AUTO_ARCHIVE_MINUTES | optional | 60, 1440 (default), 4320 or 10080. |
TICKET_ADD_STAFF_TO_THREADS | optional | false (default). See privacy below before enabling. |
TICKET_MAX_STAFF_ADDED | optional | Cap on staff added per thread (default 10). |
TICKET_STAFF_ALLOW_PERMISSIONS | optional | true (default): Administrator / Manage Threads also count as staff. |
TICKET_CLAIM_MODE | optional | staff (default) or anyone (owner may claim too). |
TICKET_TRANSCRIPTS | optional | false (default). Save a .txt transcript to the log channel and blob storage. |
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.
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.
The invite link above requests exactly what the bot uses:
| Permission | Why |
|---|---|
| View Channel | see the panel and support channels |
| Send Messages | post the panel, replies and log entries |
| Embed Links | render the ticket embeds |
| Read Message History | transcripts and ticket history |
| Manage Threads | archive, lock, reopen and unarchive threads |
| Send Messages in Threads | talk inside tickets |
| Create Private Threads | open private ticket threads |
| Create Public Threads | open public threads when TICKET_THREAD_PRIVACY=public |
| Use External Emojis | custom emojis hosted on another server |
That is permission integer 395137338368, with the bot and applications.commands scopes.
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.
valueis the stable internal id stored on tickets; changelabel/description/emojifreely.- Custom emojis hosted on another server need the
Use External Emojispermission. - To edit the built-in list in code instead, see
DEFAULT_CATEGORIESinconfig.ts.
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_THREADis "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 Threadson 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 withManage Threadson the support channel. If you grantManage Threadsto @everyone, "private" threads stop being private. - ⚠️ By default staff are not added as thread members; they reach tickets through
Manage Threads(above). SettingTICKET_ADD_STAFF_TO_THREADS=trueadditionally adds each staff member explicitly — but the enumeration usesGET /guilds/{id}/members, which requires the privilegedGUILD_MEMBERSintent 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_IDat an announcement, forum or media channel produces a clear error explaining this rather than a silent fallback to a public thread.TICKET_THREAD_PRIVACY=publicis available if you accept public tickets.
- 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 needsManage Threadsto 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.
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_idprimary 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:
INSERT OR IGNORE INTO processed_interactions— Discord's duplicate deliveries of the same interaction id are swallowed.- 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.
scripts/selftest.ts runs 60 checks, including live calls to Discord:
- Ed25519 verification accepts a valid signature and rejects tampered bodies, replayed timestamps and wrong keys; the configured public key is well-formed.
- Internal worker HMAC signing round-trips, and rejects wrong secrets, tampered bodies and expired timestamps.
- Emoji parsing:
<:name:id>,<a:name:id>and Unicode all produce correct component payloads. custom_idparsing rejects garbage, empty, zero and SQL-ish values.- Panel/card shapes, option limits, and that
custom_ids match the parser. - The full ticket lifecycle in the database plus the duplicate-interaction and per-user cap guards.
- The live bot token:
GET /users/@me,GET /applications/@me.
Then, in Discord:
-
/ticket-statusreports the parent channel and that you are recognised as staff. -
/ticket-setupposts 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 Threadsholders 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-reopenrestores 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.
| Symptom | Cause and fix |
|---|---|
| Endpoint URL won't save in the Portal | Signature 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 endpoint | The self-call failed — usually a temporarily unreachable val. Try again. |
Discord refused to open the ticket thread … Create Private Threads | Grant 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 it | Same permission family; most often the thread is already archived, or the channel blocks the bot. |
| Panel posts but the dropdown does nothing | The panel was posted by an older build → re-run /ticket-setup so the custom_id matches. |
| Slash commands don't appear | Global commands can take up to an hour. Set DISCORD_GUILD_ID and re-run setup for instant guild commands. |
| Close reports it could not archive | The bot lacks Manage Threads on the parent channel; the DB record is still closed. |
| Reopen is refused | A locked thread needs Manage Threads to unarchive — grant it, or use /ticket-reopen. |
TICKET_PARENT_CHANNEL_ID points at … error | Private threads need a regular text channel. Change the channel or set TICKET_THREAD_PRIVACY=public. |
| Staff can't see any tickets | They need a role in TICKET_STAFF_ROLE_IDS, or Manage Threads; see the privacy section. |
| Rate limits | Bots are rate-limited per-route; the client retries automatically after Discord's retry_after (logged as discord.rate_limited). |
- 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.
parseCustomIdaccepts only the exact ids this bot mints, and all SQL uses parameterised queries.
- Reopening from a button in an archived thread. Discord permits button interactions in archived
threads, but if a click is ever refused there,
/ticket-reopenis the supported path — it is deliberately included for exactly this case. TICKET_ADD_STAFF_TO_THREADSneeds the privilegedGUILD_MEMBERSintent, 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-setupposts 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.