aboutsummaryrefslogtreecommitdiff
path: root/config/xp_role.go
blob: 6592ac9cefa7492b472570cbf0e1d5fb0d728ea2 (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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
package config

import (
	"context"
	"fmt"
	"slices"
	"strconv"

	"git.anhgelus.world/anhgelus/les-copaings-bot/common"
	"git.anhgelus.world/anhgelus/les-copaings-bot/dynamicid"
	"git.anhgelus.world/anhgelus/les-copaings-bot/exp"
	"github.com/nyttikord/gokord/bot"
	"github.com/nyttikord/gokord/channel"
	"github.com/nyttikord/gokord/component"
	"github.com/nyttikord/gokord/discord/types"
	"github.com/nyttikord/gokord/interaction"
)

type XpRole struct {
	ID            uint `gorm:"primarykey"`
	XP            uint
	RoleID        uint64
	GuildConfigID uint
}

type XpRoleId struct {
	ID uint
}

const (
	ModifyXpRole         = "xp_role"
	XpRoleNew            = "xp_role_add"
	XpRoleAdd            = "xp_role_add_level"
	XpRoleEdit           = `xp_role_edit`
	XpRoleEditLevel      = `xp_role_edit_level`
	XpRoleEditLevelStart = `xp_role_edit_level_start`
	XpRoleEditRole       = `xp_role_edit_role`
	XpRoleDel            = `xp_role_del`
)

func HandleXpRole(ctx context.Context, dg bot.Session, i *interaction.Interaction) {
	cfg := GetGuildConfig(ctx, i.GuildID)
	container := component.Container{
		Components: []component.Message{
			&component.TextDisplay{Content: "## Configuration / Rôles de niveaux"},
			&component.TextDisplay{Content: "Ces rôles seront donnés et retirés en fonction du niveau de chacun"},
			&component.Separator{},
		},
	}
	slices.SortFunc(cfg.XpRoles, func(xp1, xp2 XpRole) int {
		return int(xp2.XP) - int(xp1.XP)
	})
	for _, r := range cfg.XpRoles {
		container.Components = append(container.Components, &component.Section{
			Components: []component.Message{
				&component.TextDisplay{
					Content: fmt.Sprintf("<@&%s> - Niveau %d", r.RoleID, exp.Level(r.XP)),
				},
			},
			Accessory: &component.Button{
				CustomID: dynamicid.FormatCustomID(XpRoleEdit, XpRoleId{ID: r.ID}),
				Style:    component.ButtonStyleSecondary,
				Label:    "Modifier",
			},
		})
	}
	container.Components = append(container.Components,
		&component.ActionsRow{
			Components: []component.Message{
				&component.Button{
					CustomID: XpRoleNew,
					Style:    component.ButtonStylePrimary,
					Label:    "Nouveau rôle",
				},
			},
		},
		&component.Separator{},
		&component.ActionsRow{
			Components: []component.Message{
				&component.Button{CustomID: "config", Style: component.ButtonStyleSecondary, Label: "Retour"},
			},
		},
	)

	response := &interaction.Response{
		Type: types.InteractionResponseUpdateMessage,
		Data: &interaction.ResponseData{
			Components: []component.Component{&container},
			Flags:      channel.MessageFlagsIsComponentsV2,
		},
	}
	err := interaction.Respond(i, response).Do(ctx)
	if err != nil {
		bot.Logger(ctx).Error("sending config", "error", err)
	}
}

func HandleXpRoleNew(ctx context.Context, dg bot.Session, i *interaction.MessageComponent) {
	one := 1
	resp := interaction.NewModalResponse().
		Title("Nouveau rôle de niveau").
		CustomID(XpRoleAdd).
		AddComponent(&component.Label{
			Label: "Niveau",
			Component: &component.TextInput{
				CustomID:    "level",
				Style:       component.TextInputShort,
				Placeholder: "5",
				MinLength:   1,
				MaxLength:   5,
				Required:    true,
			},
		}).
		AddComponent(&component.Label{
			Label: "Rôle",
			Component: &component.SelectMenu{
				MenuType:  types.SelectMenuRole,
				CustomID:  "role",
				MinValues: &one,
				MaxValues: one,
			},
		}).
		Response()
	err := interaction.Respond(i.Interaction, resp).Do(ctx)
	if err != nil {
		bot.Logger(ctx).Error("sending modal to add", "error", err)
	}
}

func HandleXpRoleEdit(ctx context.Context, dg bot.Session, i *interaction.Interaction, params *XpRoleId) {
	config := GetGuildConfig(ctx, i.GuildID)
	id := params.ID
	_, role := config.FindXpRoleID(id)
	if role == nil {
		HandleXpRole(ctx, dg, i)
		return
	}

	roleSelect := &component.SelectMenu{
		MenuType: types.SelectMenuRole,
		CustomID: dynamicid.FormatCustomID(XpRoleEditRole, XpRoleId{ID: id}),
		DefaultValues: []component.SelectMenuDefaultValue{
			{ID: role.RoleID, Type: types.SelectMenuDefaultValueRole},
		},
	}

	container := &component.Container{
		Components: []component.Message{
			&component.TextDisplay{Content: "## Configuration / Rôles de niveaux"},
			&component.Separator{},
			&component.Section{
				Components: []component.Message{
					&component.TextDisplay{Content: fmt.Sprintf("Niveau **%d**", exp.Level(role.XP))},
				},
				Accessory: &component.Button{
					CustomID: dynamicid.FormatCustomID(XpRoleEditLevelStart, XpRoleId{ID: id}),
					Style:    component.ButtonStyleSecondary,
					Label:    "Modifier",
				},
			},
			&component.ActionsRow{Components: []component.Message{roleSelect}},
			&component.ActionsRow{Components: []component.Message{
				&component.Button{
					CustomID: dynamicid.FormatCustomID(XpRoleDel, XpRoleId{ID: id}),
					Style:    component.ButtonStyleDanger,
					Label:    "Supprimer",
				},
			}},
			&component.Separator{},
			&component.ActionsRow{Components: []component.Message{
				&component.Button{Label: "Retour", CustomID: ModifyXpRole, Style: component.ButtonStyleSecondary},
			}},
		},
	}

	response := &interaction.Response{
		Type: types.InteractionResponseUpdateMessage,
		Data: &interaction.ResponseData{
			Components: []component.Component{container},
			Flags:      channel.MessageFlagsIsComponentsV2,
		},
	}

	err := interaction.Respond(i, response).Do(ctx)
	if err != nil {
		bot.Logger(ctx).Error("sending xp_role config", "error", err)
	}
}

func HandleXpRoleEditRole(ctx context.Context, dg bot.Session, i *interaction.MessageComponent, params *XpRoleId) {
	id := params.ID
	role, err := strconv.ParseUint(i.Data.Values[0], 10, 64)
	if err != nil {
		// panic because must ensure that the role is valid before
		panic(err)
	}
	cfg := GetGuildConfig(ctx, i.GuildID)
	_, xpRole := cfg.FindXpRoleID(id)
	if xpRole == nil {
		err := interaction.Respond(i.Interaction, &interaction.Response{
			Type: types.InteractionResponseChannelMessageWithSource,
			Data: &interaction.ResponseData{
				Flags:   channel.MessageFlagsEphemeral,
				Content: "Impossible de modifier le rôle. Peut-être a-t-il été supprimé ?",
			},
		}).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending unable to get role message", "error", err)
		}
		return
	}
	xpRole.RoleID = role
	err = common.GetDB(ctx).Save(xpRole).Error
	if err != nil {
		bot.Logger(ctx).Error("saving config", "error", err, "guild", i.GuildID, "id", id, "type", "add")
	}
	HandleXpRoleEdit(ctx, dg, i.Interaction, params)
}

