16 "github.com/andybalholm/cascadia"
17 irc "github.com/fluffle/goirc/client"
18 "golang.org/x/net/html"
22 baseurl = flag.String("baseurl", "gemini://m2i.omarpolo.com", "base url")
23 matrixOutDir = flag.String("matrix-out", "", "matrix out directory")
25 msgRe = regexp.MustCompile(`https://.*/[^\s]+\.(txt|png|jpg|jpeg|gif)`)
26 channel = "#gemini-it"
28 tooLongRe = regexp.MustCompile(`full message at (https://libera.ems.host/.*)[)]`)
30 httplink = regexp.MustCompile(`https?://[^\s)]+`)
33 func matrix2gemini(conn *irc.Conn, line *irc.Line) {
34 matches := msgRe.FindAllString(line.Text(), -1)
36 // it's not a good idea to defer inside a loop, but we know
37 // len(matches) is small (usually just 1). Morover, I like
40 for _, link := range matches {
41 resp, err := http.Get(link)
45 fmt.Sprintf("failed to download %q: %s", link, err),
49 defer resp.Body.Close()
52 tmpfile, err := ioutil.TempFile(*matrixOutDir, "message-*"+ext)
54 conn.Privmsg(channel, fmt.Sprintf("failed to tmpfile: %s", err))
59 io.Copy(tmpfile, resp.Body)
66 filepath.Base(tmpfile.Name()),
72 func messageTooLong(conn *irc.Conn, line *irc.Line) {
73 matches := tooLongRe.FindStringSubmatch(line.Text())
74 if len(matches) != 2 {
80 resp, err := http.Get(url)
84 fmt.Sprintf("failed to download %q: %s", url, err),
88 defer resp.Body.Close()
90 sb := &strings.Builder{}
91 if _, err := io.Copy(sb, resp.Body); err != nil {
94 fmt.Sprintf("failed to read body of %q: %s", url, err),
99 conn.Privmsg(channel, fmt.Sprintf("%s ha detto:", line.Nick))
100 for _, line := range strings.Split(sb.String(), "\n") {
108 func stringifyNode(node *html.Node) string {
111 if node.Type == html.TextNode {
115 for child := node.FirstChild; child != nil; child = child.NextSibling {
116 s += stringifyNode(child)
122 func pagetitle(conn *irc.Conn, line *irc.Line) {
123 log.Println("text is", line.Text())
124 matches := httplink.FindAllString(line.Text(), -1)
126 for _, link := range matches {
127 log.Println("fetching", link, "...")
129 resp, err := http.Get(link)
133 defer resp.Body.Close()
135 doc, err := html.Parse(resp.Body)
140 sel := cascadia.MustCompile("head > title")
141 n := cascadia.Query(doc, sel)
147 title := stringifyNode(n)
151 conn.Privmsg(channel, stringifyNode(n))
155 func dostuff(conn *irc.Conn, line *irc.Line) {
156 matrix2gemini(conn, line)
157 messageTooLong(conn, line)
158 pagetitle(conn, line)
165 cfg := irc.NewConfig("gemitbot")
167 cfg.SSLConfig = &tls.Config{ServerName: "irc.libera.chat"}
168 cfg.Server = "irc.libera.chat:7000"
169 cfg.NewNick = func(n string) string { return n + "^" }
173 c.HandleFunc(irc.CONNECTED, func(conn *irc.Conn, line *irc.Line) {
174 log.Println("connected, joining", channel)
178 c.HandleFunc(irc.PRIVMSG, dostuff)
179 c.HandleFunc(irc.ACTION, dostuff)
181 quit := make(chan bool)
183 c.HandleFunc(irc.DISCONNECTED, func(conn *irc.Conn, line *irc.Line) {
187 if err := c.Connect(); err != nil {
188 log.Fatalln("connection error:", err)