-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathurbandictionary.go
66 lines (56 loc) · 1.8 KB
/
urbandictionary.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
package jarvisbot
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"github.com/tucnak/telebot"
)
const udSearchEndpoint = "http://api.urbandictionary.com/v0/define?term=%s"
func (j *JarvisBot) UrbanDictSearch(msg *message) {
if len(msg.Args) == 0 {
so := &telebot.SendOptions{ReplyTo: *msg.Message, ReplyMarkup: telebot.ReplyMarkup{ForceReply: true, Selective: true}}
j.SendMessage(msg.Chat, "/urbandict: Does an Urban Dictonary search\nHere are some commands to try: \n* fleek\n* sapiosexual\n\n\U0001F4A1 You could also use this format for faster results:\n/ud fleek", so)
return
}
rawQuery := ""
for _, v := range msg.Args {
rawQuery = rawQuery + v + " "
}
rawQuery = strings.TrimSpace(rawQuery)
q := url.QueryEscape(rawQuery)
urlString := fmt.Sprintf(udSearchEndpoint, q)
resp, err := http.Get(urlString)
if err != nil {
j.log.Printf("failure retrieving videos from Urban Dictionary for query '%s': %s", q, err)
return
}
jsonBody, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
j.log.Printf("failure reading json results from Urban Dictionary video search for query '%s': %s", q, err)
return
}
searchRes := struct {
List []struct {
Word string `json:"word"`
Definition string `json:"definition"`
Example string `json:"example"`
} `json:"list"`
}{}
err = json.Unmarshal(jsonBody, &searchRes)
if err != nil {
j.log.Printf("failure unmarshalling json for Urban Dictionary search query '%s': %s", q, err)
return
}
resMsg := "%s\n\nDefinition:\n%s\n\nExample:\n%s"
if len(searchRes.List) > 0 {
r := searchRes.List[0]
rm := fmt.Sprintf(resMsg, r.Word, r.Definition, r.Example)
j.SendMessage(msg.Chat, rm, nil)
} else {
j.SendMessage(msg.Chat, "My Urban Dictionary search returned nothing. \U0001F622", nil)
}
}