-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
539 lines (489 loc) · 17.2 KB
/
main.go
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package main
import (
"errors"
"flag"
"fmt"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
"os"
"os/signal"
"strings"
"time"
"github.com/bwmarrin/discordgo"
)
// system vars
var (
logger log.Logger
GuildID = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")
BotToken = flag.String("token", "", "Bot access token")
RemoveCommands = flag.Bool("rmcmd", true, "Remove all commands after shutdowning or not")
)
var s *discordgo.Session
func init() { flag.Parse() }
func init() {
var err error
s, err = discordgo.New("Bot " + *BotToken)
if err != nil {
fmt.Println("Invalid bot parameters: %v", err)
}
}
var (
integerOptionMinValue = 1.0
dmPermission = false
defaultMemberPermissions int64 = discordgo.PermissionManageServer
commands = []*discordgo.ApplicationCommand{
{
Name: "basic-command",
// All commands and options must have a description
// Commands/options without description will fail the registration
// of the command.
Description: "Basic command",
},
{
Name: "permission-overview",
Description: "Command for demonstration of default command permissions",
DefaultMemberPermissions: &defaultMemberPermissions,
DMPermission: &dmPermission,
},
{
Name: "basic-command-with-files",
Description: "Basic command with files",
},
{
Name: "options",
Description: "Command for demonstrating options",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "string-option",
Description: "String option",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionInteger,
Name: "integer-option",
Description: "Integer option",
MinValue: &integerOptionMinValue,
MaxValue: 10,
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionNumber,
Name: "number-option",
Description: "Float option",
MaxValue: 10.1,
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionBoolean,
Name: "bool-option",
Description: "Boolean option",
Required: true,
},
// Required options must be listed first since optional parameters
// always come after when they're used.
// The same concept applies to Discord's Slash-commands API
{
Type: discordgo.ApplicationCommandOptionChannel,
Name: "channel-option",
Description: "Channel option",
// Channel type mask
ChannelTypes: []discordgo.ChannelType{
discordgo.ChannelTypeGuildText,
discordgo.ChannelTypeGuildVoice,
},
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionUser,
Name: "user-option",
Description: "User option",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionRole,
Name: "role-option",
Description: "Role option",
Required: false,
},
},
},
{
Name: "subcommands",
Description: "Subcommands and command groups example",
Options: []*discordgo.ApplicationCommandOption{
// When a command has subcommands/subcommand groups
// It must not have top-level options, they aren't accesible in the UI
// in this case (at least not yet), so if a command has
// subcommands/subcommand any groups registering top-level options
// will cause the registration of the command to fail
{
Name: "subcommand-group",
Description: "Subcommands group",
Options: []*discordgo.ApplicationCommandOption{
// Also, subcommand groups aren't capable of
// containing options, by the name of them, you can see
// they can only contain subcommands
{
Name: "nested-subcommand",
Description: "Nested subcommand",
Type: discordgo.ApplicationCommandOptionSubCommand,
},
},
Type: discordgo.ApplicationCommandOptionSubCommandGroup,
},
// Also, you can create both subcommand groups and subcommands
// in the command at the same time. But, there's some limits to
// nesting, count of subcommands (top level and nested) and options.
// Read the intro of slash-commands docs on Discord dev portal
// to get more information
{
Name: "subcommand",
Description: "Top-level subcommand",
Type: discordgo.ApplicationCommandOptionSubCommand,
},
},
},
{
Name: "responses",
Description: "Interaction responses testing initiative",
Options: []*discordgo.ApplicationCommandOption{
{
Name: "resp-type",
Description: "Response type",
Type: discordgo.ApplicationCommandOptionInteger,
Choices: []*discordgo.ApplicationCommandOptionChoice{
{
Name: "Channel message with source",
Value: 4,
},
{
Name: "Deferred response With Source",
Value: 5,
},
},
Required: true,
},
},
},
{
Name: "followups",
Description: "Followup messages",
},
}
commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
"basic-command": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
level.Info(logger).Log("msg", "basic-command recieved")
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Hey there! Congratulations, you just executed your first slash command",
},
})
},
"basic-command-with-files": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Hey there! Congratulations, you just executed your first slash command with a file in the response",
Files: []*discordgo.File{
{
ContentType: "text/plain",
Name: "test.txt",
Reader: strings.NewReader("Hello Discord!!"),
},
},
},
})
},
"options": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Access options in the order provided by the user.
options := i.ApplicationCommandData().Options
// Or convert the slice into a map
optionMap := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(options))
for _, opt := range options {
optionMap[opt.Name] = opt
}
// This example stores the provided arguments in an []interface{}
// which will be used to format the bot's response
margs := make([]interface{}, 0, len(options))
msgformat := "You learned how to use command options! " +
"Take a look at the value(s) you entered:\n"
// Get the value from the option map.
// When the option exists, ok = true
if option, ok := optionMap["string-option"]; ok {
// Option values must be type asserted from interface{}.
// Discordgo provides utility functions to make this simple.
margs = append(margs, option.StringValue())
msgformat += "> string-option: %s\n"
}
if opt, ok := optionMap["integer-option"]; ok {
margs = append(margs, opt.IntValue())
msgformat += "> integer-option: %d\n"
}
if opt, ok := optionMap["number-option"]; ok {
margs = append(margs, opt.FloatValue())
msgformat += "> number-option: %f\n"
}
if opt, ok := optionMap["bool-option"]; ok {
margs = append(margs, opt.BoolValue())
msgformat += "> bool-option: %v\n"
}
if opt, ok := optionMap["channel-option"]; ok {
margs = append(margs, opt.ChannelValue(nil).ID)
msgformat += "> channel-option: <#%s>\n"
}
if opt, ok := optionMap["user-option"]; ok {
margs = append(margs, opt.UserValue(nil).ID)
msgformat += "> user-option: <@%s>\n"
}
if opt, ok := optionMap["role-option"]; ok {
margs = append(margs, opt.RoleValue(nil, "").ID)
msgformat += "> role-option: <@&%s>\n"
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
// Ignore type for now, they will be discussed in "responses"
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf(
msgformat,
margs...,
),
},
})
},
"permission-overview": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
perms, err := s.ApplicationCommandPermissions(s.State.User.ID, i.GuildID, i.ApplicationCommandData().ID)
var restError *discordgo.RESTError
if errors.As(err, &restError) && restError.Message != nil && restError.Message.Code == discordgo.ErrCodeUnknownApplicationCommandPermissions {
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: ":x: No permission overwrites",
},
})
return
} else if err != nil {
panic(err)
}
if err != nil {
panic(err)
}
format := "- %s %s\n"
channels := ""
users := ""
roles := ""
for _, o := range perms.Permissions {
emoji := "❌"
if o.Permission {
emoji = "☑"
}
switch o.Type {
case discordgo.ApplicationCommandPermissionTypeUser:
users += fmt.Sprintf(format, emoji, "<@!"+o.ID+">")
case discordgo.ApplicationCommandPermissionTypeChannel:
allChannels, _ := discordgo.GuildAllChannelsID(i.GuildID)
if o.ID == allChannels {
channels += fmt.Sprintf(format, emoji, "All channels")
} else {
channels += fmt.Sprintf(format, emoji, "<#"+o.ID+">")
}
case discordgo.ApplicationCommandPermissionTypeRole:
if o.ID == i.GuildID {
roles += fmt.Sprintf(format, emoji, "@everyone")
} else {
roles += fmt.Sprintf(format, emoji, "<@&"+o.ID+">")
}
}
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{
{
Title: "Permissions overview",
Description: "Overview of permissions for this command",
Fields: []*discordgo.MessageEmbedField{
{
Name: "Users",
Value: users,
},
{
Name: "Channels",
Value: channels,
},
{
Name: "Roles",
Value: roles,
},
},
},
},
AllowedMentions: &discordgo.MessageAllowedMentions{},
},
})
},
"subcommands": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
options := i.ApplicationCommandData().Options
content := ""
// As you can see, names of subcommands (nested, top-level)
// and subcommand groups are provided through the arguments.
switch options[0].Name {
case "subcommand":
content = "The top-level subcommand is executed. Now try to execute the nested one."
case "subcommand-group":
options = options[0].Options
switch options[0].Name {
case "nested-subcommand":
content = "Nice, now you know how to execute nested commands too"
default:
content = "Oops, something went wrong.\n" +
"Hol' up, you aren't supposed to see this message."
}
}
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: content,
},
})
},
"responses": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Responses to a command are very important.
// First of all, because you need to react to the interaction
// by sending the response in 3 seconds after receiving, otherwise
// interaction will be considered invalid and you can no longer
// use the interaction token and ID for responding to the user's request
content := ""
// As you can see, the response type names used here are pretty self-explanatory,
// but for those who want more information see the official documentation
switch i.ApplicationCommandData().Options[0].IntValue() {
case int64(discordgo.InteractionResponseChannelMessageWithSource):
content =
"You just responded to an interaction, sent a message and showed the original one. " +
"Congratulations!"
content +=
"\nAlso... you can edit your response, wait 5 seconds and this message will be changed"
default:
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Something went wrong",
})
}
return
}
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
Data: &discordgo.InteractionResponseData{
Content: content,
},
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Something went wrong",
})
return
}
time.AfterFunc(time.Second*5, func() {
content := content + "\n\nWell, now you know how to create and edit responses. " +
"But you still don't know how to delete them... so... wait 10 seconds and this " +
"message will be deleted."
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &content,
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Something went wrong",
})
return
}
time.Sleep(time.Second * 10)
s.InteractionResponseDelete(i.Interaction)
})
},
"followups": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Followup messages are basically regular messages (you can create as many of them as you wish)
// but work as they are created by webhooks and their functionality
// is for handling additional messages after sending a response.
s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
// Note: this isn't documented, but you can use that if you want to.
// This flag just allows you to create messages visible only for the caller of the command
// (user who triggered the command)
Flags: discordgo.MessageFlagsEphemeral,
Content: "Surprise!",
},
})
msg, err := s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Followup message has been created, after 5 seconds it will be edited",
})
if err != nil {
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "Something went wrong",
})
return
}
time.Sleep(time.Second * 5)
content := "Now the original message is gone and after 10 seconds this message will ~~self-destruct~~ be deleted."
s.FollowupMessageEdit(i.Interaction, msg.ID, &discordgo.WebhookEdit{
Content: &content,
})
time.Sleep(time.Second * 10)
s.FollowupMessageDelete(i.Interaction, msg.ID)
s.FollowupMessageCreate(i.Interaction, true, &discordgo.WebhookParams{
Content: "For those, who didn't skip anything and followed tutorial along fairly, " +
"take a unicorn :unicorn: as reward!\n" +
"Also, as bonus... look at the original interaction response :D",
})
},
}
)
func init() {
s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
h(s, i)
}
})
}
func main() {
fmt.Println("Crub")
// set up logging
logger = log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
logger = level.NewFilter(logger, level.AllowInfo())
logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
level.Info(logger).Log("msg", "starting bot")
s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
level.Info(logger).Log("msg",fmt.Sprintf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator))
})
err := s.Open()
if err != nil {
level.Info(logger).Log("err",fmt.Sprintf("Cannot open the session: %v", err))
}
level.Info(logger).Log("msg", "adding commands")
registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
for i, v := range commands {
cmd, err := s.ApplicationCommandCreate(s.State.User.ID, *GuildID, v)
if err != nil {
level.Info(logger).Log("err",fmt.Sprintf("Cannot create '%v' command: %v", v.Name, err))
}
registeredCommands[i] = cmd
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
level.Info(logger).Log("msg", "Press Ctrl+C to exit")
<-stop
if *RemoveCommands {
level.Info(logger).Log("msg", "Removing commands...")
for _, v := range registeredCommands {
err := s.ApplicationCommandDelete(s.State.User.ID, *GuildID, v.ID)
if err != nil {
level.Info(logger).Log("err",fmt.Sprintf("Cannot delete '%v' command: %v", v.Name, err))
}
}
}
level.Info(logger).Log("msg", "gracefully shutting down")
}