-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvote.go
481 lines (422 loc) Β· 13.5 KB
/
vote.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
package slash
import (
"fmt"
"time"
"github.com/bwmarrin/discordgo"
"github.com/google/uuid"
"github.com/ritsec/ops-bot-iii/commands/slash/permission"
"github.com/ritsec/ops-bot-iii/config"
"github.com/ritsec/ops-bot-iii/data"
"github.com/ritsec/ops-bot-iii/helpers"
"github.com/ritsec/ops-bot-iii/logging"
"github.com/ritsec/ops-bot-iii/structs"
"github.com/sirupsen/logrus"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
var (
// VoteURL is the URL for the vote page
VoteURL = config.GetString("commands.vote.url")
)
// Vote is a slash command that creates a vote
func Vote() (*discordgo.ApplicationCommand, func(s *discordgo.Session, i *discordgo.InteractionCreate)) {
return &discordgo.ApplicationCommand{
Name: "vote",
Description: "Create Vote",
Options: []*discordgo.ApplicationCommandOption{
{
Type: discordgo.ApplicationCommandOptionString,
Name: "title",
Description: "Title of the vote to be created",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_1",
Description: "First option for the vote",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_2",
Description: "Second option for the vote",
Required: true,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_3",
Description: "Third option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_4",
Description: "Fourth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_5",
Description: "Fifth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_6",
Description: "Sixth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_7",
Description: "Seventh option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_8",
Description: "Eighth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_9",
Description: "Ninth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_10",
Description: "Tenth option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_11",
Description: "Eleventh option for the vote",
Required: false,
},
{
Type: discordgo.ApplicationCommandOptionString,
Name: "option_12",
Description: "Twelvth option for the vote",
Required: false,
},
},
DefaultMemberPermissions: &permission.Admin,
},
func(s *discordgo.Session, i *discordgo.InteractionCreate) {
span := tracer.StartSpan(
"commands.slash.vote:Vote",
tracer.ResourceName("/vote"),
)
defer span.Finish()
logging.Debug(s, "Vote Command Recieved", i.Member.User, span)
title := i.ApplicationCommandData().Options[0].StringValue()
intOptions := len(i.ApplicationCommandData().Options) - 1
rawOptions := func() []string {
var options []string
for j := 0; j < intOptions; j++ {
options = append(options, i.ApplicationCommandData().Options[j+1].StringValue())
}
return options
}()
location, err := time.LoadLocation("America/New_York")
if err != nil {
logging.Error(s, err.Error(), i.Member.User, span)
}
voteDuration := 5 * time.Minute
voteEndTime := time.Now().In(location).Add(voteDuration).Format("3:04PM")
if !helpers.IsUnique(rawOptions) {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "Error: All options must be unique",
},
})
if err != nil {
logging.Error(s, err.Error(), nil, span)
}
return
}
voteSlug := uuid.New().String()
(*ComponentHandlers)[voteSlug] = func(s *discordgo.Session, i *discordgo.InteractionCreate) {
span_voteSlug := tracer.StartSpan(
"commands.slash.vote:Vote:voteSlug",
tracer.ResourceName("/vote:voteSlug"),
tracer.ChildOf(span.Context()),
)
defer span.Finish()
options := make([]string, len(rawOptions))
copy(options, rawOptions)
signins, err := data.Signin.GetSignins(i.Member.User.ID, span.Context())
if err != nil {
logging.Error(s, err.Error(), i.Member.User, span_voteSlug)
return
}
if signins < 3 {
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Flags: discordgo.MessageFlagsEphemeral,
Content: "Error: You must have at least 3 signins to vote",
},
})
if err != nil {
logging.Error(s, err.Error(), nil, span_voteSlug, logrus.Fields{"error": err})
}
return
}
i, ranking, err := voteGetVote(s, i, options, span_voteSlug.Context())
if err != nil {
logging.Error(s, err.Error(), nil, span_voteSlug, logrus.Fields{"error": err})
return
}
for j, option := range ranking {
_, err := data.Vote.Create(i.Member.User.ID, voteSlug, option, j, span.Context())
if err != nil {
logging.Error(s, err.Error(), i.Member.User, span_voteSlug, logrus.Fields{"error": err})
return
}
}
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: func() string {
response := fmt.Sprintf("Voting submitted for: **%s**\n", title)
response += "Ranking:\n"
for _, option := range ranking {
response += fmt.Sprintf("- **%s**\n", option)
}
response += "\nThanks for voting!\nIf you wish to overwrite the votes, just use the vote button to vote again!\n"
return response
}(),
Components: []discordgo.MessageComponent{},
},
})
if err != nil {
logging.Error(s, err.Error(), i.Member.User, span_voteSlug, logrus.Fields{"error": err})
return
}
}
err = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: func() string {
response := fmt.Sprintf("Voting opened for: **%s**\n", title)
response += fmt.Sprintf("Voting will close at: **%s**\n", voteEndTime)
response += "Options:\n"
for _, option := range rawOptions {
response += fmt.Sprintf("- **%s**\n", option)
}
response += "\nVote by clicking the below button\n"
return response
}(),
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.Button{
Label: "Vote",
Style: discordgo.SuccessButton,
CustomID: voteSlug,
Emoji: &discordgo.ComponentEmoji{
Name: "π³οΈ",
},
},
},
},
},
},
})
if err != nil {
logging.Error(s, err.Error(), i.Member.User, span, logrus.Fields{"error": err})
return
}
time.Sleep(voteDuration)
delete(*ComponentHandlers, voteSlug)
results, err := voteRankChoiceVoting(title, rawOptions, voteSlug, span.Context())
if err != nil {
logging.Error(s, err.Error(), nil, span, logrus.Fields{"error": err})
return
}
entVoteResults, err := data.VoteResult.Create(voteSlug, results.HTML(), results.String(), span.Context())
if err != nil {
logging.Error(s, err.Error(), nil, span, logrus.Fields{"error": err})
return
}
out := "```\n" + entVoteResults.Plain + "\n```" + "\nResults Graph:\n" + VoteURL + "/vote/" + voteSlug + "\n"
_, err = s.InteractionResponseEdit(i.Interaction, &discordgo.WebhookEdit{
Content: &out,
Components: &[]discordgo.MessageComponent{},
})
if err != nil {
logging.Error(s, err.Error(), nil, span, logrus.Fields{"error": err})
return
}
_, err = data.Vote.DeleteAll(voteSlug, span.Context())
if err != nil {
logging.Error(s, err.Error(), nil, span, logrus.Fields{"error": err})
}
}
}
// voteRankChoiceVoting is a helper function to calculate the results of a rank choice vote
func voteRankChoiceVoting(title string, rawOptions []string, voteID string, ctx ddtrace.SpanContext) (structs.RankChoiceVote, error) {
span := tracer.StartSpan(
"commands.slash.vote:voteRankChoiceVoting",
tracer.ResourceName("/vote:rankchoice"),
tracer.ChildOf(ctx),
)
defer span.Finish()
var (
vote structs.RankChoiceVote
options []string = make([]string, len(rawOptions))
)
vote.Title = title
vote.Options = make([]string, len(rawOptions))
copy(options, rawOptions)
copy(vote.Options, rawOptions)
for i := 1; i < len(rawOptions); i++ {
round, err := data.Vote.GetRound(voteID, span.Context())
if err != nil {
return vote, err
}
vote.Rounds = append(vote.Rounds, structs.ConvertToRound(round, options))
eliminationPool := helpers.EliminationPool(round, options)
if helpers.IsEmpty(eliminationPool) {
return vote, fmt.Errorf("empty elimination pool")
}
eliminated := helpers.Choose(eliminationPool)
_, err = data.Vote.RemoveChoice(voteID, eliminated, span.Context())
if err != nil {
return vote, err
}
options = helpers.Remove(options, eliminated)
vote.Eliminations = append(vote.Eliminations, eliminated)
}
round, err := data.Vote.GetRound(voteID, span.Context())
if err != nil {
return vote, err
}
vote.Rounds = append(vote.Rounds, structs.ConvertToRound(round, options))
vote.Winner = func() string {
for choice := range round {
return choice
}
return ""
}()
return vote, nil
}
// voteGetVote is a helper function to get the vote from a user
func voteGetVote(s *discordgo.Session, i *discordgo.InteractionCreate, rawOptions []string, ctx ddtrace.SpanContext) (*discordgo.InteractionCreate, []string, error) {
span := tracer.StartSpan(
"commands.slash.vote:voteGetVote",
tracer.ResourceName("/vote:getvote"),
tracer.ChildOf(ctx),
)
defer span.Finish()
ranking := []string{}
options := make([]string, len(rawOptions))
copy(options, rawOptions)
selectionChan := make(chan string)
defer close(selectionChan)
interactionCreateChan := make(chan *discordgo.InteractionCreate)
defer close(interactionCreateChan)
messageSlug := uuid.New().String()
(*ComponentHandlers)[messageSlug] = func(s *discordgo.Session, i *discordgo.InteractionCreate) {
selectionChan <- i.MessageComponentData().Values[0]
interactionCreateChan <- i
}
emojis := []string{
"π₯",
"π§",
"π©",
"π¦",
"πͺ",
"β¬",
"β¬",
"π₯",
"π§",
"π©",
"π¦",
"πͺ",
"β¬",
"β¬",
}
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseChannelMessageWithSource,
Data: &discordgo.InteractionResponseData{
Content: "Please select your highest ranked option\n",
Flags: discordgo.MessageFlagsEphemeral,
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
CustomID: messageSlug,
Options: func() []discordgo.SelectMenuOption {
var innerOptions []discordgo.SelectMenuOption
for j, option := range options {
innerOptions = append(innerOptions, discordgo.SelectMenuOption{
Label: option,
Value: option,
Emoji: &discordgo.ComponentEmoji{
Name: emojis[j],
},
})
}
return innerOptions
}(),
},
},
},
},
},
})
if err != nil {
return nil, nil, err
}
selection := <-selectionChan
i = <-interactionCreateChan
ranking = append(ranking, selection)
options = helpers.Remove(options, selection)
for len(options) > 1 {
err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
Type: discordgo.InteractionResponseUpdateMessage,
Data: &discordgo.InteractionResponseData{
Content: "Please select your highest ranked option\n",
Flags: discordgo.MessageFlagsEphemeral,
Components: []discordgo.MessageComponent{
discordgo.ActionsRow{
Components: []discordgo.MessageComponent{
discordgo.SelectMenu{
CustomID: messageSlug,
Options: func() []discordgo.SelectMenuOption {
var innerOptions []discordgo.SelectMenuOption
for j, option := range options {
innerOptions = append(innerOptions, discordgo.SelectMenuOption{
Label: option,
Value: option,
Emoji: &discordgo.ComponentEmoji{
Name: emojis[j],
},
})
}
return innerOptions
}(),
},
},
},
},
},
})
if err != nil {
return nil, nil, err
}
selection := <-selectionChan
i = <-interactionCreateChan
ranking = append(ranking, selection)
options = helpers.Remove(options, selection)
}
ranking = append(ranking, options[0])
return i, ranking, nil
}