Files
botik/irc_bot.go
2022-09-22 20:44:04 +02:00

102 lines
2.1 KiB
Go

package main
import (
"bufio"
"crypto/tls"
"flag"
"fmt"
"io"
"os"
"os/exec"
"strings"
"github.com/icelain/jokeapi"
)
const (
host string = "h21.fun:6697"
help string = `
botík obecný
https://gitlab.com/prokop_paruzek/botik
Je v kanálu #test i v DM
Zdraví nově příchozí.
Příkazy:
!help - Zobraz nápovědu
!pozdrav - pozdraví
!fortune - řekne moudrost
!ftip - poví vtip
`
)
func sendMsg(conn io.Writer, msg string, receiver string) {
fmt.Fprintln(conn, "PRIVMSG "+receiver+" :"+msg)
}
func sendMultiline(conn io.Writer, msg string, receiver string) {
for _, l := range strings.Split(strings.Trim(msg, "\n"), "\n") {
sendMsg(conn, l, receiver)
}
}
func main() {
// flags parse
var debug bool
flag.BoolVar(&debug, "D", false, "Print debug messages.")
flag.Parse()
// IRC init
conn, err := tls.Dial("tcp", host, &tls.Config{RootCAs: nil})
if err != nil {
panic("Failed to connect")
}
defer conn.Close()
reader := bufio.NewReader(conn)
fmt.Fprintln(conn, "PASS horal")
fmt.Fprintln(conn, "USER bot rpi3 rpi3 :botik obecny")
fmt.Fprintln(conn, "NICK botik")
fmt.Fprintln(conn, "JOIN #test")
// joke init
api := jokeapi.New()
api.SetLang("en")
// IRC
for {
in, _ := reader.ReadString('\n')
words := strings.Fields(in)
if debug {
fmt.Fprintln(os.Stderr, words)
}
who := strings.Split(words[0], "!")[0][1:]
if who == "botik" {
continue
}
switch words[1] {
case "JOIN":
sendMsg(conn, "Vítej "+who, words[2])
case "PRIVMSG":
var receiver string
if []rune(words[2])[0] == '#' {
receiver = words[2]
} else {
receiver = who
}
switch words[3][1:] {
case "!help":
sendMultiline(conn, help, receiver)
case "!pozdrav":
sendMsg(conn, "Ahoj "+who, receiver)
case "!fortune":
msg, _ := exec.Command("fortune").Output()
fmt.Println(string(msg))
sendMultiline(conn, string(msg), receiver)
case "!ftip":
ftip, _ := api.Fetch()
for _, l := range ftip.Joke {
sendMultiline(conn, l, receiver)
}
}
}
if words[0] == "PING" {
fmt.Fprintln(conn, "PONG "+words[1])
}
}
}