Files
velox-bot/internal/tickets/panel.go
T
FernandoJVideiraandClaude Opus 5.5 d294b3463b Add support tickets that work with private threads
Members open a ticket from a panel in the ticket channel: one button per
category (a dropdown past five), then a short form. Each ticket is a private
thread named after the category, number and opener, with a first message
that mentions the category's staff role so its members join, and Claim and
Close buttons.

- Claim: staff (the category's role, or Manage Threads / Manage Server)
  take a ticket; the first message shows who has it.
- Close: the opener or staff close it, with an optional reason. The thread
  is locked and archived, and the log channel gets a summary and a .txt
  transcript of the whole thread.
- /ticket add|remove|claim|close inside a ticket; /tickets setup,
  /tickets category add|remove|list and /tickets panel for admins.
- Per-member limit on open tickets (default 1), per-server ticket numbers
  handed out atomically, a deleted thread closes its ticket.
- The dashboard asks the bot to post or refresh the panel through
  ticket_commands (LISTEN/NOTIFY, like music); the listener reconnects if
  the database connection drops.
- Setup warns about missing bot permissions in the ticket and log channels.

The flows live in internal/tickets behind small Discord and store
interfaces, with unit tests on fakes; the repo and the listener have
integration tests (-tags integration, TICKETS_TEST_DB).

Needs the ticket tables (velox-dashboard-api migration 000016_tickets).
.gitignore gains the /tldr benchmark rules so private chat exports and
benchmark results on disk can't be committed from this branch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-20 19:31:52 +01:00

188 lines
5.7 KiB
Go

package tickets
import (
"context"
"fmt"
"regexp"
"strconv"
"strings"
"velox-bot/internal/db/repos/ticketrepo"
"github.com/bwmarrin/discordgo"
)
// Custom IDs. Everything starts with "tickets:" so the interaction router can
// hand it to this package.
const (
idOpenPrefix = "tickets:open:" // panel button, + category ID
idSelect = "tickets:select" // panel dropdown (many categories)
idOpenFormPrefix = "tickets:openform:" // opening form, + category ID
idClaim = "tickets:claim"
idClose = "tickets:close"
idCloseForm = "tickets:closeform"
fieldSubject = "subject"
fieldDetails = "details"
fieldReason = "reason"
)
var customEmojiRe = regexp.MustCompile(`^<(a?):(\w+):(\d+)>$`)
// parseEmoji accepts a Unicode emoji or a custom one written as <:name:id>.
func parseEmoji(s string) *discordgo.ComponentEmoji {
s = strings.TrimSpace(s)
if s == "" {
return nil
}
if m := customEmojiRe.FindStringSubmatch(s); m != nil {
return &discordgo.ComponentEmoji{Name: m[2], ID: m[3], Animated: m[1] == "a"}
}
return &discordgo.ComponentEmoji{Name: s}
}
// BuildPanel is the message members open tickets from: an embed with the
// guild's text and one button per category, or a dropdown once there are
// more categories than fit comfortably in a row.
func BuildPanel(s *ticketrepo.Settings, cats []ticketrepo.Category) (*discordgo.MessageEmbed, []discordgo.MessageComponent) {
embed := &discordgo.MessageEmbed{
Title: clip(s.PanelTitle, 256),
Description: clip(s.PanelDescription, 4000),
Color: accent,
}
if len(cats) > maxCategories {
cats = cats[:maxCategories]
}
if len(cats) <= maxPanelButtons {
var buttons []discordgo.MessageComponent
for _, c := range cats {
buttons = append(buttons, discordgo.Button{
Label: clip(c.Name, 80),
Style: discordgo.PrimaryButton,
CustomID: idOpenPrefix + id(c.ID),
Emoji: parseEmoji(c.Emoji),
})
}
// With few categories their descriptions go in the embed, since a
// button has no room for one.
for _, c := range cats {
if c.Description != "" {
embed.Fields = append(embed.Fields, &discordgo.MessageEmbedField{Name: clip(c.Name, 256), Value: clip(c.Description, 1024)})
}
}
return embed, []discordgo.MessageComponent{discordgo.ActionsRow{Components: buttons}}
}
var opts []discordgo.SelectMenuOption
for _, c := range cats {
opts = append(opts, discordgo.SelectMenuOption{
Label: clip(c.Name, 100),
Value: id(c.ID),
Description: clip(c.Description, 100),
Emoji: parseEmoji(c.Emoji),
})
}
return embed, []discordgo.MessageComponent{discordgo.ActionsRow{Components: []discordgo.MessageComponent{
discordgo.SelectMenu{CustomID: idSelect, Placeholder: "Choose what you need help with", Options: opts},
}}}
}
// PostPanel posts the panel in the ticket channel, or updates the one it
// posted before, and returns where it ended up.
func PostPanel(ctx context.Context, d Discord, st Store, guildID int64) (*discordgo.Message, error) {
s, err := st.GetSettings(ctx, guildID)
if err != nil {
return nil, err
}
if s.ChannelID == 0 {
return nil, ErrNotSetUp
}
cats, err := st.ListCategories(ctx, guildID)
if err != nil {
return nil, err
}
if len(cats) == 0 {
return nil, ErrNoCategories
}
embed, comps := BuildPanel(s, cats)
if s.PanelMessageID != 0 {
embeds := []*discordgo.MessageEmbed{embed}
msg, err := d.ChannelMessageEditComplex(&discordgo.MessageEdit{
Channel: id(s.ChannelID),
ID: id(s.PanelMessageID),
Embeds: &embeds,
Components: &comps,
})
if err == nil {
return msg, nil
}
// The old panel was deleted or the channel changed: post a new one.
}
msg, err := d.ChannelMessageSendComplex(id(s.ChannelID), &discordgo.MessageSend{
Embeds: []*discordgo.MessageEmbed{embed},
Components: comps,
})
if err != nil {
return nil, fmt.Errorf("posting the panel: %w", err)
}
if mid, err := strconv.ParseInt(msg.ID, 10, 64); err == nil {
if err := st.SetPanelMessage(ctx, guildID, mid); err != nil {
return msg, fmt.Errorf("saving the panel message: %w", err)
}
}
return msg, nil
}
// OpenForm is the short form shown after a member picks a category.
func OpenForm(cat *ticketrepo.Category) *discordgo.InteractionResponse {
return &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: idOpenFormPrefix + id(cat.ID),
Title: clip("Open a ticket: "+cat.Name, 45),
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{Components: []discordgo.MessageComponent{discordgo.TextInput{
CustomID: fieldSubject,
Label: "What do you need help with?",
Style: discordgo.TextInputShort,
Placeholder: "A short summary",
Required: true,
MinLength: 3,
MaxLength: maxSubject,
}}},
discordgo.ActionsRow{Components: []discordgo.MessageComponent{discordgo.TextInput{
CustomID: fieldDetails,
Label: "Details",
Style: discordgo.TextInputParagraph,
Placeholder: "Anything the staff should know (optional)",
Required: false,
MaxLength: maxDetails,
}}},
},
},
}
}
// CloseForm asks for an optional reason before closing.
func CloseForm() *discordgo.InteractionResponse {
return &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseModal,
Data: &discordgo.InteractionResponseData{
CustomID: idCloseForm,
Title: "Close this ticket",
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{Components: []discordgo.MessageComponent{discordgo.TextInput{
CustomID: fieldReason,
Label: "Reason (optional)",
Style: discordgo.TextInputParagraph,
Required: false,
MaxLength: maxReason,
}}},
},
},
}
}