func HandleXpRoleEditLevelStart(ctx context.Context, dg bot.Session, i *interaction.MessageComponent, params *XpRoleId) {
	id := params.ID
	cfg := GetGuildConfig(ctx, i.GuildID)
	_, xpRole := cfg.FindXpRoleID(id)
	if xpRole == nil {
		err := interaction.Respond(i.Interaction, &interaction.Response{
			Type: types.InteractionResponseChannelMessageWithSource,
			Data: &interaction.ResponseData{
				Flags:   channel.MessageFlagsEphemeral,
				Content: "Impossible de trouver le rôle. Peut-être a-t-il été supprimé ?",
			},
		}).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending unable to get role message", "error", err)
		}
		return
	}
	response := &interaction.Response{
		Type: types.InteractionResponseModal,
		Data: &interaction.ResponseData{
			Title:    "Modification du niveau lié au rôle",
			CustomID: dynamicid.FormatCustomID(XpRoleEditLevel, XpRoleId{ID: id}),
			Components: []component.Component{
				&component.Label{
					Label: "Nouveau niveau",
					Component: &component.TextInput{
						Style:       component.TextInputShort,
						Required:    true,
						CustomID:    "level",
						MinLength:   1,
						MaxLength:   5,
						Placeholder: "5",
						Value:       strconv.FormatUint(uint64(exp.Level(xpRole.XP)), 10),
					},
				},
			},
		},
	}
	err := interaction.Respond(i.Interaction, response).Do(ctx)
	if err != nil {
		bot.Logger(ctx).Error("sending edit level modal", "error", err)
	}
}

