forked from fabioxgn/go-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.go
97 lines (84 loc) · 2.25 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
// Package bot provides a simple to use IRC bot
package bot
import (
"crypto/tls"
"github.com/thoj/go-ircevent"
"log"
"math/rand"
"strings"
"time"
)
const (
// CmdPrefix is the prefix used to identify a command.
// !hello whould be identified as a command
CmdPrefix = "!"
)
// Config must contain the necessary data to connect to an IRC server
type Config struct {
Server string // IRC server:port. Ex: irc.freenode.org:7000
Channels []string // Channels to connect. Ex: []string{"#go-bot", "#channel mypassword"}
User string // The IRC username the bot will use
Nick string // The nick the bot will use
Password string // Server password
UseTLS bool // Should connect using TLS?
TLSServerName string // Must supply if UseTLS is true
Debug bool // This will log all IRC communication to standad output
}
type ircConnection interface {
Privmsg(target, message string)
GetNick() string
Join(target string)
Part(target string)
}
var (
irccon *irc.Connection
config *Config
)
func onPRIVMSG(e *irc.Event) {
messageReceived(e.Arguments[0], e.Message(), e.Nick, irccon)
}
func getServerName() string {
separatorIndex := strings.LastIndex(config.Server, ":")
if separatorIndex != -1 {
return config.Server[:separatorIndex]
} else {
return config.Server
}
}
func connect() {
irccon = irc.IRC(config.User, config.Nick)
irccon.Password = config.Password
irccon.UseTLS = config.UseTLS
irccon.TLSConfig = &tls.Config{
ServerName: getServerName(),
}
irccon.VerboseCallbackHandler = config.Debug
err := irccon.Connect(config.Server)
if err != nil {
log.Fatal(err)
}
}
func onWelcome(e *irc.Event) {
for _, channel := range config.Channels {
irccon.Join(channel)
}
}
func onEndOfNames(e *irc.Event) {
log.Printf("onEndOfNames: %v", e.Arguments)
}
func configureEvents() {
irccon.AddCallback("001", onWelcome)
irccon.AddCallback("366", onEndOfNames)
irccon.AddCallback("PRIVMSG", onPRIVMSG)
}
// Run reads the Config, connect to the specified IRC server and starts the bot.
// The bot will automatically join all the channels specified in the configuration
func Run(c *Config) {
config = c
connect()
configureEvents()
irccon.Loop()
}
func init() {
rand.Seed(time.Now().UnixNano())
}