all repos — paprika @ 5e7478268e4bce3b6747afe20282d3bd2fe0a7a5

go rewrite of taigabot

main.go (view raw)

  1package main
  2
  3import (
  4	"crypto/tls"
  5	"errors"
  6	"log"
  7	"net"
  8	"strings"
  9
 10	"git.icyphox.sh/paprika/config"
 11	"git.icyphox.sh/paprika/database"
 12	"git.icyphox.sh/paprika/plugins"
 13	"gopkg.in/irc.v3"
 14)
 15
 16func handleChatMessage(c *irc.Client, m *irc.Message, response string, err error) {
 17	if errors.Is(err, plugins.NoReply) {
 18		return
 19	}
 20
 21	cmd := "PRIVMSG"
 22	if errors.Is(err, plugins.IsNotice) {
 23		err = nil
 24		cmd = "NOTICE"
 25	}
 26
 27	target := m.Params[0]
 28	if serr, ok := err.(*plugins.IsPrivateNotice); ok {
 29		target = serr.To
 30		cmd = "NOTICE"
 31		err = nil
 32	}
 33
 34	msg := irc.Message{Command: cmd}
 35	split := strings.Split(response, "\n")
 36
 37	if errors.Is(err, plugins.IsRaw) {
 38		for _, line := range split {
 39			c.Write(line)
 40		}
 41	} else if err != nil {
 42		msg.Params = []string{target, response}
 43		c.WriteMessage(&msg)
 44		log.Printf("error: %v", err)
 45	} else {
 46		for _, line := range split {
 47			msg.Params = []string{target, line}
 48			c.WriteMessage(&msg)
 49		}
 50		return
 51	}
 52}
 53
 54func ircHandler(c *irc.Client, m *irc.Message) {
 55	switch m.Command {
 56	case "001":
 57		c.Write(config.SplitChannelList(config.C.Channels))
 58	case "JOIN":
 59		response, err := plugins.GetIntro(m)
 60		handleChatMessage(c, m, response, err)
 61	case "PRIVMSG":
 62		// Trim leading and trailing spaces to not trip up our
 63		// plugins.
 64		m.Params[1] = strings.TrimSpace(m.Params[1])
 65		response, err := plugins.ProcessTrigger(m)
 66		handleChatMessage(c, m, response, err)
 67	}
 68}
 69
 70func main() {
 71	ircConfig := irc.ClientConfig{
 72		Nick:    config.C.Nick,
 73		Pass:    config.C.Pass,
 74		User:    "paprikabot",
 75		Name:    config.C.Nick,
 76		Handler: irc.HandlerFunc(ircHandler),
 77	}
 78
 79	var err error
 80	database.DB.DB, err = database.Open()
 81	if err != nil {
 82		log.Fatal(err)
 83	}
 84	defer database.DB.Close()
 85
 86	var client *irc.Client
 87	if !config.C.Tls {
 88		conn, err := net.Dial("tcp", config.C.Host)
 89		if err != nil {
 90			log.Fatal(err)
 91		}
 92		defer conn.Close()
 93		client = irc.NewClient(conn, ircConfig)
 94	} else {
 95		conn, err := tls.Dial("tcp", config.C.Host, nil)
 96		if err != nil {
 97			log.Fatal(err)
 98		}
 99		defer conn.Close()
100		client = irc.NewClient(conn, ircConfig)
101	}
102	err = client.Run()
103	if err != nil {
104		log.Fatal(err)
105	}
106}