func HandleXpRoleEditLevel(ctx context.Context, dg bot.Session, i *interaction.ModalSubmit, params *XpRoleId) {
	id := params.ID

	levelInput := i.Data.Components[0].(*component.Label).Component.(*component.TextInput)
	level, err := strconv.Atoi(levelInput.Value)
	if err != nil || level < 0 {
		resp := interaction.NewMessageResponse().
			IsEphemeral().
			Message(fmt.Sprintf("Le niveau doit être un nombre entier positif.\n-# Trouvé : %s", levelInput.Value)).
			Response()
		err = interaction.Respond(i.Interaction, resp).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending bad number warning message", "error", err)
		}
		return
	}
	xp := exp.LevelXP(uint(level))

	cfg := GetGuildConfig(ctx, i.GuildID)
	_, xpRole := cfg.FindXpRoleID(id)
	if xpRole == nil {
		err = interaction.Respond(i.Interaction, &interaction.Response{
			Type: types.InteractionResponseChannelMessageWithSource,
			Data: &interaction.ResponseData{
				Flags:   channel.MessageFlagsEphemeral,
				Content: "Impossible de modifier le rôle. Peut-être a-t-il été supprimé ?",
			},
		}).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending unable to modify role message", "error", err)
		}
		return
	}
	xpRole.XP = xp
	err = common.GetDB(ctx).Save(xpRole).Error
	if err != nil {
		bot.Logger(ctx).Error("saving config", "guild", i.GuildID, "id", id, "type", "edit")
	}
	HandleXpRoleEdit(ctx, dg, i.Interaction, params)
}

func HandleXpRoleDel(ctx context.Context, dg bot.Session, i *interaction.MessageComponent, parameters *XpRoleId) {
	id := parameters.ID
	cfg := GetGuildConfig(ctx, i.GuildID)
	_, role := cfg.FindXpRoleID(id)
	if role == nil {
		err := interaction.Respond(i.Interaction, &interaction.Response{
			Type: types.InteractionResponseChannelMessageWithSource,
			Data: &interaction.ResponseData{
				Content: "Rôle introuvable. Peut-être a-t-il déjà été supprimé ?",
				Flags:   channel.MessageFlagsEphemeral,
			},
		}).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending role not found message", "error", err)
		}
		return
	}
	err := common.GetDB(ctx).Delete(role).Error
	if err != nil {
		bot.Logger(ctx).Error("deleting entry", "error", err, "guild", i.GuildID, "id", id, "type", "del")
	}

	HandleXpRole(ctx, dg, i.Interaction)
}

func HandleXpRoleAdd(ctx context.Context, dg bot.Session, i *interaction.ModalSubmit) {
	levelInput := i.Data.Components[0].(*component.Label).Component.(*component.TextInput)

	in, err := strconv.Atoi(levelInput.Value)
	if err != nil || in < 0 {
		resp := interaction.NewMessageResponse().
			IsEphemeral().
			Message(fmt.Sprintf("Le niveau doit être un nombre entier positif.\n-# Trouvé : %s", levelInput.Value)).
			Response()
		err = interaction.Respond(i.Interaction, resp).Do(ctx)
		if err != nil {
			bot.Logger(ctx).Error("sending bad number warning message", "error", err)
		}
		return
	}
	xp := exp.LevelXP(uint(in))

	rawRoleId := i.Data.Components[1].(*component.Label).Component.(*component.SelectMenu).Values[0]
	roleId, err := strconv.ParseUint(rawRoleId, 10, 64)
	if err != nil {
		// panic because select menu must ensure that the value is valid
		panic(err)
	}

	cfg := GetGuildConfig(ctx, i.GuildID)
	cfg.XpRoles = append(cfg.XpRoles, XpRole{
		XP:     xp,
		RoleID: roleId,
	})
	err = cfg.Save(ctx)
	if err != nil {
		bot.Logger(ctx).Error("saving config", "error", err, "role", roleId, "guild", i.GuildID)
		return
	}

	HandleXpRole(ctx, dg, i.Interaction)
}