-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.go
276 lines (232 loc) · 5.01 KB
/
bot.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/gorilla/websocket"
"github.com/jbpratt78/tmdb"
)
type bot struct {
mu sync.Mutex
authToken string
address string
conn *websocket.Conn
client *tmdb.Client
}
type message struct {
Type string `json:"type"`
Contents *contents
}
type contents struct {
Nick string `json:"nick"`
Data string `json:"data"`
Timestamp int64 `json:"timestamp"`
}
type config struct {
AuthToken string `json:"auth_token"`
Address string `json:"address"`
TmdbApiKey string `json:"tmdb_api_key"`
}
var configFile string
func main() {
flag.Parse()
config, err := readConfig()
if err != nil {
log.Fatal(err)
}
bot := newBot(config)
if err = bot.setAddress(config.Address); err != nil {
log.Fatal(err)
}
err = bot.connect()
if err != nil {
bot.close()
log.Fatal(err)
}
}
func readConfig() (*config, error) {
file, err := os.Open(configFile)
if err != nil {
return nil, err
}
defer file.Close()
bv, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
var c *config
c = new(config)
err = json.Unmarshal(bv, &c)
if err != nil {
return nil, err
}
return c, err
}
func newBot(config *config) *bot {
c := tmdb.New(config.TmdbApiKey)
return &bot{authToken: ";jwt=" + config.AuthToken, client: c}
}
func (b *bot) setAddress(url string) error {
b.mu.Lock()
defer b.mu.Unlock()
if url == "" {
return errors.New("url address not supplied")
}
b.address = url
return nil
}
func (b *bot) connect() error {
b.mu.Lock()
defer b.mu.Unlock()
header := http.Header{}
header.Add("Cookie", fmt.Sprintf("authtoken=%s", b.authToken))
conn, resp, err := websocket.DefaultDialer.Dial(b.address, header)
if err != nil {
return fmt.Errorf("handshake failed with status %v", resp)
}
b.conn = conn
b.listen()
return nil
}
// TODO: handle cloudflare dc
func (b *bot) listen() {
for {
_, message, err := b.conn.ReadMessage()
fmt.Println(string(message))
if err != nil {
log.Fatal(err)
}
m, err := parseMessage(message)
if err != nil {
panic(err)
}
if m.Contents != nil {
if m.Type == "PRIVMSG" {
fmt.Println("Received", m.Contents)
err := b.send(m.Contents)
if err != nil {
fmt.Println(err)
}
}
}
}
}
func (b *bot) close() error {
b.mu.Lock()
defer b.mu.Unlock()
if b.conn == nil {
return errors.New("connection already closed")
}
err := b.conn.Close()
if err != nil {
return err
}
b.conn = nil
return nil
}
func (b *bot) send(contents *contents) error {
if b.conn == nil {
return errors.New("no connection available")
}
query := strings.Fields(contents.Data)
var response string
if len(query) < 3 {
response = "MiyanoBird"
} else {
t := query[0]
switch {
case t == "search":
k := query[1]
switch {
case k == "movie":
s, err := b.client.SearchMovie(query[2:])
if err != nil {
return err
}
response = handleMovieResult(s)
case k == "tv":
s, err := b.client.SearchTv(query[2:])
if err != nil {
return err
}
response = handleTvResult(s)
case k == "keyword":
s, err := b.client.SearchKeyword(query[2:])
if err != nil {
return err
}
response = handleKeywordResult(s)
case k == "person":
s, err := b.client.SearchPerson(query[2:])
if err != nil {
return err
}
response = handlePersonResult(s)
case k == "collection":
s, err := b.client.SearchCollection(query[2:])
if err != nil {
return err
}
response = handleCollectionResult(s)
}
case t == "discover":
case t == "trending":
default:
response = "`ERROR`"
}
}
defer fmt.Println("message sent")
return b.conn.WriteMessage(
websocket.TextMessage, []byte(
fmt.Sprintf(`PRIVMSG {"nick": "%s", "data": "%s"}`, contents.Nick, response)))
}
func parseMessage(msg []byte) (*message, error) {
received := string(msg)
m := new(message)
maxBound := strings.IndexByte(received, ' ')
if maxBound < 0 {
return nil, errors.New("couldn't parse message type.")
}
m.Type = received[:maxBound]
m.Contents = parseContents(received, len(m.Type))
return m, nil
}
func parseContents(received string, length int) *contents {
contents := contents{}
json.Unmarshal([]byte(received[length:]), &contents)
return &contents
}
func handleMovieResult(result *tmdb.SearchMovieResult) string {
var out string
fmt.Printf("%+v\n", result)
for _, r := range result.Results {
out += r.Title + " "
}
return out
}
func handleTvResult(result *tmdb.SearchTvResult) string {
fmt.Printf("%+v\n", result)
return ""
}
func handleKeywordResult(result *tmdb.SearchKeywordResult) string {
fmt.Printf("%+v\n", result)
return ""
}
func handlePersonResult(result *tmdb.SearchPersonResult) string {
fmt.Printf("%+v\n", result)
return ""
}
func handleCollectionResult(result *tmdb.SearchCollectionResult) string {
fmt.Printf("%+v\n", result)
return ""
}
func init() {
flag.StringVar(&configFile, "config", "config.json", "location of config")
}