Files
botik/irc_bot.go
2025-03-19 23:32:09 +01:00

132 lines
2.8 KiB
Go

package main
import (
"bufio"
"crypto/tls"
"encoding/json"
"flag"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"os/exec"
"strings"
"github.com/icelain/jokeapi"
)
const (
host string = "irc.eu.libera.chat:6697"
help string = `
botík obecný
https://git.h21.fun/h21/botik.git
Je v kanálu #h21 i v DM
Zdraví nově příchozí.
Příkazy:
!help - Zobraz nápovědu
!pozdrav - pozdraví
!fortune - řekne moudrost
!ftip - poví vtip
`
)
type ChuckJoke struct {
Categories []interface{} `json:"categories"`
Created_at string `json:"created_at"`
Icon_url string `json:"icon_url"`
Id string `json:"id"`
Update_at string `json:"update_at"`
Url string `json:"url"`
Value string `json:"value"`
}
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, "USER h21-botik botik h21 :botik obecny")
fmt.Fprintln(conn, "NICK h21-botik")
fmt.Fprintln(conn, "JOIN #h21")
// 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", "cs").Output()
fmt.Println(string(msg))
sendMultiline(conn, string(msg), receiver)
case "!ftip":
if rand.Intn(2) == 0 {
res, err := http.Get("https://api.chucknorris.io/jokes/random")
if err != nil {
fmt.Println(err)
}
var parse ChuckJoke
bodyStr, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println(err)
}
err = json.Unmarshal(bodyStr, &parse)
if err != nil {
fmt.Println(err)
}
sendMultiline(conn, parse.Value, receiver)
} else {
ftip, _ := api.Fetch()
for _, l := range ftip.Joke {
sendMultiline(conn, l, receiver)
}
}
}
}
if words[0] == "PING" {
fmt.Fprintln(conn, "PONG "+words[1])
}
}
}