-
Notifications
You must be signed in to change notification settings - Fork 0
/
irc2slack.go
401 lines (344 loc) · 10.4 KB
/
irc2slack.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"regexp"
"strings"
"sync"
"time"
"gopkg.in/yaml.v2"
)
// Config structure to hold the yaml configuration
type Config struct {
IRC struct {
Server string `yaml:"server"`
Channel string `yaml:"channel"`
Nickname string `yaml:"nickname"`
} `yaml:"irc"`
Slack struct {
WebhookURL string `yaml:"webhook_url"`
ListenAddress string `yaml:"listen_address"`
APIToken string `yaml:"api_token"`
IgnoreBots bool `yaml:"ignore_bots"`
IgnoreUsers []string `yaml:"ignore_users"`
} `yaml:"slack"`
}
// IRCConnection holds the connection and related data
type IRCConnection struct {
conn net.Conn
mutex sync.Mutex
config *Config
}
// SlackEvent represents the structure of incoming Slack events
type SlackEvent struct {
Type string `json:"type"`
Challenge string `json:"challenge"`
Event struct {
Type string `json:"type"`
User string `json:"user"`
Text string `json:"text"`
Channel string `json:"channel"`
BotID string `json:"bot_id,omitempty"`
Subtype string `json:"subtype,omitempty"`
} `json:"event"`
}
// SlackUserInfo represents user information from Slack API
type SlackUserInfo struct {
Ok bool `json:"ok"`
User struct {
Profile struct {
DisplayName string `json:"display_name"`
RealName string `json:"real_name"`
} `json:"profile"`
} `json:"user"`
}
// UserCache holds user display names with expiration
type UserCache struct {
displayName string
expiration time.Time
}
var (
// Cache user info for 1 hour
userCache = make(map[string]UserCache)
userCacheMux sync.RWMutex
cacheDuration = 1 * time.Hour
// Regex for finding user mentions in Slack messages
mentionRegex = regexp.MustCompile(`<@(U[A-Z0-9]+)>`)
)
func translateMentions(text string, config *Config) string {
return mentionRegex.ReplaceAllStringFunc(text, func(mention string) string {
matches := mentionRegex.FindStringSubmatch(mention)
if len(matches) < 2 {
return mention
}
userID := matches[1]
displayName := getUserDisplayName(userID, config)
return "@" + displayName
})
}
func getUserDisplayName(userID string, config *Config) string {
// Check cache first
userCacheMux.RLock()
if cache, exists := userCache[userID]; exists && time.Now().Before(cache.expiration) {
userCacheMux.RUnlock()
return cache.displayName
}
userCacheMux.RUnlock()
// Fetch from Slack API
url := fmt.Sprintf("https://slack.com/api/users.info?user=%s", userID)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Printf("Error creating request: %v", err)
return userID
}
req.Header.Add("Authorization", "Bearer "+config.Slack.APIToken)
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Printf("Error fetching user info: %v", err)
return userID
}
defer resp.Body.Close()
var userInfo SlackUserInfo
if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
log.Printf("Error decoding user info: %v", err)
return userID
}
if !userInfo.Ok {
log.Printf("Error from Slack API for user %s", userID)
return userID
}
// Use display name if set, otherwise use real name
displayName := userInfo.User.Profile.DisplayName
if displayName == "" {
displayName = userInfo.User.Profile.RealName
}
if displayName == "" {
displayName = userID
}
// Update cache
userCacheMux.Lock()
userCache[userID] = UserCache{
displayName: displayName,
expiration: time.Now().Add(cacheDuration),
}
userCacheMux.Unlock()
return displayName
}
func main() {
config := loadConfig("config.yaml")
// Create a channel to signal connection status
connectionReady := make(chan *IRCConnection)
// Start IRC connection management
go manageIRCConnection(config, connectionReady)
// Wait for initial connection
ircConn := <-connectionReady
// Start webhook listener
log.Printf("Starting Slack webhook listener on %s", config.Slack.ListenAddress)
http.HandleFunc("/webhook", createWebhookHandler(ircConn))
if err := http.ListenAndServe(config.Slack.ListenAddress, nil); err != nil {
log.Fatalf("Failed to start webhook listener: %v", err)
}
}
func shouldProcessMessage(event *SlackEvent, config *Config) bool {
// Ignore messages with subtypes (like bot_message, message_changed, etc.)
if event.Event.Subtype != "" {
return false
}
// Ignore bot messages if configured
if config.Slack.IgnoreBots && event.Event.BotID != "" {
return false
}
// Check if user is in ignore list
for _, ignoredUser := range config.Slack.IgnoreUsers {
if event.Event.User == ignoredUser {
return false
}
}
return true
}
func createWebhookHandler(ircConn *IRCConnection) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var event SlackEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
log.Printf("Error decoding webhook payload: %v", err)
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
// Handle URL verification challenge
if event.Type == "url_verification" {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(event.Challenge))
return
}
// Handle message events
if event.Type == "event_callback" && event.Event.Type == "message" {
// Check if we should process this message
if !shouldProcessMessage(&event, ircConn.config) {
w.WriteHeader(http.StatusOK)
return
}
// Get user's display name
displayName := getUserDisplayName(event.Event.User, ircConn.config)
// Translate any @mentions in the message
translatedText := translateMentions(event.Event.Text, ircConn.config)
// Send message to IRC using the shared connection
ircMessage := fmt.Sprintf("PRIVMSG %s :<%s> %s\r\n",
ircConn.config.IRC.Channel,
displayName,
translatedText)
// Use mutex to ensure thread-safe writes to the connection
ircConn.mutex.Lock()
_, err := fmt.Fprintf(ircConn.conn, ircMessage)
ircConn.mutex.Unlock()
if err != nil {
log.Printf("Error sending message to IRC: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
}
// Acknowledge receipt of the event
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
}
}
func manageIRCConnection(config *Config, ready chan<- *IRCConnection) {
var ircConn *IRCConnection
firstConnection := true
for {
conn, err := net.Dial("tcp", config.IRC.Server)
if err != nil {
log.Printf("Failed to connect to IRC server: %v", err)
if firstConnection {
log.Fatalf("Failed to establish initial IRC connection")
}
continue
}
ircConn = &IRCConnection{
conn: conn,
config: config,
}
// Send IRC authentication
fmt.Fprintf(conn, "NICK %s\r\n", config.IRC.Nickname)
fmt.Fprintf(conn, "USER %s 8 * :%s\r\n", config.IRC.Nickname, config.IRC.Nickname)
fmt.Fprintf(conn, "JOIN %s\r\n", config.IRC.Channel)
if firstConnection {
ready <- ircConn
firstConnection = false
}
// Handle incoming IRC messages
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
log.Printf("Error reading from IRC: %v", err)
break
}
handleMessage(message, ircConn, config.Slack.WebhookURL)
}
// If we get here, the connection was lost
log.Println("IRC connection lost, reconnecting...")
}
}
func handleMessage(message string, ircConn *IRCConnection, slackWebhookURL string) {
// Print message to console (for debugging)
fmt.Print(message)
// Respond to PING messages to avoid being disconnected
if strings.HasPrefix(message, "PING") {
response := strings.Replace(message, "PING", "PONG", 1)
ircConn.mutex.Lock()
fmt.Fprintf(ircConn.conn, response)
ircConn.mutex.Unlock()
return
}
// Detect JOIN event
if strings.Contains(message, "JOIN") {
nickname := extractNickname(message)
formattedMessage := fmt.Sprintf("*%s has joined the channel*", nickname)
postToSlack(formattedMessage, slackWebhookURL)
return
}
// Detect PART event
if strings.Contains(message, "PART") {
nickname := extractNickname(message)
formattedMessage := fmt.Sprintf("*%s has left the channel*", nickname)
postToSlack(formattedMessage, slackWebhookURL)
return
}
// Detect ACTION (/me) event
if strings.Contains(message, "PRIVMSG") && strings.Contains(message, "ACTION") {
nickname := extractNickname(message)
actionMessage := extractActionMessage(message)
formattedMessage := fmt.Sprintf("_%s %s_", nickname, actionMessage)
postToSlack(formattedMessage, slackWebhookURL)
return
}
// Handle regular PRIVMSG (chat messages)
if strings.Contains(message, "PRIVMSG") {
nickname := extractNickname(message)
ircMessage := extractIRCMessage(message)
formattedMessage := fmt.Sprintf("<%s> %s", nickname, ircMessage)
postToSlack(formattedMessage, slackWebhookURL)
}
}
// Extract the nickname from an IRC message
func extractNickname(message string) string {
prefixEnd := strings.Index(message, "!")
if prefixEnd == -1 {
return ""
}
return message[1:prefixEnd]
}
// Extract the regular IRC message
func extractIRCMessage(message string) string {
messageParts := strings.SplitN(message, ":", 3)
if len(messageParts) > 2 {
return messageParts[2]
}
return ""
}
// Extract the ACTION message (/me command)
func extractActionMessage(message string) string {
start := strings.Index(message, "ACTION") + len("ACTION ")
end := strings.Index(message[start:], "")
if end == -1 {
return message[start:]
}
return message[start : start+end]
}
func postToSlack(message, slackWebhookURL string) {
// Escape special characters in the message
escapedMessage := strings.ReplaceAll(message, `"`, `\"`)
// Prepare the payload for the Slack webhook
payload := fmt.Sprintf(`{"text": "%s"}`, escapedMessage)
fmt.Println("Payload:", payload) // Print the payload for debugging
resp, err := http.Post(slackWebhookURL, "application/json", strings.NewReader(payload))
if err != nil {
log.Printf("Error sending message to Slack: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Printf("Received non-OK response from Slack: %s", resp.Status)
}
}
func loadConfig(filename string) *Config {
config := &Config{}
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatalf("Error reading config file: %v", err)
}
err = yaml.Unmarshal(data, config)
if err != nil {
log.Fatalf("Error parsing config file: %v", err)
}
return config
}