-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
447 lines (400 loc) · 12.6 KB
/
main.go
File metadata and controls
447 lines (400 loc) · 12.6 KB
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
package main
import (
"errors"
"flag"
"fmt"
"log"
"os"
"os/signal"
"strconv"
"strings"
"time"
"github.com/bwmarrin/discordgo"
"github.com/gisforgravity/mellogo/db"
)
type Score struct {
Minutes int
Seconds int
}
func (s *Score) String() string {
return fmt.Sprintf("%d:%02d", s.Minutes, s.Seconds)
}
var (
Token string // Discord bot token
AppId string // Discord app id
Db db.Database // Database for scores and users
SubmitCommand = discordgo.ApplicationCommand{
Name: "submit",
Description: "submit a time for the uniform speedrun",
Type: discordgo.ChatApplicationCommand,
Options: []*discordgo.ApplicationCommandOption{
{
Name: "today",
Description: "submit a time for today",
Type: discordgo.ApplicationCommandOptionSubCommand,
Options: []*discordgo.ApplicationCommandOption{
{
Name: "time",
Description: "the time to submit",
Type: discordgo.ApplicationCommandOptionString,
Required: true,
MinLength: create(4),
},
},
},
{
Name: "for-date",
Description: "submit a time for a certain date",
Type: discordgo.ApplicationCommandOptionSubCommand,
Options: []*discordgo.ApplicationCommandOption{
{
Name: "date",
Description: "(MM/DD/YYYY) the date to submit a time for",
Type: discordgo.ApplicationCommandOptionString,
Required: true,
MinLength: create(10),
MaxLength: 10,
},
{
Name: "time",
Description: "(Minutes:Seconds) the time to submit",
Type: discordgo.ApplicationCommandOptionString,
Required: true,
MinLength: create(4),
},
},
},
},
}
LeaderboardCommand = discordgo.ApplicationCommand{
Name: "leaderboard",
Description: "shows the current leaderboard",
Type: discordgo.ChatApplicationCommand,
}
ChangeNameCommand = discordgo.ApplicationCommand{
Name: "change-name",
Description: "changes your name in the leaderboard",
Type: discordgo.ChatApplicationCommand,
Options: []*discordgo.ApplicationCommandOption{
{
Name: "name",
Description: "the name to change to",
Type: discordgo.ApplicationCommandOptionString,
MaxLength: 18,
Required: true,
},
},
}
)
func create(a int) *int {
return &a
}
func init() {
// Parse command line flags (bot token)
flag.StringVar(&Token, "token", "", "Discord bot token")
flag.StringVar(&AppId, "id", "", "Discord application id")
flag.Parse()
// Create database object
Db = db.CreateSqlite("scores.sqlite")
}
func main() {
// Initialize mello database (if not already initialized)
err := Db.Initialize()
if err != nil {
log.Panicln("failed to initialize db:", err)
}
// Create a bot session using the token provided in flag
s, err := discordgo.New("Bot " + Token)
if err != nil {
log.Panicln("bot creation error:", err)
return
}
// Register handlers
s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
// name, ok := commandId[i.AppID]
// if !ok {
// fmt.Println("unknown command error: ", errors.New("unknown command with ID: "+i.AppID))
// return
// }
name := i.ApplicationCommandData().Name
fmt.Printf("%#v\n", i.ApplicationCommandData())
switch name {
case "submit":
submitHandler(s, i)
case "leaderboard":
leaderboardHandler(s, i)
case "change-name":
changeNameHandler(s, i)
default:
// handle default case
response := discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Sorry, I was unable to process your message.",
},
}
// send response
s.InteractionRespond(i.Interaction, &response)
}
})
s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
log.Printf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
})
// Specify intents
s.Identify.Intents = discordgo.IntentGuildMessages | discordgo.IntentDirectMessages
// Open channel
err = s.Open()
if err != nil {
log.Panicln("bot connection error:", err)
}
defer s.Close()
// Register commands
registerCommand(s, &SubmitCommand)
registerCommand(s, &LeaderboardCommand)
registerCommand(s, &ChangeNameCommand)
// Block
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
log.Println("Press Ctrl+C to exit")
<-stop
}
func registerCommand(s *discordgo.Session, command *discordgo.ApplicationCommand) {
_, err := s.ApplicationCommandCreate(AppId, "", command)
if err != nil {
log.Panicln("command registration error: ", err)
}
}
func sendUserError(s *discordgo.Session, i *discordgo.InteractionCreate, update bool, ephemeral bool, msg string) {
// Create embed
embed := discordgo.MessageEmbed{
Color: 0xff7081, // red rgb
Description: msg,
}
// determine response type
var responseType discordgo.InteractionResponseType
if update {
responseType = discordgo.InteractionResponseDeferredMessageUpdate
} else {
responseType = discordgo.InteractionResponseChannelMessageWithSource
}
// determine flags
var messageFlags discordgo.MessageFlags
if ephemeral {
messageFlags = discordgo.MessageFlagsEphemeral
} else {
messageFlags = 0
}
if update {
_, err := s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{&embed},
})
if err != nil {
fmt.Println("error sending user an error:", err)
}
} else {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: responseType,
Data: &discordgo.InteractionResponseData{
Embeds: []*discordgo.MessageEmbed{&embed},
Flags: messageFlags,
},
})
if err != nil {
fmt.Println("error sending user an error:", err)
}
}
}
func submitHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
// acknowledge command is received and tell discord we will respond later
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
},
})
if err != nil {
fmt.Println("error sending interaction response:", err)
return
}
// variables
subOption := i.ApplicationCommandData().Options[0]
options := subOption.Options
member := i.Member
var scoreArg int
var date time.Time
// handle date and score or just score
switch subOption.Name {
case "today":
date = time.Now()
scoreArg = 0 // options[0] should be time/score
case "for-date":
// options[0] should be date
if options[0].Name != "date" {
sendUserError(s, i, true, true, "There was an issue processing the command! Sorry ):")
fmt.Println("error:", errors.New("second argument of /submit for-date is not 'date'")) // this should be reported as it is sTrAnGe (sppooookkyyy)
return
}
// parse date
var err error
date, err = time.Parse("01/02/2006", options[0].StringValue())
if err != nil {
sendUserError(s, i, true, true, "I could not understand the date you sent. Please write it in the form MM/DD/YYYY.")
return
}
// options[1] should be time/score
scoreArg = 1
default:
sendUserError(s, i, true, true, "There was an issue processing the command! Sorry ):")
fmt.Println("error:", errors.New("invalid command "+options[0].Name)) // also spooky
return
}
if options[scoreArg].Name != "time" {
fmt.Println("error:", errors.New("second argument of /submit today is not 'time'"))
return
}
// parse score
score, err := parseScore(options[scoreArg].StringValue())
if err != nil {
sendUserError(s, i, true, true, "I couldn't understand the time you submitted. Please make sure it's a real amount of time and it looks like Minutes:Seconds.")
return
}
err = submitScore(s, date, member, *score)
if err != nil {
// Log the error and inform the user of the issue
fmt.Println("error submitting score:", err)
sendUserError(s, i, true, true, "There was an issue submitting yoru score. Please try again later.")
return
}
// Tell user their time was submitted
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{
{
Title: "Submitted successfully!",
Description: fmt.Sprintf("Your time of `%s` on `%s` has been submitted successfully.", score.String(), date.Format("01/02/2006")),
},
},
})
if err != nil {
fmt.Println("error sending interaction response:", err)
}
}
func submitScore(_ *discordgo.Session, d time.Time, member *discordgo.Member, score Score) error {
id := member.User.ID
nickname := member.Nick
if nickname == "" {
nickname = member.User.Username
}
// log that we are submitting a score
fmt.Printf("Submitting score for %s: %s - %s\n", nickname, d.Format("01/02/2006"), score.String())
// Open db connection to submit score
conn, err := Db.Open()
if err != nil {
fmt.Println("error opening db connection:", err)
}
defer conn.Close()
// Submit the score
return conn.SubmitScore(id, nickname, score.Minutes, score.Seconds, d) // TODO: replace with username
}
func parseScore(score string) (*Score, error) {
segments := strings.Split(score, ":")
if len(segments) != 2 {
return nil, errors.New("too many ':' in score string")
}
minutes, errM := strconv.Atoi(segments[0])
seconds, errS := strconv.Atoi(segments[1])
fmt.Printf("time: %d:%d\n", minutes, seconds)
if errM != nil || errS != nil {
return nil, errors.New("unable to parse numbers in score string")
}
if minutes < 0 || 60 <= minutes {
return nil, errors.New("minutes outside range")
}
if seconds < 0 || 60 <= seconds {
return nil, errors.New("seconds outside range")
}
return &Score{minutes, seconds}, nil
}
func leaderboardHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
// acknowledge command is received and tell discord we will respond later
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseDeferredChannelMessageWithSource,
})
if err != nil {
fmt.Println("error sending defer response:", err)
return
}
// open database connection
conn, err := Db.Open()
if err != nil {
fmt.Println("error opening database connection:", err)
}
defer conn.Close()
// request top 10 scores
top, err := conn.QueryTopScores(10)
if err != nil {
sendUserError(s, i, true, false, "There was an issue processing the command! Sorry ):")
fmt.Println("error querying db for top scores:", err)
return
}
// loop through all and craft message
var msg strings.Builder
msg.WriteString("Here are the top 10 scores of all time: ```\n") // notice backticks to make code block
for i, sr := range top {
s := Score{Minutes: sr.Minutes, Seconds: sr.Seconds}
// i+1 time username date
msg.WriteString(fmt.Sprintf("%d) %s by %s on %s\n", i+1, s.String(), sr.User, sr.Date.Format("1/2/2006")))
}
// finish message and send to user
msg.WriteString("```") // close code block lol
// Send the leaderboard
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Embeds: &[]*discordgo.MessageEmbed{
{
Title: "Leaderboard",
Description: msg.String(),
},
},
})
if err != nil {
fmt.Println("error sending interaction response:", err)
}
}
func changeNameHandler(s *discordgo.Session, i *discordgo.InteractionCreate) {
// Process args
options := i.ApplicationCommandData().Options
if len(options) != 1 {
sendUserError(s, i, false, true, "There was an issue with your command [):]. Please try again.")
fmt.Println("changeNameHandler: options has ", len(options), "args")
return
}
nOpt := options[0]
if nOpt.Name != "name" {
sendUserError(s, i, false, true, "There was an issue with your command [):]. Please try again.")
fmt.Println("changeNameHandler: nOpt has name ", nOpt.Name)
return
}
name := nOpt.StringValue()
// Connect to database
conn, err := Db.Open()
if err != nil {
sendUserError(s, i, false, true, "There was an error trying to change your name. Sorry.")
fmt.Println("error opening db connection:", err)
return
}
defer conn.Close()
// send new name to database
err = conn.SetNickname(i.Member.User.ID, name)
if err != nil {
sendUserError(s, i, false, true, "There was an error trying to change your name. Sorry.")
fmt.Println("error while setting nickname:", err)
return
}
// tell user that the name change was successful
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: fmt.Sprintf("Successfully changed your name to `%s`!", name),
Flags: discordgo.MessageFlagsEphemeral,
},
})
}