Blob


1 package main
3 import (
4 "crypto/tls"
5 "flag"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "log"
10 "net/http"
11 "path/filepath"
12 "regexp"
14 irc "github.com/fluffle/goirc/client"
15 )
17 var (
18 baseurl = flag.String("baseurl", "gemini://m2i.omarpolo.com", "base url")
19 matrixOutDir = flag.String("matrix-out", "", "matrix out directory")
21 matrixRe = regexp.MustCompile(`https://matrix.org/[^\s]+\.txt`)
22 channel = "#gemini-italia"
23 )
25 func matrix2gemini(conn *irc.Conn, line *irc.Line) {
26 matches := matrixRe.FindAllString(line.Text(), -1)
28 // it's not a good idea to defer inside a loop, but we know
29 // len(matches) is small (usually just 1). Morover, I like
30 // living in danger!
32 for _, link := range matches {
33 resp, err := http.Get(link)
34 if err != nil {
35 conn.Privmsg(
36 channel,
37 fmt.Sprintf("failed to download %q: %s", link, err),
38 )
39 continue
40 }
41 defer resp.Body.Close()
43 tmpfile, err := ioutil.TempFile(*matrixOutDir, "message-")
44 if err != nil {
45 conn.Privmsg(channel, fmt.Sprintf("failed to tmpfile: %s", err))
46 return
47 }
48 defer tmpfile.Close()
50 io.Copy(tmpfile, resp.Body)
52 conn.Privmsg(
53 channel,
54 fmt.Sprintf(
55 "better: %s/%s",
56 *baseurl,
57 filepath.Base(tmpfile.Name()),
58 ),
59 )
60 }
61 }
63 func dostuff(conn *irc.Conn, line *irc.Line) {
64 matrix2gemini(conn, line)
65 // ...
66 }
68 func main() {
69 flag.Parse()
71 cfg := irc.NewConfig("gemitbot")
72 cfg.SSL = true
73 cfg.SSLConfig = &tls.Config{ServerName: "irc.freenode.net"}
74 cfg.Server = "irc.freenode.net:7000"
75 cfg.NewNick = func(n string) string { return n + "^" }
77 c := irc.Client(cfg)
79 c.HandleFunc(irc.CONNECTED, func(conn *irc.Conn, line *irc.Line) {
80 log.Println("connected, joining", channel)
81 conn.Join(channel)
82 })
84 c.HandleFunc(irc.PRIVMSG, dostuff)
85 c.HandleFunc(irc.ACTION, dostuff)
87 quit := make(chan bool)
89 c.HandleFunc(irc.DISCONNECTED, func(conn *irc.Conn, line *irc.Line) {
90 quit <- true
91 })
93 if err := c.Connect(); err != nil {
94 log.Fatalln("connection error:", err)
95 }
97 <-quit
98 }