aboutsummaryrefslogtreecommitdiff
path: root/dynamicid/handling.go
blob: 44223f1c680db43b112dd8185ceec2a68893f7bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package dynamicid

import (
	"context"
	"strings"

	"github.com/nyttikord/gokord/bot"
	"github.com/nyttikord/gokord/discord/types"
	"github.com/nyttikord/gokord/interaction"
	"github.com/nyttikord/gokord/interaction/interactionhandler"
)

func HandleDynamicMessageComponent[T any](
	m *interactionhandler.Manager,
	handler func(context.Context, bot.Session, *interaction.MessageComponent, T),
	base string,
) {
	m.HandleRaw(func(ctx context.Context, dg bot.Session, i *interaction.Interaction) {
		if i.Type != types.InteractionMessageComponent {
			return
		}
		msg := i.MessageComponent()
		cid := msg.Data.CustomID
		if !strings.HasPrefix(cid, base+";") {
			return
		}
		dynamicID := cid[len(base)+1:]
		var dynamic T
		err := UnmarshallCSV(dynamicID, dynamic)
		if err != nil {
			bot.Logger(ctx).Error("Unable to parse CustomID", "error", err, "CustomID", cid, "base", base)
			return
		}
		handler(ctx, dg, msg, dynamic)
	})
}

func HandleDynamicModalComponent[T any](
	m *interactionhandler.Manager,
	handler func(context.Context, bot.Session, *interaction.ModalSubmit, T),
	base string,

) {
	m.HandleRaw(func(ctx context.Context, dg bot.Session, i *interaction.Interaction) {
		if i.Type != types.InteractionModalSubmit {
			return
		}
		modal := i.ModalSubmit()
		cid := modal.Data.CustomID
		if !strings.HasPrefix(cid, base+";") {
			return
		}
		dynamicID := cid[len(base)+1:]
		var dynamic T
		err := UnmarshallCSV(dynamicID, dynamic)
		if err != nil {
			bot.Logger(ctx).Error("Unable to parse CustomID", "error", err, "CustomID", cid, "base", base)
			return
		}
		handler(ctx, dg, modal, dynamic)
	})
}

func FormatCustomID(base string, dynamicData any) string {
	return base + ";" + MarshallCSV(dynamicData)
}