<commit_before>/*
*  Copyright (c) 2012 by <NAME> <<EMAIL>>
*                        <NAME> <<EMAIL>>
*  All rights reserved. Distributed under the Simplified BSD License.
 */

package main

import (
	"flag"
	"fmt"
	irc "github.com/fluffle/goirc/client"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"
)

var (
	timezone          = time.UTC
	wolframURL        = "http://www.wolframalpha.com/input/?i=%s"
	mathbinPreviewURL = "http://mathbin.net/preview.cgi?body=%s"
	mathbinURL        = "http://mathbin.net/%s"
	reMathbin         = regexp.MustCompile(`equation_previews/[\d_]+\.png`)
)

func init() {
	tz, err := time.LoadLocation("Europe/Vienna")
	if err != nil {
		log.Fatal(err)
	}
	timezone = tz
}

var tmpl = template.Must(template.New("weierbot").Parse(`<!doctype html>
<html>
<head>
<title>{{.Title}} - Weierbot</title>
<style>a { color: #111; }</style>
</head>
<body>
<div style="float:right;">
{{if .Prev}}<a style="color:#FF1A00;" href="/{{.Prev}}">Previous</a>{{end}}
{{if .Next}}<a style="color:#FF1A00;" href="/{{.Next}}">Next</a>{{end}}
</div>
<h1 style="color:#111; font-size: 1.2em; margin:0;">Weierbot</h1>
<h2 style="margin: .1em 0 .5em; font-size: 1.8em;">
<a style="color:#FF1A00; text-decoration: none;" href="/{{.Title}}">{{.Title}}</a>
</h2>
<pre style="white-space:pre-wrap;">{{.Chatlog}}</pre>
<p class="margin-top: 1em; color:#888;">Proudly powered by
<a href="https://github.com/nomatter01/weierbot">weierbot</a></p>
</body>
</html>`))

var reURL = regexp.MustCompile(`https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]`)
var reTime = regexp.MustCompile(`(?m)^\[\S+\]`)

type WeierBot struct {
	server     string
	client     *irc.Conn
	log        chan Message
	disconnect chan bool
}

func NewWeierBot(server, nick, password string, channels []string) *WeierBot {
	w := &WeierBot{
		server:     server,
		client:     irc.SimpleClient(nick),
		log:        make(chan Message, 512),
		disconnect: make(chan bool),
	}
	w.client.Me.Name = nick
	w.client.Me.Ident = nick

	w.client.AddHandler("connected", func(conn *irc.Conn, line *irc.Line) {
		if password != "" {
			conn.Privmsg("NickServ", "identify "+password)
		}
		for _, ch := range channels {
			log.Printf("Joining %s\n", ch)
			conn.Join(ch)
		}
	})
	w.client.AddHandler("disconnected", func(conn *irc.Conn, line *irc.Line) {
		w.disconnect <- true
	})
	w.client.AddHandler("join", func(conn *irc.Conn, line *irc.Line) {
		if len(line.Args) >= 1 && strings.HasPrefix(line.Args[0], "#") {
			conn.Privmsg(line.Nick, fmt.Sprintf("Hallo %s, willkommen auf %s. "+
				"Dieser Channel wird unter http://weierbot.tux21b.org/ mitgespeichert.",
				line.Nick, line.Args[0]))
		}
	})
	w.client.AddHandler("privmsg", func(conn *irc.Conn, line *irc.Line) {
		if len(line.Args) < 2 {
			return
		}
		w.handleMessage(line.Args[0], Message{
			Nick:    line.Nick,
			Time:    line.Time,
			Message: line.Args[1],
		})
	})

	go w.writeLog()

	return w
}

