-
Notifications
You must be signed in to change notification settings - Fork 20
/
bot.go
189 lines (164 loc) · 4.7 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
package bruxism
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"runtime/debug"
)
// VersionString is the current version of the bot
const VersionString string = "0.12"
type serviceEntry struct {
Service
Plugins map[string]Plugin
messageChannels []chan Message
}
// Bot enables registering of Services and Plugins.
type Bot struct {
Services map[string]*serviceEntry
ImgurID string
ImgurAlbum string
MashableKey string
}
// MessageRecover is the default panic handler for bruxism.
func MessageRecover() {
if r := recover(); r != nil {
log.Println("Recovered:", string(debug.Stack()))
}
}
// NewBot will create a new bot.
func NewBot() *Bot {
return &Bot{
Services: make(map[string]*serviceEntry, 0),
}
}
func (b *Bot) PluginFile(service Service, plugin Plugin) string {
return service.Name() + "/" + plugin.Name()
}
func (b *Bot) getData(service Service, plugin Plugin) []byte {
if b, err := ioutil.ReadFile(b.PluginFile(service, plugin)); err == nil {
return b
}
return nil
}
// RegisterService registers a service with the bot.
func (b *Bot) RegisterService(service Service) {
if b.Services[service.Name()] != nil {
log.Println("Service with that name already registered", service.Name())
}
serviceName := service.Name()
b.Services[serviceName] = &serviceEntry{
Service: service,
Plugins: make(map[string]Plugin, 0),
}
b.RegisterPlugin(service, NewHelpPlugin())
}
// RegisterPlugin registers a plugin on a service.
func (b *Bot) RegisterPlugin(service Service, plugin Plugin) {
s := b.Services[service.Name()]
if s.Plugins[plugin.Name()] != nil {
log.Println("Plugin with that name already registered", plugin.Name())
}
s.Plugins[plugin.Name()] = plugin
}
func (b *Bot) listen(service Service, messageChan <-chan Message) {
serviceName := service.Name()
for {
message := <-messageChan
//log.Printf("<%s> %s: %s\n", message.Channel(), message.UserName(), message.Message())
plugins := b.Services[serviceName].Plugins
for _, plugin := range plugins {
go plugin.Message(b, service, message)
}
}
}
// Open will open all the current services and begins listening.
func (b *Bot) Open() {
log.Printf("Bot opening")
for _, service := range b.Services {
log.Printf("Opening service %s\n", service.Name())
if messageChan, err := service.Open(); err == nil {
for _, plugin := range service.Plugins {
err := plugin.Load(b, service.Service, b.getData(service, plugin))
if err != nil {
log.Printf("Error loading plugin %s/%s: %v\n", service.Name(), plugin.Name(), err)
}
}
go b.listen(service.Service, messageChan)
log.Printf("Opened service %s\n", service.Name())
} else {
log.Printf("Error creating service %s: %v\n", service.Name(), err)
}
}
log.Printf("Bot opened")
}
// Save will save the current plugin state for all plugins on all services.
func (b *Bot) Save() {
for _, service := range b.Services {
serviceName := service.Name()
if err := os.Mkdir(serviceName, os.ModePerm); err != nil {
if !os.IsExist(err) {
log.Println("Error creating service directory.")
}
}
for _, plugin := range service.Plugins {
if data, err := plugin.Save(); err != nil {
log.Printf("Error saving plugin %s %s. %v", serviceName, plugin.Name(), err)
} else if data != nil {
if err := ioutil.WriteFile(serviceName+"/"+plugin.Name(), data, os.ModePerm); err != nil {
log.Printf("Error saving plugin %s %s. %v", serviceName, plugin.Name(), err)
}
}
}
}
}
// UploadToImgur uploads image data to Imgur and returns the url to it.
func (b *Bot) UploadToImgur(re io.Reader, filename string) (string, error) {
if b.ImgurID == "" {
return "", errors.New("No Imgur client ID provided.")
}
bodyBuf := &bytes.Buffer{}
bodywriter := multipart.NewWriter(bodyBuf)
writer, err := bodywriter.CreateFormFile("image", filename)
if err != nil {
return "", err
}
_, err = io.Copy(writer, re)
if err != nil {
return "", err
}
contentType := bodywriter.FormDataContentType()
if b.ImgurAlbum != "" {
bodywriter.WriteField("album", b.ImgurAlbum)
}
bodywriter.Close()
r, err := http.NewRequest("POST", "https://api.imgur.com/3/image", bodyBuf)
if err != nil {
return "", err
}
r.Header.Set("Content-Type", contentType)
r.Header.Set("Authorization", "Client-ID "+b.ImgurID)
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))
}
j := make(map[string]interface{})
err = json.Unmarshal(body, &j)
if err != nil {
return "", err
}
return j["data"].(map[string]interface{})["link"].(string), nil
}