-
Notifications
You must be signed in to change notification settings - Fork 0
/
quiz.go
474 lines (407 loc) · 11.4 KB
/
quiz.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"sort"
"strings"
"sync"
"time"
"github.com/osm/irc"
)
// initQuizDefaults sets default values for the quiz commands and messages.
func (b *bot) initQuizDefaults() {
// Commands.
if b.IRC.QuizCmd == "" {
b.IRC.QuizCmd = "!quiz"
}
if b.IRC.QuizSubCmdStart == "" {
b.IRC.QuizCmd = "start"
}
if b.IRC.QuizSubCmdStop == "" {
b.IRC.QuizCmd = "stop"
}
if b.IRC.QuizSubCmdStats == "" {
b.IRC.QuizCmd = "stats"
}
// Hint interval.
if b.IRC.QuizHintInterval == 0 {
b.IRC.QuizHintInterval = 15
}
// Messages.
if b.IRC.QuizMsgNameDoesNotExist == "" {
b.IRC.QuizMsgNameDoesNotExist = "<name> does not exist"
}
if b.IRC.QuizMsgLoadError == "" {
b.IRC.QuizMsgLoadError = "unable to load <name>"
}
if b.IRC.QuizMsgAlreadyStarted == "" {
b.IRC.QuizMsgAlreadyStarted = "a quiz is already started"
}
if b.IRC.QuizMsgQuestion == "" {
b.IRC.QuizMsgQuestion = "<category>: <question>"
}
if b.IRC.QuizMsgHint == "" {
b.IRC.QuizMsgHint = "hint: <text>"
}
if b.IRC.QuizMsgAnswer == "" {
b.IRC.QuizMsgHint = "answer: <text>"
}
if b.IRC.QuizMsgCorrect == "" {
b.IRC.QuizMsgCorrect = "correct! one point to <nick>"
}
if b.IRC.QuizMsgQuizEnd == "" {
b.IRC.QuizMsgQuizEnd = "the quiz is over"
}
// Initialize the quiz sources cache.
b.IRC.quizSourcesCache = make(map[string][]QuizQuestion)
}
// quizHandler handles all IRC related communication with the quiz bot.
func (b *bot) quizHandler(m *irc.Message) {
a := b.parseAction(m).(*privmsgAction)
if !a.validChannel {
return
}
if b.shouldIgnore(m) {
return
}
// Handle the quiz IRC commands.
if len(a.args) == 2 &&
a.cmd == b.IRC.QuizCmd &&
a.args[0] == b.IRC.QuizSubCmdStart {
b.quizStart(a.args[1])
return
} else if len(a.args) == 1 &&
a.cmd == b.IRC.QuizCmd &&
a.args[0] == b.IRC.QuizSubCmdStop &&
b.IRC.quizRound != nil {
b.IRC.quizRound.stop()
return
}
// No active quiz round, return immediately.
if b.IRC.quizRound == nil {
return
}
// Check if the given message was the correct answer for the question.
b.IRC.quizRound.answer(a.nick, a.msg)
}
// quizStart starts a quiz with the given name.
func (b *bot) quizStart(name string) {
// Don't allow a new quiz to be started if there are one running
// already.
if b.IRC.quizRound != nil {
b.privmsg(b.IRC.QuizMsgAlreadyStarted)
return
}
// Make sure that the name of the quiz exists in our database.
_, exists := b.IRC.QuizSources[name]
if !exists {
b.privmsgph(b.IRC.QuizMsgNameDoesNotExist, map[string]string{
"<name>": name,
})
return
}
// Initialize a new quiz round and pop the first question.
b.IRC.quizRound = newQuizRound(b, name, 10)
if b.IRC.quizRound != nil {
b.IRC.quizRound.getQuestion()
}
}
// quizQuestion defines the data structure that holds information about a
// question in the quiz.
type QuizQuestion struct {
Category string `json:"category"`
Question string `json:"question"`
Answer string `json:"answer"`
}
// quizRound defines the structure that holds all the data that is required
// for the quiz run.
type quizRound struct {
// id is a random UUID that should be unique for each quiz round. It
// is used only for the purpose of making the database data easier to
// query.
id string
// name is the name of the quiz source that is defined in the
// configuration file.
name string
// ch is a channel that is used to stop the hint goroutines early if
// the correct answer has been given by a user.
ch chan bool
// mu is a mutex that will be used to make sure that we don't get a
// race condition when answering questions.
mu sync.Mutex
// bot is just a pointer to the bot.
bot *bot
// stats holds information about the current quiz round.
stats map[string]int
// question is the current question that.
question QuizQuestion
// questions holds all the questions for the current quiz round.
questions []QuizQuestion
}
// quizLoadFromFile reads the given file path into memory and returns a slice
// of quiz questions.
func quizLoadFromFile(filePath string) ([]QuizQuestion, error) {
file, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("quizLoadFromFile: cant open quiz file %s, %v", filePath, err)
}
var questions []QuizQuestion
err = json.Unmarshal(file, &questions)
if err != nil {
return nil, fmt.Errorf("quizLoadFromFile: cant decode quiz file, %v", err)
}
return questions, nil
}
// quizLoadFromHttp loads quiz questions from the given url.
func quizLoadFromHttp(url string) ([]QuizQuestion, error) {
res, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("quizLoadFromHttp: cant open url %s, %v", url, err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("quizLoadFromHttp: cant read body from %s, %v", url, err)
}
var questions []QuizQuestion
err = json.Unmarshal(body, &questions)
if err != nil {
return nil, fmt.Errorf("quizLoadFromHttp: cant decode quiz from %s, %s, %v", url, body, err)
}
return questions, nil
}
// quizLoadFromSql loads quiz questions by fetching data from the database.
// The query should return the fields like this:
// SELECT category, question, answer FROM blabla
func quizLoadFromSql(b *bot, query string) ([]QuizQuestion, error) {
rows, err := b.query(query)
if err != nil {
return nil, err
}
defer rows.Close()
var questions []QuizQuestion
for rows.Next() {
var c, q, a string
rows.Scan(&c, &q, &a)
questions = append(questions, QuizQuestion{c, q, a})
}
return questions, nil
}
// newQuizRound returns a new quizRound data structure.
func newQuizRound(bot *bot, name string, nQuestions int) *quizRound {
var allQuestions []QuizQuestion
var err error
path := bot.IRC.QuizSources[name]
// Load questions.
if strings.HasPrefix(path, "http") {
// Always refreh quiz from http.
allQuestions, err = quizLoadFromHttp(path)
} else if strings.HasPrefix(path, "SELECT ") {
// Load questions from the database.
allQuestions, err = quizLoadFromSql(bot, path)
} else if _, ok := bot.IRC.quizSourcesCache[name]; ok {
// The quiz exists in the cache, so just fetch it from there.
allQuestions = bot.IRC.quizSourcesCache[name]
} else {
// Fetch the quiz data from a local file.
allQuestions, err = quizLoadFromFile(path)
if err == nil {
bot.IRC.quizSourcesCache[name] = allQuestions
}
}
// Something went wrong when the quiz was loaded, log the error and
// print a message to the channel.
if err != nil {
bot.logger.Printf("%v", err)
bot.privmsgph(bot.IRC.QuizMsgLoadError, map[string]string{
"<name>": name,
})
return nil
}
// Make sure that we don't pick too many questions.
quizLen := len(allQuestions)
l := nQuestions
if l > quizLen {
l = quizLen
}
// We pick nQuestions number of questions from the source and store
// them inside the questions slice.
var questions []QuizQuestion
for i := 0; i < l; i++ {
questions = append(questions, allQuestions[rand.Int()%quizLen])
}
// Return a new quiz round with the randomly picked questions.
return &quizRound{
id: newUUID(),
name: name,
bot: bot,
ch: make(chan bool),
stats: make(map[string]int),
questions: questions,
}
}
// answer checks whether or not the given answer is the correct answer for the
// current question.
func (qr *quizRound) answer(n, a string) {
// Acquire a lock before we check whether or not the answer is
// correct.
qr.mu.Lock()
defer qr.mu.Unlock()
// The quiz round might have been completed by another goroutine, so
// let's check that before we proceed.
if qr.bot.IRC.quizRound == nil {
return
}
// Incorrect answer, return early.
if strings.ToLower(a) != strings.ToLower(qr.question.Answer) {
return
}
// Closing the channel will stop all running goroutines, which we want
// at this point. So, let's close it and create a new channel for the
// next question.
close(qr.ch)
qr.ch = make(chan bool)
// Print the correct message to the channel.
qr.bot.privmsgph(qr.bot.IRC.QuizMsgCorrect, map[string]string{
"<nick>": n,
"<text>": a,
})
// Increment the quiz round stats
if _, ok := qr.stats[n]; !ok {
qr.stats[n] = 0
}
qr.stats[n]++
// Also, add stats to the database.
stmt, err := qr.bot.prepare("INSERT INTO quiz_stat (id, nick, quiz_round_id, quiz_name, category, question, answer, inserted_at) VALUES($1, $2, $3, $4, $5, $6, $7, $8)")
if err != nil {
qr.bot.logger.Printf("quizAnswer: %v", err)
}
defer stmt.Close()
_, err = stmt.Exec(
newUUID(),
n,
qr.id,
qr.name,
qr.question.Category,
qr.question.Question,
qr.question.Answer,
newTimestamp(),
)
if err != nil {
qr.bot.logger.Printf("quizAnswer: %v", err)
}
// Pop a new qusetion.
qr.getQuestion()
}
// hint sleeps for t number of seconds before it writes the given hint back to
// the channel. If newQuestion is set to true a new question will be popped
// when the timeout occurs.
func (qr *quizRound) hint(t time.Duration, ph, text string, newQuestion bool) {
select {
case <-time.After(t * time.Second):
qr.bot.privmsgph(ph, map[string]string{
"<text>": text,
})
if newQuestion {
qr.getQuestion()
}
case <-qr.ch:
}
}
// getQuestion takes a question from the slice of questions and returns it to
// the channel.
func (qr *quizRound) getQuestion() {
if len(qr.questions) > 0 {
// Pop one question from the array.
qr.question, qr.questions = qr.questions[0], qr.questions[1:]
// Write the question to the channel.
qr.bot.privmsgph(qr.bot.IRC.QuizMsgQuestion, map[string]string{
"<category>": qr.question.Category,
"<question>": qr.question.Question,
})
// Start the hint and correct answer goroutines for the
// question.
go qr.hint(
qr.bot.IRC.QuizHintInterval,
qr.bot.IRC.QuizMsgHint,
maskText(qr.question.Answer),
false,
)
go qr.hint(
qr.bot.IRC.QuizHintInterval*2,
qr.bot.IRC.QuizMsgHint,
hintText(qr.question.Answer),
false,
)
go qr.hint(
qr.bot.IRC.QuizHintInterval*3,
qr.bot.IRC.QuizMsgAnswer,
qr.question.Answer,
true,
)
} else {
// No more questions left, stop the quiz.
qr.bot.IRC.quizRound.stop()
}
}
// stops the current quiz round early.
func (qr *quizRound) stop() {
// Quiz is over, present the results.
qr.bot.privmsg(qr.bot.IRC.QuizMsgQuizEnd)
// Construct a map of the stats but where the key is the
// number of points instead of the nick.
count := make(map[int]string)
for k, v := range qr.stats {
if _, ok := count[v]; !ok {
count[v] = k
} else {
count[v] = fmt.Sprintf("%s, %s", count[v], k)
}
}
// Sort the count map so that we can output the stats in a nicer way.
sortedKeys := make([]int, 0, len(count))
for k := range count {
sortedKeys = append(sortedKeys, k)
}
sort.Sort(sort.Reverse(sort.IntSlice(sortedKeys)))
// Output the results to the channel.
for _, k := range sortedKeys {
qr.bot.privmsg(fmt.Sprintf("%d: %s", k, count[k]))
}
close(qr.ch)
qr.bot.IRC.quizRound = nil
}
// maskText replaces all characters of the string with an asterisk unless it's
// a space.
func maskText(s string) string {
ret := ""
for _, r := range s {
if r == ' ' {
ret += " "
} else {
ret += "*"
}
}
return ret
}
// hintText replaces half of the text with *, unless it's a space, spaces are
// left untouched.
func hintText(s string) string {
ret := ""
c := 0
l := len(s)
for i, r := range s {
if r == ' ' {
ret += " "
} else if c <= l/2 && i%l >= rand.Intn(l) {
c += 1
ret += string(r)
} else {
ret += "*"
}
}
return ret
}