-
Notifications
You must be signed in to change notification settings - Fork 6
/
parrot.go
256 lines (225 loc) · 6.49 KB
/
parrot.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
package main
import (
"bytes"
"crypto/tls"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"log/syslog"
"net/http"
"os"
"regexp"
"strings"
"time"
irc "github.com/fluffle/goirc/client"
)
const CONN_RETRY_DELAY = 3
var (
useSyslog = flag.Bool("syslog", false, "Log to syslog")
nick = flag.String("nick", "parrot", "bot's nickname")
nickPassword = flag.String("nickpassword", "", "nickserv password")
ircAddress = flag.String("irc-address", "irc.freenode.net", "IRC server address")
ircSSL = flag.Bool("ssl", false, "Connect with SSL")
defaultChannel = flag.String("default-channel", "parrot", "default channel for messages, and initial channel")
httpAddress = flag.String("http-address", ":5555", "TCP address of the HTTP server")
httpURL = flag.String("http-url", "", "HTTP URL to contact the bot, and to post message")
)
// The struct going from the HTTP go routine to the IRC channel by the Bridge chan
type ChannelMessage struct {
Channel string
Message []byte
}
type IRCBridge struct {
Client *irc.Conn
Bridge chan ChannelMessage
IrcAddress string
}
func (irc *IRCBridge) Channels() []string {
cs := make([]string, 0)
for ch := range irc.Client.Me().Channels {
cs = append(cs, ch)
}
return cs
}
// goroutine blocking on receiving messages and emitting them to the appropriate chan
func (irc *IRCBridge) recv() {
for {
msg := <-irc.Bridge
channel := fmt.Sprintf("#%s", msg.Channel)
for _, line := range bytes.Split(msg.Message, []byte("\n")) {
strMsg := fmt.Sprintf("%s", line)
irc.Emit(channel, strMsg)
}
}
}
func (irc *IRCBridge) Emit(channel string, message string) {
// join channels we don't track
if _, isOn := irc.Client.StateTracker().IsOn(channel, irc.Client.Me().Nick); !isOn {
log.Println("Joining", channel)
irc.Client.Join(channel)
}
irc.Client.Privmsg(channel, message)
}
func (irc *IRCBridge) ReceiveHTTPMessage(w http.ResponseWriter, r *http.Request, channel string) {
var msg []byte
if r.Method != "POST" {
w.WriteHeader(http.StatusNotFound)
return
}
ct := r.Header.Get("Content-Type")
if ct == "application/x-www-form-urlencoded" || ct == "multipart/form-data" {
msg = []byte(strings.TrimSpace(r.FormValue("msg")))
if len(msg) == 0 {
return
}
} else {
var err error
msg, err = ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "POST error in body reading: %s", err)
return
}
}
// Can't acknowledge this message
if !irc.Client.Connected() {
log.Printf("Couldn't send '%s' to channel %s on behalf of %s",
bytes.Replace(msg, []byte("\n"), []byte("\\n"), -1),
channel,
r.RemoteAddr)
w.Header().Set("Retry-After", fmt.Sprintf("%d", CONN_RETRY_DELAY*2))
w.WriteHeader(http.StatusServiceUnavailable)
return
}
log.Printf("%s sent '%s' to channel %s",
r.RemoteAddr,
bytes.Replace(msg, []byte("\n"), []byte("\\n"), -1),
channel)
irc.Bridge <- ChannelMessage{channel, msg}
}
func (irc *IRCBridge) connectRetry() {
for err := irc.connect(); err != nil; {
time.Sleep(CONN_RETRY_DELAY * time.Second)
err = irc.connect()
}
}
func (irc *IRCBridge) connect() (err error) {
log.Printf("Connecting to IRC %s", irc.IrcAddress)
irc.Client.Config().Server = irc.IrcAddress
if *ircSSL {
irc.Client.Config().SSL = true
irc.Client.Config().SSLConfig = &tls.Config{InsecureSkipVerify: true}
}
if err = irc.Client.Connect(); err != nil {
log.Printf("Connection error: %s\n", err)
}
return
}
func main() {
flag.Parse()
if *httpURL == "" {
log.Fatal("Please specify the HTTP URL for the end user to use -http-url=...")
}
if *useSyslog {
sl, err := syslog.New(syslog.LOG_INFO, "parrot")
if err != nil {
log.Fatalf("Can't initialize syslog: %v", err)
}
log.SetOutput(sl)
log.SetFlags(0)
}
filename := "home.html"
t, err := template.ParseFiles(filename)
if err != nil {
panic(err)
}
// create new IRC connection
c := irc.SimpleClient(*nick, *nick)
parrot := IRCBridge{c, make(chan ChannelMessage), *ircAddress}
// keep track of channels we're on (and much more we don't need)
c.EnableStateTracking()
c.HandleFunc("connected",
func(conn *irc.Conn, line *irc.Line) {
conn.Join(fmt.Sprintf("#%s", *defaultChannel))
log.Printf("Connected")
if len(*nickPassword) > 0 {
conn.Privmsg("NickServ", "IDENTIFY "+*nickPassword)
}
})
c.HandleFunc("disconnected",
func(conn *irc.Conn, line *irc.Line) {
conn.Join(fmt.Sprintf("#%s", *defaultChannel))
log.Printf("Oops got disconnected, retrying to connect...")
go parrot.connectRetry()
})
c.HandleFunc("NOTICE",
func(conn *irc.Conn, line *irc.Line) {
log.Printf("NOTICE: %s", line.Raw)
})
c.HandleFunc("PRIVMSG",
func(conn *irc.Conn, line *irc.Line) {
channel := line.Args[0]
message := line.Args[1]
standardDisclaimer := fmt.Sprintf("I'm not very smart, see %s", *httpURL)
r, err := regexp.Compile(fmt.Sprintf("(?i:%s|%s|parrot)(?::|,)",
regexp.QuoteMeta(*nick),
regexp.QuoteMeta(conn.Me().Nick)))
if err != nil {
log.Printf("err: %s, %s\n", conn.Me().Nick, err)
return
}
if channel == conn.Me().Nick {
log.Printf("%s said to me %s: %s\n", line.Nick, channel, message)
conn.Privmsg(line.Nick, standardDisclaimer)
} else if r.MatchString(message) {
log.Printf("%s said to me %s: %s\n", line.Nick, channel, message)
conn.Privmsg(channel, standardDisclaimer)
}
})
// Print a small SYNOPSIS on home page of the HTTP server
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" || r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
return
}
home := struct {
Nick string
Channels []string
Url string
HttpAddress string
IrcAddress string
}{
parrot.Client.Me().Nick,
parrot.Channels(),
*httpURL,
*httpAddress,
parrot.IrcAddress,
}
t.Execute(w, home)
})
// Message handlers
http.HandleFunc("/post/", func(w http.ResponseWriter, r *http.Request) {
lenPath := len("/post/")
channel := r.URL.Path[lenPath:]
if len(strings.TrimSpace(channel)) == 0 {
channel = *defaultChannel
}
parrot.ReceiveHTTPMessage(w, r, channel)
})
http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) {
parrot.ReceiveHTTPMessage(w, r, *defaultChannel)
})
// start receiver
go parrot.recv()
// connect to irc server
ircerr := parrot.connect()
if ircerr != nil {
os.Exit(1)
}
log.Printf("HTTP server running at %s", *httpAddress)
httpErr := http.ListenAndServe(*httpAddress, nil)
if httpErr != nil {
log.Fatalf("HTTP error: %s", httpErr)
}
}