/
main.go
122 lines (96 loc) · 2.63 KB
/
main.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
// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.
package main
import (
"flag"
"fmt"
"github.com/chimeracoder/gopherbot/cmd"
"github.com/chimeracoder/gopherbot/net"
"github.com/chimeracoder/gopherbot/plugin"
"github.com/chimeracoder/gopherbot/proto"
"log"
"os"
"path/filepath"
_ "github.com/ChimeraCoder/gopherbot/plugins/reputation"
_ "github.com/ChimeraCoder/gopherbot/plugins/url"
_ "github.com/ChimeraCoder/gopherbot/plugins/whois"
_ "github.com/chimeracoder/gopherbot/plugins/admin"
_ "github.com/chimeracoder/gopherbot/plugins/dict"
)
func main() {
conn, client := setup()
defer shutdown(conn, client)
// Perform handshake.
log.Printf("Performing handshake...")
client.User(config.Nickname)
client.Nick(config.Nickname, config.NickservPassword)
// Main data loop.
log.Printf("Entering data loop...")
for {
line, err := conn.ReadLine()
if err != nil {
break
}
client.Read(string(line))
}
}
// setup initializes the application.
func setup() (*net.Conn, *proto.Client) {
// parse commandline arguments and create configuration.
config = parseArgs()
log.Printf("Connecting to %s...", config.Address)
// Open connection to server.
conn, err := net.Dial(config.Address, config.SSLCert, config.SSLKey)
if err != nil {
fmt.Fprintf(os.Stderr, "Dial: %v\n", err)
os.Exit(1)
}
log.Println("Connection established.")
// Create client protocol.
client := proto.NewClient(func(p []byte) error {
_, err := conn.Write(p)
return err
})
// Initialize plugins.
err = plugin.Load(config.Profile, client)
if err != nil {
log.Fatal(err)
}
// Inform command package of our user whitelist.
cmd.SetWhitelist(config.Whitelist)
// Bind protocol handlers and commands.
bind(client)
return conn, client
}
// shutdown cleans up our mess.
func shutdown(conn *net.Conn, client *proto.Client) {
plugin.Unload(client)
log.Printf("Shutting down.")
client.Quit(config.QuitMessage)
client.Close()
conn.Close()
}
// parseArgs reads and verfies commandline arguments.
// It loads and returns a configuration object.
func parseArgs() *Config {
profile := flag.String("p", "", "Path to bot profile directory.")
version := flag.Bool("v", false, "Display version information.")
flag.Parse()
if *version {
fmt.Printf("%s\n", Version())
os.Exit(0)
}
if len(*profile) == 0 {
fmt.Fprintf(os.Stderr, "Missing profile directory.\n")
flag.Usage()
os.Exit(1)
}
var c Config
c.Profile = filepath.Clean(*profile)
err := c.Load(filepath.Join(c.Profile, "config.ini"))
if err != nil {
fmt.Fprintf(os.Stderr, "Load config: %v\n", err)
os.Exit(1)
}
return &c
}