forked from iopred/bruxism
-
Notifications
You must be signed in to change notification settings - Fork 0
/
numbertriviaplugin.go
67 lines (55 loc) · 1.58 KB
/
numbertriviaplugin.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
package numbertriviaplugin
import (
"errors"
"fmt"
"io/ioutil"
"math/rand"
"net/http"
"strconv"
"github.com/landonr/bruxism"
)
func numberTrivia(bot *bruxism.Bot, num int, notfound bool) (string, error) {
notfoundString := ""
if notfound {
notfoundString = "?notfound=floor"
}
r, err := http.NewRequest("GET", fmt.Sprintf("https://numbersapi.p.mashape.com/%d/trivia%s", num, notfoundString), nil)
if err != nil {
return "", err
}
r.Header.Set("X-Mashape-Authorization", bot.MashableKey)
r.Header.Set("Accept", "text/plain")
resp, err := http.DefaultClient.Do(r)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
if resp.StatusCode != 200 {
return "", errors.New(string(body))
}
return string(body), nil
}
// NumberTriviaCommand is a command for getting number trivial.
func NumberTriviaCommand(bot *bruxism.Bot, service bruxism.Service, message bruxism.Message, command string, parts []string) {
notfound := true
num := rand.Intn(1000)
if len(parts) == 1 {
if i, err := strconv.Atoi(parts[0]); err == nil {
num = i
notfound = false
}
}
service.Typing(message.Channel())
str, err := numberTrivia(bot, num, notfound)
if err != nil {
service.SendMessage(message.Channel(), "There was an error requesting trivia, sorry!")
return
}
service.SendMessage(message.Channel(), str)
}
// NumberTriviaHelp is the help for the number trivia plugin.
var NumberTriviaHelp = bruxism.NewCommandHelp("[number]", "Returns trivia for a random number, or a specified number if provided.")