func createMathbinImage(latexcode string) string {
	resp, err := http.Get(fmt.Sprintf(mathbinPreviewURL, url.QueryEscape("[EQ]"+latexcode+"[/EQ]")))
	if err != nil {
		return err.Error()
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	result := reMathbin.FindString(string(body))

	return fmt.Sprintf(mathbinURL, result)
}

func (bot *WeierBot) handleMessage(target string, msg Message) {
	if strings.HasPrefix(target, "#") {
		bot.log <- msg
	} else {
		target = msg.Nick
	}

	switch {
	case strings.HasPrefix(msg.Message, "!wolfram "):
		bot.send(target, fmt.Sprintf(wolframURL, url.QueryEscape(msg.Message[9:])))
	case msg.Message == "!log":
		bot.send(target, "http://weierbot.tux21b.org/")
	case strings.HasPrefix(msg.Message, "!mathbin "):
		imgurl := createMathbinImage(msg.Message[9:])
		bot.send(target, fmt.Sprintf(imgurl))
	}
}

func (bot *WeierBot) send(target, message string) {
	bot.client.Privmsg(target, message)
	if strings.HasPrefix(target, "#") {
		bot.log <- Message{Nick: bot.client.Me.Nick, Time: time.Now(),
			Message: message}
	}
}

func (bot *WeierBot) writeLog() {
	var (
		file     *os.File
		format   = "2006-01-02.log"
		filename string
	)
	defer func() {
		if file != nil {<commit_msg>private !log message, added !coin<commit_after>/*
*  Copyright (c) 2012 by <NAME> <<EMAIL>>
*                        <NAME> <<EMAIL>>
*  All rights reserved. Distributed under the Simplified BSD License.
 */

package main

import (
	"flag"
	"fmt"
	irc "github.com/fluffle/goirc/client"
	"html/template"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"
)

var (
	timezone          = time.UTC
	wolframURL        = "http://www.wolframalpha.com/input/?i=%s"
	mathbinPreviewURL = "http://mathbin.net/preview.cgi?body=%s"
	mathbinURL        = "http://mathbin.net/%s"
	reMathbin         = regexp.MustCompile(`equation_previews/[\d_]+\.png`)
)

func init() {
	tz, err := time.LoadLocation("Europe/Vienna")
	if err != nil {
		log.Fatal(err)
	}
	timezone = tz
}

var tmpl = template.Must(template.New("weierbot").Parse(`<!doctype html>
<html>
<head>
<title>{{.Title}} - Weierbot</title>
<style>a { color: #111; }</style>
</head>
<body>
<div style="float:right;">
{{if .Prev}}<a style="color:#FF1A00;" href="/{{.Prev}}">Previous</a>{{end}}
{{if .Next}}<a style="color:#FF1A00;" href="/{{.Next}}">Next</a>{{end}}
</div>
<h1 style="color:#111; font-size: 1.2em; margin:0;">Weierbot</h1>
<h2 style="margin: .1em 0 .5em; font-size: 1.8em;">
<a style="color:#FF1A00; text-decoration: none;" href="/{{.Title}}">{{.Title}}</a>
</h2>
<pre style="white-space:pre-wrap;">{{.Chatlog}}</pre>
<p class="margin-top: 1em; color:#888;">Proudly powered by
<a href="https://github.com/nomatter01/weierbot">weierbot</a></p>
</body>
</html>`))

var reURL = regexp.MustCompile(`https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]`)
var reTime = regexp.MustCompile(`(?m)^\[\S+\]`)

type WeierBot struct {
	server     string
	client     *irc.Conn
	log        chan Message
	disconnect chan bool
}

func NewWeierBot(server, nick, password string, channels []string) *WeierBot {
	w := &WeierBot{
		server:     server,
		client:     irc.SimpleClient(nick),
		log:        make(chan Message, 512),
		disconnect: make(chan bool),
	}
	w.client.Me.Name = nick
	w.client.Me.Ident = nick

	w.client.AddHandler("connected", func(conn *irc.Conn, line *irc.Line) {
		if password != "" {
			conn.Privmsg("NickServ", "identify "+password)
		}
		for _, ch := range channels {
			log.Printf("Joining %s\n", ch)
			conn.Join(ch)
		}
	})
	w.client.AddHandler("disconnected", func(conn *irc.Conn, line *irc.Line) {
		w.disconnect <- true
	})
	w.client.AddHandler("join", func(conn *irc.Conn, line *irc.Line) {
		if len(line.Args) >= 1 && strings.HasPrefix(line.Args[0], "#") {
			conn.Privmsg(line.Nick, fmt.Sprintf("Hallo %s, willkommen auf %s. "+
				"Dieser Channel wird unter http://weierbot.tux21b.org/ mitgespeichert.",
				line.Nick, line.Args[0]))
		}
	})
	w.client.AddHandler("privmsg", func(conn *irc.Conn, line *irc.Line) {
		if len(line.Args) < 2 {
			return
		}
		w.handleMessage(line.Args[0], Message{
			Nick:    line.Nick,
			Time:    line.Time,
			Message: line.Args[1],
		})
	})

	go w.writeLog()

	return w
}

func createMathbinImage(latexcode string) string {
	resp, err := http.Get(fmt.Sprintf(mathbinPreviewURL, url.QueryEscape("[EQ]"+latexcode+"[/EQ]")))
	if err != nil {
		return err.Error()
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)

	result := reMathbin.FindString(string(body))

	return fmt.Sprintf(mathbinURL, result)
}

func (bot *WeierBot) handleMessage(target string, msg Message) {
	if strings.HasPrefix(target, "#") {
		bot.log <- msg
	} else {
		target = msg.Nick
	}

	switch {
	case msg.Message == "!coin":
		if rand.Intn(2) == 0 {
			bot.send(target, "head")
		} else {
			bot.send(target, "tail")
		}
	case strings.HasPrefix(msg.Message, "!wolfram "):
		bot.send(target, fmt.Sprintf(wolframURL, url.QueryEscape(msg.Message[9:])))
	case msg.Message == "!log":
		bot.send(msg.Nick, "http://weierbot.tux21b.org/")
	case strings.HasPrefix(msg.Message, "!mathbin "):
		imgurl := createMathbinImage(msg.Message[9:])
		bot.send(target, fmt.Sprintf(imgurl))
	}
}

func (bot *WeierBot) send(target, message string) {
	bot.client.Privmsg(target, message)
	if strings.HasPrefix(target, "#") {
		bot.log <- Message{Nick: bot.client.Me.Nick, Time: time.Now(),
			Message: message}
	}
}

func (bot *WeierBot) writeLog() {
	var (
		file     *os.File
		format   = "2006-01-02.log"
		filename string
	)
	defer func() {
		if file != nil {
{'fraction_non_alphanumeric': 0.20198866921031333, 'fraction_numerical': 0.015030639380275176, 'mean_word_length': 3.80822679266259, 'pattern_counts': {'":': 3, '<': 81, '<?xml version=': 0, '>': 75, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7502977', 'n_tokens_mistral': 3704, 'n_tokens_neox': 3400, 'n_words': 646}