98 lines
2.1 KiB
Go
98 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"bufio"
|
|
"bytes"
|
|
"strings"
|
|
"database/sql"
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
func sendmsg (conn net.Conn, channel string, msg string) {
|
|
mesg := fmt.Sprintf("PRIVMSG %s :%s\r\n", channel, msg)
|
|
fmt.Printf(mesg)
|
|
conn.Write([]byte(mesg))
|
|
}
|
|
|
|
func scanline_privmsg (msg string) irc_msg {
|
|
var irc irc_msg
|
|
|
|
msg = msg[1:]
|
|
t := strings.Split(msg, "!")
|
|
irc.author, irc.channel = t[0], t[1]
|
|
t = strings.Split(irc.channel, "PRIVMSG ")
|
|
irc.channel = t[1]
|
|
t = strings.Split(irc.channel, " :")
|
|
irc.channel, irc.msg = t[0], t[1]
|
|
t = strings.Split(irc.msg, "\r\n")
|
|
irc.msg = strings.TrimSpace(t[0])
|
|
if ! strings.HasPrefix(irc.channel, "#") {
|
|
irc.channel = irc.author
|
|
}
|
|
return irc
|
|
}
|
|
|
|
func listenToIRC (foo bot) <-chan []byte {
|
|
c := make(chan []byte)
|
|
reader := bufio.NewReader(foo.conn)
|
|
db, err = sql.Open("sqlite3", foo.Conf.Database)
|
|
if err != nil {
|
|
LOG_ERR.Printf("opening database failed")
|
|
return nil
|
|
}
|
|
|
|
var line []byte
|
|
var err error
|
|
|
|
go func() {
|
|
for {
|
|
line, err = reader.ReadBytes('\n')
|
|
if err != nil {
|
|
LOG_ERR.Printf("Error while reading bytes from connection.\n")
|
|
dead = true
|
|
c <- []byte("killed it")
|
|
return
|
|
}
|
|
|
|
c <- line
|
|
|
|
if bytes.Contains([]byte(line), []byte("PING :")) {
|
|
v := []byte(bytes.Replace([]byte(line), []byte("PING"), []byte("PONG"), 1))
|
|
fmt.Printf(string(v[:]))
|
|
foo.conn.Write(v)
|
|
continue
|
|
}
|
|
|
|
if !bytes.Contains([]byte(line), []byte("PRIVMSG")) {
|
|
continue
|
|
}
|
|
|
|
parsemsg(scanline_privmsg(string(line)), foo)
|
|
}
|
|
} ()
|
|
return c
|
|
}
|
|
|
|
func connect(boddle bot) <-chan []byte {
|
|
conn, err := net.Dial("tcp", boddle.Conf.Server)
|
|
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "Error while dialing server.")
|
|
LOG_ERR.Printf("Error while connecting to server.")
|
|
return nil
|
|
}
|
|
|
|
boddle.conn = conn
|
|
|
|
/* connect to irc */
|
|
fmt.Fprintf(boddle.conn, "NICK %s\r\n", boddle.Conf.Name)
|
|
fmt.Fprintf(boddle.conn, "USER %s 1 1 1:%s\r\n", boddle.Conf.Name, boddle.Conf.Name)
|
|
for _, channel := range(boddle.Conf.Channels) {
|
|
fmt.Fprintf(boddle.conn, "JOIN %s\r\n", channel)
|
|
}
|
|
|
|
return listenToIRC(boddle)
|
|
}
|