Merge pull request #158 from velour/logging

Logging
This commit is contained in:
Chris Sexton 2019-03-07 11:51:41 -05:00 committed by GitHub
commit 701143dac5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 526 additions and 359 deletions

View File

@ -4,12 +4,12 @@ package bot
import ( import (
"html/template" "html/template"
"log"
"net/http" "net/http"
"reflect" "reflect"
"strings" "strings"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/bot/msglog" "github.com/velour/catbase/bot/msglog"
"github.com/velour/catbase/bot/user" "github.com/velour/catbase/bot/user"
@ -105,7 +105,7 @@ func (b *bot) migrateDB() {
name string, name string,
value string value string
);`); err != nil { );`); err != nil {
log.Fatal("Initial DB migration create variables table: ", err) log.Fatal().Err(err).Msgf("Initial DB migration create variables table")
} }
} }
@ -160,7 +160,7 @@ func (b *bot) serveRoot(w http.ResponseWriter, r *http.Request) {
context["EndPoints"] = b.httpEndPoints context["EndPoints"] = b.httpEndPoints
t, err := template.New("rootIndex").Parse(rootIndex) t, err := template.New("rootIndex").Parse(rootIndex)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
} }
t.Execute(w, context) t.Execute(w, context)
} }
@ -170,7 +170,8 @@ func IsCmd(c *config.Config, message string) (bool, string) {
cmdcs := c.GetArray("CommandChar", []string{"!"}) cmdcs := c.GetArray("CommandChar", []string{"!"})
botnick := strings.ToLower(c.Get("Nick", "bot")) botnick := strings.ToLower(c.Get("Nick", "bot"))
if botnick == "" { if botnick == "" {
log.Fatalf(`You must run catbase -set nick -val <your bot nick>`) log.Fatal().
Msgf(`You must run catbase -set nick -val <your bot nick>`)
} }
iscmd := false iscmd := false
lowerMessage := strings.ToLower(message) lowerMessage := strings.ToLower(message)

View File

@ -6,7 +6,6 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"log"
"math/rand" "math/rand"
"reflect" "reflect"
"regexp" "regexp"
@ -14,18 +13,21 @@ import (
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
) )
func (b *bot) Receive(kind Kind, msg msg.Message, args ...interface{}) bool { func (b *bot) Receive(kind Kind, msg msg.Message, args ...interface{}) bool {
log.Println("Received event: ", msg) log.Debug().
Interface("msg", msg).
Msg("Received event")
// msg := b.buildMessage(client, inMsg) // msg := b.buildMessage(client, inMsg)
// do need to look up user and fix it // do need to look up user and fix it
if kind == Message && strings.HasPrefix(msg.Body, "help") && msg.Command { if kind == Message && strings.HasPrefix(msg.Body, "help") && msg.Command {
parts := strings.Fields(strings.ToLower(msg.Body)) parts := strings.Fields(strings.ToLower(msg.Body))
b.checkHelp(msg.Channel, parts) b.checkHelp(msg.Channel, parts)
log.Println("Handled a help, returning") log.Debug().Msg("Handled a help, returning")
goto RET goto RET
} }
@ -171,7 +173,7 @@ func (b *bot) getVar(varName string) (string, error) {
case err == sql.ErrNoRows: case err == sql.ErrNoRows:
return "", fmt.Errorf("No factoid found") return "", fmt.Errorf("No factoid found")
case err != nil: case err != nil:
log.Fatal("getVar error: ", err) log.Fatal().Err(err).Msg("getVar error")
} }
return text, nil return text, nil
} }
@ -180,7 +182,7 @@ func (b *bot) listVars(channel string, parts []string) {
var variables []string var variables []string
err := b.DB().Select(&variables, `select name from variables group by name`) err := b.DB().Select(&variables, `select name from variables group by name`)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
msg := "I know: $who, $someone, $digit, $nonzero" msg := "I know: $who, $someone, $digit, $nonzero"
if len(variables) > 0 { if len(variables) > 0 {

View File

@ -4,12 +4,12 @@ package bot
import ( import (
"fmt" "fmt"
"log"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
"github.com/stretchr/testify/mock" "github.com/stretchr/testify/mock"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/bot/user" "github.com/velour/catbase/bot/user"
@ -64,14 +64,14 @@ func (mb *MockBot) edit(channel, newMessage, identifier string) (string, error)
isMessage := identifier[0] == 'm' isMessage := identifier[0] == 'm'
if !isMessage && identifier[0] != 'a' { if !isMessage && identifier[0] != 'a' {
err := fmt.Errorf("failed to parse identifier: %s", identifier) err := fmt.Errorf("failed to parse identifier: %s", identifier)
log.Println(err) log.Error().Err(err)
return "", err return "", err
} }
index, err := strconv.Atoi(strings.Split(identifier, "-")[1]) index, err := strconv.Atoi(strings.Split(identifier, "-")[1])
if err != nil { if err != nil {
err := fmt.Errorf("failed to parse identifier: %s", identifier) err := fmt.Errorf("failed to parse identifier: %s", identifier)
log.Println(err) log.Error().Err(err)
return "", err return "", err
} }

View File

@ -5,7 +5,6 @@ package config
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"log"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
@ -13,6 +12,7 @@ import (
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
sqlite3 "github.com/mattn/go-sqlite3" sqlite3 "github.com/mattn/go-sqlite3"
"github.com/rs/zerolog/log"
) )
// Config stores any system-wide startup information that cannot be easily configured via // Config stores any system-wide startup information that cannot be easily configured via
@ -74,7 +74,7 @@ func (c *Config) GetString(key, fallback string) string {
q := `select value from config where key=?` q := `select value from config where key=?`
err := c.DB.Get(&configValue, q, key) err := c.DB.Get(&configValue, q, key)
if err != nil { if err != nil {
log.Printf("WARN: Key %s is empty", key) log.Debug().Msgf("WARN: Key %s is empty", key)
return fallback return fallback
} }
return configValue return configValue
@ -137,11 +137,11 @@ func ReadConfig(dbpath string) *Config {
if dbpath == "" { if dbpath == "" {
dbpath = "catbase.db" dbpath = "catbase.db"
} }
fmt.Printf("Using %s as database file.\n", dbpath) log.Info().Msgf("Using %s as database file.\n", dbpath)
sqlDB, err := sqlx.Open("sqlite3_custom", dbpath) sqlDB, err := sqlx.Open("sqlite3_custom", dbpath)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
c := Config{ c := Config{
DBFile: dbpath, DBFile: dbpath,
@ -156,7 +156,7 @@ func ReadConfig(dbpath string) *Config {
panic(err) panic(err)
} }
fmt.Printf("catbase is running.\n") log.Info().Msgf("catbase is running.")
return &c return &c
} }

View File

@ -2,9 +2,10 @@ package config
import ( import (
"bytes" "bytes"
"log"
"strings" "strings"
"text/template" "text/template"
"github.com/rs/zerolog/log"
) )
var q = ` var q = `
@ -17,7 +18,7 @@ INSERT INTO config VALUES('init',1);
func (c *Config) SetDefaults(mainChannel, nick string) { func (c *Config) SetDefaults(mainChannel, nick string) {
if nick == mainChannel && nick == "" { if nick == mainChannel && nick == "" {
log.Fatalf("You must provide a nick and a mainChannel") log.Fatal().Msgf("You must provide a nick and a mainChannel")
} }
t := template.Must(template.New("query").Parse(q)) t := template.Must(template.New("query").Parse(q))
vals := struct { vals := struct {
@ -33,5 +34,5 @@ func (c *Config) SetDefaults(mainChannel, nick string) {
t.Execute(&buf, vals) t.Execute(&buf, vals)
c.MustExec(`delete from config;`) c.MustExec(`delete from config;`)
c.MustExec(buf.String()) c.MustExec(buf.String())
log.Println("Configuration initialized.") log.Info().Msgf("Configuration initialized.")
} }

View File

@ -5,11 +5,11 @@ package irc
import ( import (
"fmt" "fmt"
"io" "io"
"log"
"os" "os"
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/bot/user" "github.com/velour/catbase/bot/user"
@ -69,7 +69,7 @@ func (i *Irc) Send(kind bot.Kind, args ...interface{}) (string, error) {
} }
func (i *Irc) JoinChannel(channel string) { func (i *Irc) JoinChannel(channel string) {
log.Printf("Joining channel: %s", channel) log.Info().Msgf("Joining channel: %s", channel)
i.Client.Out <- irc.Msg{Cmd: irc.JOIN, Args: []string{channel}} i.Client.Out <- irc.Msg{Cmd: irc.JOIN, Args: []string{channel}}
} }
@ -147,7 +147,7 @@ func (i *Irc) handleConnection() {
close(i.Client.Out) close(i.Client.Out)
for err := range i.Client.Errors { for err := range i.Client.Errors {
if err != io.EOF { if err != io.EOF {
log.Println(err) log.Error().Err(err)
} }
} }
}() }()
@ -169,7 +169,7 @@ func (i *Irc) handleConnection() {
case err, ok := <-i.Client.Errors: case err, ok := <-i.Client.Errors:
if ok && err != io.EOF { if ok && err != io.EOF {
log.Println(err) log.Error().Err(err)
i.quit <- true i.quit <- true
return return
} }
@ -183,7 +183,7 @@ func (i *Irc) handleMsg(msg irc.Msg) {
switch msg.Cmd { switch msg.Cmd {
case irc.ERROR: case irc.ERROR:
log.Println(1, "Received error: "+msg.Raw) log.Info().Msgf("Received error: " + msg.Raw)
case irc.PING: case irc.PING:
i.Client.Out <- irc.Msg{Cmd: irc.PONG} i.Client.Out <- irc.Msg{Cmd: irc.PONG}
@ -241,7 +241,7 @@ func (i *Irc) handleMsg(msg irc.Msg) {
default: default:
cmd := irc.CmdNames[msg.Cmd] cmd := irc.CmdNames[msg.Cmd]
log.Println("(" + cmd + ") " + msg.Raw) log.Debug().Msgf("(%s) %s", cmd, msg.Raw)
} }
} }

View File

@ -10,7 +10,6 @@ import (
"html" "html"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
@ -21,6 +20,7 @@ import (
"context" "context"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/bot/user" "github.com/velour/catbase/bot/user"
@ -164,7 +164,7 @@ type rtmStart struct {
func New(c *config.Config) *Slack { func New(c *config.Config) *Slack {
token := c.Get("slack.token", "NONE") token := c.Get("slack.token", "NONE")
if token == "NONE" { if token == "NONE" {
log.Fatalf("No slack token found. Set SLACKTOKEN env.") log.Fatal().Msgf("No slack token found. Set SLACKTOKEN env.")
} }
return &Slack{ return &Slack{
config: c, config: c,
@ -242,16 +242,16 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string
}) })
if err != nil { if err != nil {
log.Printf("Error sending Slack message: %s", err) log.Error().Err(err).Msgf("Error sending Slack message")
} }
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if err != nil { if err != nil {
log.Fatalf("Error reading Slack API body: %s", err) log.Fatal().Err(err).Msgf("Error reading Slack API body")
} }
log.Println(string(body)) log.Debug().Msgf("%+v", body)
type MessageResponse struct { type MessageResponse struct {
OK bool `json:"ok"` OK bool `json:"ok"`
@ -264,7 +264,7 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string
var mr MessageResponse var mr MessageResponse
err = json.Unmarshal(body, &mr) err = json.Unmarshal(body, &mr)
if err != nil { if err != nil {
log.Fatalf("Error parsing message response: %s", err) log.Fatal().Err(err).Msgf("Error parsing message response")
} }
if !mr.OK { if !mr.OK {
@ -277,13 +277,13 @@ func (s *Slack) sendMessageType(channel, message string, meMessage bool) (string
} }
func (s *Slack) sendMessage(channel, message string) (string, error) { func (s *Slack) sendMessage(channel, message string) (string, error) {
log.Printf("Sending message to %s: %s", channel, message) log.Debug().Msgf("Sending message to %s: %s", channel, message)
identifier, err := s.sendMessageType(channel, message, false) identifier, err := s.sendMessageType(channel, message, false)
return identifier, err return identifier, err
} }
func (s *Slack) sendAction(channel, message string) (string, error) { func (s *Slack) sendAction(channel, message string) (string, error) {
log.Printf("Sending action to %s: %s", channel, message) log.Debug().Msgf("Sending action to %s: %s", channel, message)
identifier, err := s.sendMessageType(channel, "_"+message+"_", true) identifier, err := s.sendMessageType(channel, "_"+message+"_", true)
return identifier, err return identifier, err
} }
@ -313,7 +313,7 @@ func (s *Slack) replyToMessageIdentifier(channel, message, identifier string) (s
return "", err return "", err
} }
log.Println(string(body)) log.Debug().Msgf("%s", body)
type MessageResponse struct { type MessageResponse struct {
OK bool `json:"ok"` OK bool `json:"ok"`
@ -339,7 +339,7 @@ func (s *Slack) replyToMessage(channel, message string, replyTo msg.Message) (st
} }
func (s *Slack) react(channel, reaction string, message msg.Message) (string, error) { func (s *Slack) react(channel, reaction string, message msg.Message) (string, error) {
log.Printf("Reacting in %s: %s", channel, reaction) log.Debug().Msgf("Reacting in %s: %s", channel, reaction)
resp, err := http.PostForm("https://slack.com/api/reactions.add", resp, err := http.PostForm("https://slack.com/api/reactions.add",
url.Values{"token": {s.token}, url.Values{"token": {s.token},
"name": {reaction}, "name": {reaction},
@ -353,7 +353,7 @@ func (s *Slack) react(channel, reaction string, message msg.Message) (string, er
} }
func (s *Slack) edit(channel, newMessage, identifier string) (string, error) { func (s *Slack) edit(channel, newMessage, identifier string) (string, error) {
log.Printf("Editing in (%s) %s: %s", identifier, channel, newMessage) log.Debug().Msgf("Editing in (%s) %s: %s", identifier, channel, newMessage)
resp, err := http.PostForm("https://slack.com/api/chat.update", resp, err := http.PostForm("https://slack.com/api/chat.update",
url.Values{"token": {s.token}, url.Values{"token": {s.token},
"channel": {channel}, "channel": {channel},
@ -374,14 +374,14 @@ func (s *Slack) populateEmojiList() {
resp, err := http.PostForm("https://slack.com/api/emoji.list", resp, err := http.PostForm("https://slack.com/api/emoji.list",
url.Values{"token": {s.token}}) url.Values{"token": {s.token}})
if err != nil { if err != nil {
log.Printf("Error retrieving emoji list from Slack: %s", err) log.Debug().Msgf("Error retrieving emoji list from Slack: %s", err)
return return
} }
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if err != nil { if err != nil {
log.Fatalf("Error reading Slack API body: %s", err) log.Fatal().Err(err).Msgf("Error reading Slack API body")
} }
type EmojiListResponse struct { type EmojiListResponse struct {
@ -392,7 +392,7 @@ func (s *Slack) populateEmojiList() {
var list EmojiListResponse var list EmojiListResponse
err = json.Unmarshal(body, &list) err = json.Unmarshal(body, &list)
if err != nil { if err != nil {
log.Fatalf("Error parsing emoji list: %s", err) log.Fatal().Err(err).Msgf("Error parsing emoji list")
} }
s.emoji = list.Emoji s.emoji = list.Emoji
} }
@ -417,7 +417,7 @@ func (s *Slack) receiveMessage() (slackMessage, error) {
m := slackMessage{} m := slackMessage{}
err := s.ws.Recv(context.TODO(), &m) err := s.ws.Recv(context.TODO(), &m)
if err != nil { if err != nil {
log.Println("Error decoding WS message") log.Error().Msgf("Error decoding WS message")
panic(fmt.Errorf("%v\n%v", m, err)) panic(fmt.Errorf("%v\n%v", m, err))
} }
return m, nil return m, nil
@ -442,7 +442,7 @@ func (s *Slack) Serve() error {
for { for {
msg, err := s.receiveMessage() msg, err := s.receiveMessage()
if err != nil && err == io.EOF { if err != nil && err == io.EOF {
log.Fatalf("Slack API EOF") log.Fatal().Msg("Slack API EOF")
} else if err != nil { } else if err != nil {
return fmt.Errorf("Slack API error: %s", err) return fmt.Errorf("Slack API error: %s", err)
} }
@ -452,7 +452,7 @@ func (s *Slack) Serve() error {
if !isItMe && !msg.Hidden && msg.ThreadTs == "" { if !isItMe && !msg.Hidden && msg.ThreadTs == "" {
m := s.buildMessage(msg) m := s.buildMessage(msg)
if m.Time.Before(s.lastRecieved) { if m.Time.Before(s.lastRecieved) {
log.Printf("Ignoring message: %+v\nlastRecieved: %v msg: %v", msg.ID, s.lastRecieved, m.Time) log.Debug().Msgf("Ignoring message: %+v\nlastRecieved: %v msg: %v", msg.ID, s.lastRecieved, m.Time)
} else { } else {
s.lastRecieved = m.Time s.lastRecieved = m.Time
s.event(bot.Message, m) s.event(bot.Message, m)
@ -461,10 +461,10 @@ func (s *Slack) Serve() error {
//we're throwing away some information here by not parsing the correct reply object type, but that's okay //we're throwing away some information here by not parsing the correct reply object type, but that's okay
s.event(bot.Reply, s.buildLightReplyMessage(msg), msg.ThreadTs) s.event(bot.Reply, s.buildLightReplyMessage(msg), msg.ThreadTs)
} else { } else {
log.Printf("THAT MESSAGE WAS HIDDEN: %+v", msg.ID) log.Debug().Msgf("THAT MESSAGE WAS HIDDEN: %+v", msg.ID)
} }
case "error": case "error":
log.Printf("Slack error, code: %d, message: %s", msg.Error.Code, msg.Error.Msg) log.Error().Msgf("Slack error, code: %d, message: %s", msg.Error.Code, msg.Error.Msg)
case "": // what even is this? case "": // what even is this?
case "hello": case "hello":
case "presence_change": case "presence_change":
@ -475,7 +475,7 @@ func (s *Slack) Serve() error {
// squeltch this stuff // squeltch this stuff
continue continue
default: default:
log.Printf("Unhandled Slack message type: '%s'", msg.Type) log.Debug().Msgf("Unhandled Slack message type: '%s'", msg.Type)
} }
} }
} }
@ -554,11 +554,11 @@ func (s *Slack) buildLightReplyMessage(m slackMessage) msg.Message {
// markAllChannelsRead gets a list of all channels and marks each as read // markAllChannelsRead gets a list of all channels and marks each as read
func (s *Slack) markAllChannelsRead() { func (s *Slack) markAllChannelsRead() {
chs := s.getAllChannels() chs := s.getAllChannels()
log.Printf("Got list of channels to mark read: %+v", chs) log.Debug().Msgf("Got list of channels to mark read: %+v", chs)
for _, ch := range chs { for _, ch := range chs {
s.markChannelAsRead(ch.ID) s.markChannelAsRead(ch.ID)
} }
log.Printf("Finished marking channels read") log.Debug().Msgf("Finished marking channels read")
} }
// getAllChannels returns info for all channels joined // getAllChannels returns info for all channels joined
@ -567,12 +567,11 @@ func (s *Slack) getAllChannels() []slackChannelListItem {
resp, err := http.PostForm(u, resp, err := http.PostForm(u,
url.Values{"token": {s.token}}) url.Values{"token": {s.token}})
if err != nil { if err != nil {
log.Printf("Error posting user info request: %s", log.Error().Err(err).Msgf("Error posting user info request")
err)
return nil return nil
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Printf("Error posting user info request: %d", log.Error().Msgf("Error posting user info request: %d",
resp.StatusCode) resp.StatusCode)
return nil return nil
} }
@ -580,7 +579,7 @@ func (s *Slack) getAllChannels() []slackChannelListItem {
var chanInfo slackChannelListResp var chanInfo slackChannelListResp
err = json.NewDecoder(resp.Body).Decode(&chanInfo) err = json.NewDecoder(resp.Body).Decode(&chanInfo)
if err != nil || !chanInfo.Ok { if err != nil || !chanInfo.Ok {
log.Println("Error decoding response: ", err) log.Error().Err(err).Msgf("Error decoding response")
return nil return nil
} }
return chanInfo.Channels return chanInfo.Channels
@ -592,21 +591,19 @@ func (s *Slack) markChannelAsRead(slackChanId string) error {
resp, err := http.PostForm(u, resp, err := http.PostForm(u,
url.Values{"token": {s.token}, "channel": {slackChanId}}) url.Values{"token": {s.token}, "channel": {slackChanId}})
if err != nil { if err != nil {
log.Printf("Error posting user info request: %s", log.Error().Err(err).Msgf("Error posting user info request")
err)
return err return err
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Printf("Error posting user info request: %d", log.Error().Msgf("Error posting user info request: %d",
resp.StatusCode) resp.StatusCode)
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
var chanInfo slackChannelInfoResp var chanInfo slackChannelInfoResp
err = json.NewDecoder(resp.Body).Decode(&chanInfo) err = json.NewDecoder(resp.Body).Decode(&chanInfo)
log.Printf("%+v, %+v", err, chanInfo)
if err != nil || !chanInfo.Ok { if err != nil || !chanInfo.Ok {
log.Println("Error decoding response: ", err) log.Error().Err(err).Msgf("Error decoding response")
return err return err
} }
@ -614,25 +611,23 @@ func (s *Slack) markChannelAsRead(slackChanId string) error {
resp, err = http.PostForm(u, resp, err = http.PostForm(u,
url.Values{"token": {s.token}, "channel": {slackChanId}, "ts": {chanInfo.Channel.Latest.Ts}}) url.Values{"token": {s.token}, "channel": {slackChanId}, "ts": {chanInfo.Channel.Latest.Ts}})
if err != nil { if err != nil {
log.Printf("Error posting user info request: %s", log.Error().Err(err).Msgf("Error posting user info request")
err)
return err return err
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Printf("Error posting user info request: %d", log.Error().Msgf("Error posting user info request: %d",
resp.StatusCode) resp.StatusCode)
return err return err
} }
defer resp.Body.Close() defer resp.Body.Close()
var markInfo map[string]interface{} var markInfo map[string]interface{}
err = json.NewDecoder(resp.Body).Decode(&markInfo) err = json.NewDecoder(resp.Body).Decode(&markInfo)
log.Printf("%+v, %+v", err, markInfo)
if err != nil { if err != nil {
log.Println("Error decoding response: ", err) log.Error().Err(err).Msgf("Error decoding response")
return err return err
} }
log.Printf("Marked %s as read", slackChanId) log.Info().Msgf("Marked %s as read", slackChanId)
return nil return nil
} }
@ -644,12 +639,12 @@ func (s *Slack) connect() {
return return
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Fatalf("Slack API failed. Code: %d", resp.StatusCode) log.Fatal().Msgf("Slack API failed. Code: %d", resp.StatusCode)
} }
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if err != nil { if err != nil {
log.Fatalf("Error reading Slack API body: %s", err) log.Fatal().Err(err).Msg("Error reading Slack API body")
} }
var rtm rtmStart var rtm rtmStart
err = json.Unmarshal(body, &rtm) err = json.Unmarshal(body, &rtm)
@ -658,7 +653,7 @@ func (s *Slack) connect() {
} }
if !rtm.Ok { if !rtm.Ok {
log.Fatalf("Slack error: %s", rtm.Error) log.Fatal().Msgf("Slack error: %s", rtm.Error)
} }
s.url = "https://slack.com/api/" s.url = "https://slack.com/api/"
@ -670,7 +665,7 @@ func (s *Slack) connect() {
rtmURL, _ := url.Parse(rtm.URL) rtmURL, _ := url.Parse(rtm.URL)
s.ws, err = websocket.Dial(context.TODO(), rtmURL) s.ws, err = websocket.Dial(context.TODO(), rtmURL)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
} }
@ -680,20 +675,20 @@ func (s *Slack) getUser(id string) (string, bool) {
return name, true return name, true
} }
log.Printf("User %s not already found, requesting info", id) log.Debug().Msgf("User %s not already found, requesting info", id)
u := s.url + "users.info" u := s.url + "users.info"
resp, err := http.PostForm(u, resp, err := http.PostForm(u,
url.Values{"token": {s.token}, "user": {id}}) url.Values{"token": {s.token}, "user": {id}})
if err != nil || resp.StatusCode != 200 { if err != nil || resp.StatusCode != 200 {
log.Printf("Error posting user info request: %d %s", log.Error().Err(err).Msgf("Error posting user info request: %d",
resp.StatusCode, err) resp.StatusCode)
return "UNKNOWN", false return "UNKNOWN", false
} }
defer resp.Body.Close() defer resp.Body.Close()
var userInfo slackUserInfoResp var userInfo slackUserInfoResp
err = json.NewDecoder(resp.Body).Decode(&userInfo) err = json.NewDecoder(resp.Body).Decode(&userInfo)
if err != nil { if err != nil {
log.Println("Error decoding response: ", err) log.Error().Err(err).Msgf("Error decoding response")
return "UNKNOWN", false return "UNKNOWN", false
} }
s.users[id] = userInfo.User.Name s.users[id] = userInfo.User.Name
@ -702,17 +697,18 @@ func (s *Slack) getUser(id string) (string, bool) {
// Who gets usernames out of a channel // Who gets usernames out of a channel
func (s *Slack) Who(id string) []string { func (s *Slack) Who(id string) []string {
log.Println("Who is queried for ", id) log.Debug().
Str("id", id).
Msg("Who is queried for ")
u := s.url + "channels.info" u := s.url + "channels.info"
resp, err := http.PostForm(u, resp, err := http.PostForm(u,
url.Values{"token": {s.token}, "channel": {id}}) url.Values{"token": {s.token}, "channel": {id}})
if err != nil { if err != nil {
log.Printf("Error posting user info request: %s", log.Error().Err(err).Msgf("Error posting user info request")
err)
return []string{} return []string{}
} }
if resp.StatusCode != 200 { if resp.StatusCode != 200 {
log.Printf("Error posting user info request: %d", log.Error().Msgf("Error posting user info request: %d",
resp.StatusCode) resp.StatusCode)
return []string{} return []string{}
} }
@ -720,17 +716,17 @@ func (s *Slack) Who(id string) []string {
var chanInfo slackChannelInfoResp var chanInfo slackChannelInfoResp
err = json.NewDecoder(resp.Body).Decode(&chanInfo) err = json.NewDecoder(resp.Body).Decode(&chanInfo)
if err != nil || !chanInfo.Ok { if err != nil || !chanInfo.Ok {
log.Println("Error decoding response: ", err) log.Error().Err(err).Msgf("Error decoding response")
return []string{} return []string{}
} }
log.Printf("%#v", chanInfo.Channel) log.Debug().Msgf("%#v", chanInfo.Channel)
handles := []string{} handles := []string{}
for _, member := range chanInfo.Channel.Members { for _, member := range chanInfo.Channel.Members {
u, _ := s.getUser(member) u, _ := s.getUser(member)
handles = append(handles, u) handles = append(handles, u)
} }
log.Printf("Returning %d handles", len(handles)) log.Debug().Msgf("Returning %d handles", len(handles))
return handles return handles
} }

View File

@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"html" "html"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
@ -15,6 +14,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/nlopes/slack" "github.com/nlopes/slack"
"github.com/nlopes/slack/slackevents" "github.com/nlopes/slack/slackevents"
@ -50,7 +51,7 @@ type SlackApp struct {
func New(c *config.Config) *SlackApp { func New(c *config.Config) *SlackApp {
token := c.Get("slack.token", "NONE") token := c.Get("slack.token", "NONE")
if token == "NONE" { if token == "NONE" {
log.Fatalf("No slack token found. Set SLACKTOKEN env.") log.Fatal().Msg("No slack token found. Set SLACKTOKEN env.")
} }
api := slack.New(token, slack.OptionDebug(false)) api := slack.New(token, slack.OptionDebug(false))
@ -88,7 +89,7 @@ func (s *SlackApp) Serve() error {
body := buf.String() body := buf.String()
eventsAPIEvent, e := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionVerifyToken(&slackevents.TokenComparator{VerificationToken: s.verification})) eventsAPIEvent, e := slackevents.ParseEvent(json.RawMessage(body), slackevents.OptionVerifyToken(&slackevents.TokenComparator{VerificationToken: s.verification}))
if e != nil { if e != nil {
log.Println(e) log.Error().Err(e)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
} }
@ -96,7 +97,7 @@ func (s *SlackApp) Serve() error {
var r *slackevents.ChallengeResponse var r *slackevents.ChallengeResponse
err := json.Unmarshal([]byte(body), &r) err := json.Unmarshal([]byte(body), &r)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
} }
w.Header().Set("Content-Type", "text") w.Header().Set("Content-Type", "text")
@ -112,7 +113,10 @@ func (s *SlackApp) Serve() error {
s.msgReceivd(ev) s.msgReceivd(ev)
} }
} else { } else {
log.Printf("Event: (%v): %+v", eventsAPIEvent.Type, eventsAPIEvent) log.Debug().
Str("type", eventsAPIEvent.Type).
Interface("event", eventsAPIEvent).
Msg("event")
} }
}) })
return nil return nil
@ -137,14 +141,19 @@ func (s *SlackApp) checkRingOrAdd(ts string) bool {
func (s *SlackApp) msgReceivd(msg *slackevents.MessageEvent) { func (s *SlackApp) msgReceivd(msg *slackevents.MessageEvent) {
if s.checkRingOrAdd(msg.TimeStamp) { if s.checkRingOrAdd(msg.TimeStamp) {
log.Printf("Got a duplicate message from server: %s", msg.TimeStamp) log.Debug().
Str("ts", msg.TimeStamp).
Msg("Got a duplicate message from server")
return return
} }
isItMe := msg.BotID != "" && msg.BotID == s.myBotID isItMe := msg.BotID != "" && msg.BotID == s.myBotID
if !isItMe && msg.ThreadTimeStamp == "" { if !isItMe && msg.ThreadTimeStamp == "" {
m := s.buildMessage(msg) m := s.buildMessage(msg)
if m.Time.Before(s.lastRecieved) { if m.Time.Before(s.lastRecieved) {
log.Printf("Ignoring message: lastRecieved: %v msg: %v", s.lastRecieved, m.Time) log.Debug().
Time("ts", m.Time).
Interface("lastRecv", s.lastRecieved).
Msg("Ignoring message")
} else { } else {
s.lastRecieved = m.Time s.lastRecieved = m.Time
s.event(bot.Message, m) s.event(bot.Message, m)
@ -153,7 +162,9 @@ func (s *SlackApp) msgReceivd(msg *slackevents.MessageEvent) {
//we're throwing away some information here by not parsing the correct reply object type, but that's okay //we're throwing away some information here by not parsing the correct reply object type, but that's okay
s.event(bot.Reply, s.buildMessage(msg), msg.ThreadTimeStamp) s.event(bot.Reply, s.buildMessage(msg), msg.ThreadTimeStamp)
} else { } else {
log.Printf("THAT MESSAGE WAS HIDDEN: %+v", msg.Text) log.Debug().
Str("text", msg.Text).
Msg("THAT MESSAGE WAS HIDDEN")
} }
} }
@ -197,7 +208,7 @@ func (s *SlackApp) sendMessageType(channel, message string, meMessage bool) (str
} }
if err != nil { if err != nil {
log.Printf("Error sending message: %+v", err) log.Error().Err(err).Msg("Error sending message")
return "", err return "", err
} }
@ -205,13 +216,19 @@ func (s *SlackApp) sendMessageType(channel, message string, meMessage bool) (str
} }
func (s *SlackApp) sendMessage(channel, message string) (string, error) { func (s *SlackApp) sendMessage(channel, message string) (string, error) {
log.Printf("Sending message to %s: %s", channel, message) log.Debug().
Str("channel", channel).
Str("message", message).
Msg("Sending message")
identifier, err := s.sendMessageType(channel, message, false) identifier, err := s.sendMessageType(channel, message, false)
return identifier, err return identifier, err
} }
func (s *SlackApp) sendAction(channel, message string) (string, error) { func (s *SlackApp) sendAction(channel, message string) (string, error) {
log.Printf("Sending action to %s: %s", channel, message) log.Debug().
Str("channel", channel).
Str("message", message).
Msg("Sending action")
identifier, err := s.sendMessageType(channel, "_"+message+"_", true) identifier, err := s.sendMessageType(channel, "_"+message+"_", true)
return identifier, err return identifier, err
} }
@ -241,7 +258,7 @@ func (s *SlackApp) replyToMessageIdentifier(channel, message, identifier string)
return "", err return "", err
} }
log.Println(string(body)) log.Debug().Bytes("body", body)
type MessageResponse struct { type MessageResponse struct {
OK bool `json:"ok"` OK bool `json:"ok"`
@ -267,7 +284,10 @@ func (s *SlackApp) replyToMessage(channel, message string, replyTo msg.Message)
} }
func (s *SlackApp) react(channel, reaction string, message msg.Message) (string, error) { func (s *SlackApp) react(channel, reaction string, message msg.Message) (string, error) {
log.Printf("Reacting in %s: %s", channel, reaction) log.Debug().
Str("channel", channel).
Str("reaction", reaction).
Msg("reacting")
ref := slack.ItemRef{ ref := slack.ItemRef{
Channel: channel, Channel: channel,
Timestamp: message.AdditionalData["RAW_SLACK_TIMESTAMP"], Timestamp: message.AdditionalData["RAW_SLACK_TIMESTAMP"],
@ -277,7 +297,11 @@ func (s *SlackApp) react(channel, reaction string, message msg.Message) (string,
} }
func (s *SlackApp) edit(channel, newMessage, identifier string) (string, error) { func (s *SlackApp) edit(channel, newMessage, identifier string) (string, error) {
log.Printf("Editing in (%s) %s: %s", identifier, channel, newMessage) log.Debug().
Str("channel", channel).
Str("identifier", identifier).
Str("newMessage", newMessage).
Msg("editing")
nick := s.config.Get("Nick", "bot") nick := s.config.Get("Nick", "bot")
_, ts, err := s.api.PostMessage(channel, _, ts, err := s.api.PostMessage(channel,
slack.MsgOptionUsername(nick), slack.MsgOptionUsername(nick),
@ -293,14 +317,14 @@ func (s *SlackApp) GetEmojiList() map[string]string {
func (s *SlackApp) populateEmojiList() { func (s *SlackApp) populateEmojiList() {
if s.userToken == "NONE" { if s.userToken == "NONE" {
log.Println("Cannot get emoji list without slack.usertoken") log.Error().Msg("Cannot get emoji list without slack.usertoken")
return return
} }
api := slack.New(s.userToken, slack.OptionDebug(false)) api := slack.New(s.userToken, slack.OptionDebug(false))
em, err := api.GetEmoji() em, err := api.GetEmoji()
if err != nil { if err != nil {
log.Printf("Error retrieving emoji list from Slack: %s", err) log.Error().Err(err).Msg("Error retrieving emoji list from Slack")
return return
} }
@ -357,7 +381,9 @@ func (s *SlackApp) getUser(id string) (string, error) {
return name, nil return name, nil
} }
log.Printf("User %s not already found, requesting info", id) log.Debug().
Str("id", id).
Msg("User not already found, requesting info")
u, err := s.api.GetUserInfo(id) u, err := s.api.GetUserInfo(id)
if err != nil { if err != nil {
return "UNKNOWN", err return "UNKNOWN", err
@ -369,12 +395,14 @@ func (s *SlackApp) getUser(id string) (string, error) {
// Who gets usernames out of a channel // Who gets usernames out of a channel
func (s *SlackApp) Who(id string) []string { func (s *SlackApp) Who(id string) []string {
if s.userToken == "NONE" { if s.userToken == "NONE" {
log.Println("Cannot get emoji list without slack.usertoken") log.Error().Msg("Cannot get emoji list without slack.usertoken")
return []string{s.config.Get("nick", "bot")} return []string{s.config.Get("nick", "bot")}
} }
api := slack.New(s.userToken, slack.OptionDebug(false)) api := slack.New(s.userToken, slack.OptionDebug(false))
log.Println("Who is queried for ", id) log.Debug().
Str("id", id).
Msg("Who is queried")
// Not super sure this is the correct call // Not super sure this is the correct call
params := &slack.GetUsersInConversationParameters{ params := &slack.GetUsersInConversationParameters{
ChannelID: id, ChannelID: id,
@ -382,7 +410,7 @@ func (s *SlackApp) Who(id string) []string {
} }
members, _, err := api.GetUsersInConversation(params) members, _, err := api.GetUsersInConversation(params)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
return []string{s.config.Get("nick", "bot")} return []string{s.config.Get("nick", "bot")}
} }
@ -390,7 +418,10 @@ func (s *SlackApp) Who(id string) []string {
for _, m := range members { for _, m := range members {
u, err := s.getUser(m) u, err := s.getUser(m)
if err != nil { if err != nil {
log.Printf("Couldn't get user %s: %s", m, err) log.Error().
Err(err).
Str("user", m).
Msg("Couldn't get user")
continue continue
} }
ret = append(ret, u) ret = append(ret, u)

1
go.mod
View File

@ -15,6 +15,7 @@ require (
github.com/nlopes/slack v0.5.0 github.com/nlopes/slack v0.5.0
github.com/pkg/errors v0.8.1 // indirect github.com/pkg/errors v0.8.1 // indirect
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d // indirect github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d // indirect
github.com/rs/zerolog v1.12.0
github.com/stretchr/objx v0.1.1 // indirect github.com/stretchr/objx v0.1.1 // indirect
github.com/stretchr/testify v1.3.0 github.com/stretchr/testify v1.3.0
github.com/velour/chat v0.0.0-20180713122344-fd1d1606cb89 github.com/velour/chat v0.0.0-20180713122344-fd1d1606cb89

2
go.sum
View File

@ -32,6 +32,8 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d h1:1VUlQbCfkoSGv7qP7Y+ro3ap1P1pPZxgdGVqiTVy5C4= github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d h1:1VUlQbCfkoSGv7qP7Y+ro3ap1P1pPZxgdGVqiTVy5C4=
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY= github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY=
github.com/rs/zerolog v1.12.0 h1:aqZ1XRadoS8IBknR5IDFvGzbHly1X9ApIqOroooQF/c=
github.com/rs/zerolog v1.12.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=

27
main.go
View File

@ -4,11 +4,14 @@ package main
import ( import (
"flag" "flag"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"os"
"time" "time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/config" "github.com/velour/catbase/config"
"github.com/velour/catbase/connectors/irc" "github.com/velour/catbase/connectors/irc"
@ -19,7 +22,6 @@ import (
"github.com/velour/catbase/plugins/beers" "github.com/velour/catbase/plugins/beers"
"github.com/velour/catbase/plugins/couldashouldawoulda" "github.com/velour/catbase/plugins/couldashouldawoulda"
"github.com/velour/catbase/plugins/counter" "github.com/velour/catbase/plugins/counter"
"github.com/velour/catbase/plugins/db"
"github.com/velour/catbase/plugins/dice" "github.com/velour/catbase/plugins/dice"
"github.com/velour/catbase/plugins/emojifyme" "github.com/velour/catbase/plugins/emojifyme"
"github.com/velour/catbase/plugins/fact" "github.com/velour/catbase/plugins/fact"
@ -45,6 +47,8 @@ var (
key = flag.String("set", "", "Configuration key to set") key = flag.String("set", "", "Configuration key to set")
val = flag.String("val", "", "Configuration value to set") val = flag.String("val", "", "Configuration value to set")
initDB = flag.Bool("init", false, "Initialize the configuration DB") initDB = flag.Bool("init", false, "Initialize the configuration DB")
prettyLog = flag.Bool("pretty", false, "Use pretty console logger")
debug = flag.Bool("debug", false, "Turn on debug logging")
) )
func main() { func main() {
@ -54,15 +58,23 @@ func main() {
"Database file to load. (Defaults to catbase.db)") "Database file to load. (Defaults to catbase.db)")
flag.Parse() // parses the logging flags. flag.Parse() // parses the logging flags.
if *prettyLog {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
}
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if *debug {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}
c := config.ReadConfig(*dbpath) c := config.ReadConfig(*dbpath)
if *key != "" && *val != "" { if *key != "" && *val != "" {
c.Set(*key, *val) c.Set(*key, *val)
log.Printf("Set config %s: %s", *key, *val) log.Info().Msgf("Set config %s: %s", *key, *val)
return return
} }
if (*initDB && len(flag.Args()) != 2) || (!*initDB && c.GetInt("init", 0) != 1) { if (*initDB && len(flag.Args()) != 2) || (!*initDB && c.GetInt("init", 0) != 1) {
log.Fatal(`You must run "catbase -init <channel> <nick>"`) log.Fatal().Msgf(`You must run "catbase -init <channel> <nick>"`)
} else if *initDB { } else if *initDB {
c.SetDefaults(flag.Arg(0), flag.Arg(1)) c.SetDefaults(flag.Arg(0), flag.Arg(1))
return return
@ -78,7 +90,7 @@ func main() {
case "slackapp": case "slackapp":
client = slackapp.New(c) client = slackapp.New(c)
default: default:
log.Fatalf("Unknown connection type: %s", c.Get("type", "UNSET")) log.Fatal().Msgf("Unknown connection type: %s", c.Get("type", "UNSET"))
} }
b := bot.New(c, client) b := bot.New(c, client)
@ -108,12 +120,11 @@ func main() {
b.AddPlugin(nerdepedia.New(b)) b.AddPlugin(nerdepedia.New(b))
// catches anything left, will always return true // catches anything left, will always return true
b.AddPlugin(fact.New(b)) b.AddPlugin(fact.New(b))
b.AddPlugin(db.New(b))
if err := client.Serve(); err != nil { if err := client.Serve(); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
addr := c.Get("HttpAddr", "127.0.0.1:1337") addr := c.Get("HttpAddr", "127.0.0.1:1337")
log.Fatal(http.ListenAndServe(addr, nil)) log.Fatal().Err(http.ListenAndServe(addr, nil))
} }

View File

@ -4,10 +4,11 @@ package admin
import ( import (
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -63,14 +64,14 @@ func (p *AdminPlugin) message(k bot.Kind, message msg.Message, args ...interface
if strings.ToLower(body) == "shut up" { if strings.ToLower(body) == "shut up" {
dur := time.Duration(p.cfg.GetInt("quietDuration", 5)) * time.Minute dur := time.Duration(p.cfg.GetInt("quietDuration", 5)) * time.Minute
log.Printf("Going to sleep for %v, %v", dur, time.Now().Add(dur)) log.Info().Msgf("Going to sleep for %v, %v", dur, time.Now().Add(dur))
p.Bot.Send(bot.Message, message.Channel, "Okay. I'll be back later.") p.Bot.Send(bot.Message, message.Channel, "Okay. I'll be back later.")
p.quiet = true p.quiet = true
go func() { go func() {
select { select {
case <-time.After(dur): case <-time.After(dur):
p.quiet = false p.quiet = false
log.Println("Waking up from nap.") log.Info().Msg("Waking up from nap.")
} }
}() }()
return true return true
@ -105,7 +106,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool {
_, err := p.db.Exec(`delete from variables where name=? and value=?`, variable, value) _, err := p.db.Exec(`delete from variables where name=? and value=?`, variable, value)
if err != nil { if err != nil {
p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.")
log.Println("[admin]: ", err) log.Error().Err(err)
} else { } else {
p.Bot.Send(bot.Message, message.Channel, "Removed.") p.Bot.Send(bot.Message, message.Channel, "Removed.")
} }
@ -126,7 +127,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool {
err := row.Scan(&count) err := row.Scan(&count)
if err != nil { if err != nil {
p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.")
log.Println("[admin]: ", err) log.Error().Err(err)
return true return true
} }
@ -136,7 +137,7 @@ func (p *AdminPlugin) handleVariables(message msg.Message) bool {
_, err := p.db.Exec(`INSERT INTO variables (name, value) VALUES (?, ?)`, variable, value) _, err := p.db.Exec(`INSERT INTO variables (name, value) VALUES (?, ?)`, variable, value)
if err != nil { if err != nil {
p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.") p.Bot.Send(bot.Message, message.Channel, "I'm broke and need attention in my variable creation code.")
log.Println("[admin]: ", err) log.Error().Err(err)
return true return true
} }
p.Bot.Send(bot.Message, message.Channel, "Added.") p.Bot.Send(bot.Message, message.Channel, "Added.")

View File

@ -6,10 +6,11 @@ import (
"database/sql" "database/sql"
"errors" "errors"
"fmt" "fmt"
"log"
"math/rand" "math/rand"
"strings" "strings"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -53,20 +54,18 @@ type BabblerArc struct {
} }
func New(b bot.Bot) *BabblerPlugin { func New(b bot.Bot) *BabblerPlugin {
log.SetFlags(log.LstdFlags | log.Lshortfile)
if _, err := b.DB().Exec(`create table if not exists babblers ( if _, err := b.DB().Exec(`create table if not exists babblers (
id integer primary key, id integer primary key,
babbler string babbler string
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
if _, err := b.DB().Exec(`create table if not exists babblerWords ( if _, err := b.DB().Exec(`create table if not exists babblerWords (
id integer primary key, id integer primary key,
word string word string
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
if _, err := b.DB().Exec(`create table if not exists babblerNodes ( if _, err := b.DB().Exec(`create table if not exists babblerNodes (
@ -76,7 +75,7 @@ func New(b bot.Bot) *BabblerPlugin {
root integer, root integer,
rootFrequency integer rootFrequency integer
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
if _, err := b.DB().Exec(`create table if not exists babblerArcs ( if _, err := b.DB().Exec(`create table if not exists babblerArcs (
@ -85,7 +84,7 @@ func New(b bot.Bot) *BabblerPlugin {
toNodeId interger, toNodeId interger,
frequency integer frequency integer
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
plugin := &BabblerPlugin{ plugin := &BabblerPlugin{
@ -167,7 +166,7 @@ func (p *BabblerPlugin) makeBabbler(name string) (*Babbler, error) {
if err == nil { if err == nil {
id, err := res.LastInsertId() id, err := res.LastInsertId()
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
return &Babbler{ return &Babbler{
@ -183,11 +182,10 @@ func (p *BabblerPlugin) getBabbler(name string) (*Babbler, error) {
err := p.db.QueryRowx(`select * from babblers where babbler = ? LIMIT 1;`, name).StructScan(&bblr) err := p.db.QueryRowx(`select * from babblers where babbler = ? LIMIT 1;`, name).StructScan(&bblr)
if err != nil { if err != nil {
if err == sql.ErrNoRows { if err == sql.ErrNoRows {
log.Printf("failed to find babbler") log.Error().Msg("failed to find babbler")
return nil, NO_BABBLER return nil, NO_BABBLER
} }
log.Printf("encountered problem in babbler lookup") log.Error().Err(err).Msg("encountered problem in babbler lookup")
log.Print(err)
return nil, err return nil, err
} }
return &bblr, nil return &bblr, nil
@ -198,13 +196,13 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) {
if err == NO_BABBLER { if err == NO_BABBLER {
babbler, err = p.makeBabbler(name) babbler, err = p.makeBabbler(name)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
rows, err := p.db.Queryx(fmt.Sprintf("select tidbit from factoid where fact like '%s quotes';", babbler.Name)) rows, err := p.db.Queryx(fmt.Sprintf("select tidbit from factoid where fact like '%s quotes';", babbler.Name))
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return babbler, nil return babbler, nil
} }
defer rows.Close() defer rows.Close()
@ -214,10 +212,10 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) {
var tidbit string var tidbit string
err := rows.Scan(&tidbit) err := rows.Scan(&tidbit)
log.Print(tidbit) log.Debug().Str("tidbit", tidbit)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return babbler, err return babbler, err
} }
tidbits = append(tidbits, tidbit) tidbits = append(tidbits, tidbit)
@ -225,7 +223,7 @@ func (p *BabblerPlugin) getOrCreateBabbler(name string) (*Babbler, error) {
for _, tidbit := range tidbits { for _, tidbit := range tidbits {
if err = p.addToMarkovChain(babbler, tidbit); err != nil { if err = p.addToMarkovChain(babbler, tidbit); err != nil {
log.Print(err) log.Error().Err(err)
} }
} }
} }
@ -247,12 +245,12 @@ func (p *BabblerPlugin) getWord(word string) (*BabblerWord, error) {
func (p *BabblerPlugin) createNewWord(word string) (*BabblerWord, error) { func (p *BabblerPlugin) createNewWord(word string) (*BabblerWord, error) {
res, err := p.db.Exec(`insert into babblerWords (word) values (?);`, word) res, err := p.db.Exec(`insert into babblerWords (word) values (?);`, word)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
id, err := res.LastInsertId() id, err := res.LastInsertId()
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
return &BabblerWord{ return &BabblerWord{
@ -266,7 +264,7 @@ func (p *BabblerPlugin) getOrCreateWord(word string) (*BabblerWord, error) {
return p.createNewWord(word) return p.createNewWord(word)
} else { } else {
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
} }
return w, err return w, err
} }
@ -292,19 +290,19 @@ func (p *BabblerPlugin) getBabblerNode(babbler *Babbler, word string) (*BabblerN
func (p *BabblerPlugin) createBabblerNode(babbler *Babbler, word string) (*BabblerNode, error) { func (p *BabblerPlugin) createBabblerNode(babbler *Babbler, word string) (*BabblerNode, error) {
w, err := p.getOrCreateWord(word) w, err := p.getOrCreateWord(word)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
res, err := p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?, ?, 0, 0)`, babbler.BabblerId, w.WordId) res, err := p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?, ?, 0, 0)`, babbler.BabblerId, w.WordId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
id, err := res.LastInsertId() id, err := res.LastInsertId()
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
@ -327,12 +325,12 @@ func (p *BabblerPlugin) getOrCreateBabblerNode(babbler *Babbler, word string) (*
func (p *BabblerPlugin) incrementRootWordFrequency(babbler *Babbler, word string) (*BabblerNode, error) { func (p *BabblerPlugin) incrementRootWordFrequency(babbler *Babbler, word string) (*BabblerNode, error) {
node, err := p.getOrCreateBabblerNode(babbler, word) node, err := p.getOrCreateBabblerNode(babbler, word)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
_, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + 1, root = 1 where id = ?;`, node.NodeId) _, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + 1, root = 1 where id = ?;`, node.NodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
node.RootFrequency += 1 node.RootFrequency += 1
@ -354,7 +352,7 @@ func (p *BabblerPlugin) getBabblerArc(fromNode, toNode *BabblerNode) (*BabblerAr
func (p *BabblerPlugin) incrementWordArc(fromNode, toNode *BabblerNode) (*BabblerArc, error) { func (p *BabblerPlugin) incrementWordArc(fromNode, toNode *BabblerNode) (*BabblerArc, error) {
res, err := p.db.Exec(`update babblerArcs set frequency = frequency + 1 where fromNodeId = ? and toNodeId = ?;`, fromNode.NodeId, toNode.NodeId) res, err := p.db.Exec(`update babblerArcs set frequency = frequency + 1 where fromNodeId = ? and toNodeId = ?;`, fromNode.NodeId, toNode.NodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
@ -366,7 +364,7 @@ func (p *BabblerPlugin) incrementWordArc(fromNode, toNode *BabblerNode) (*Babble
if affectedRows == 0 { if affectedRows == 0 {
res, err = p.db.Exec(`insert into babblerArcs (fromNodeId, toNodeId, frequency) values (?, ?, 1);`, fromNode.NodeId, toNode.NodeId) res, err = p.db.Exec(`insert into babblerArcs (fromNodeId, toNodeId, frequency) values (?, ?, 1);`, fromNode.NodeId, toNode.NodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
} }
@ -390,19 +388,19 @@ func (p *BabblerPlugin) addToMarkovChain(babbler *Babbler, phrase string) error
curNode, err := p.incrementRootWordFrequency(babbler, words[0]) curNode, err := p.incrementRootWordFrequency(babbler, words[0])
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
for i := 1; i < len(words); i++ { for i := 1; i < len(words); i++ {
nextNode, err := p.getOrCreateBabblerNode(babbler, words[i]) nextNode, err := p.getOrCreateBabblerNode(babbler, words[i])
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
_, err = p.incrementWordArc(curNode, nextNode) _, err = p.incrementWordArc(curNode, nextNode)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
curNode = nextNode curNode = nextNode
@ -415,7 +413,7 @@ func (p *BabblerPlugin) addToMarkovChain(babbler *Babbler, phrase string) error
func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *BabblerWord, error) { func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *BabblerWord, error) {
rows, err := p.db.Queryx(`select * from babblerNodes where babblerId = ? and root = 1;`, babbler.BabblerId) rows, err := p.db.Queryx(`select * from babblerNodes where babblerId = ? and root = 1;`, babbler.BabblerId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
defer rows.Close() defer rows.Close()
@ -427,7 +425,7 @@ func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *Ba
var node BabblerNode var node BabblerNode
err = rows.StructScan(&node) err = rows.StructScan(&node)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
rootNodes = append(rootNodes, &node) rootNodes = append(rootNodes, &node)
@ -446,21 +444,21 @@ func (p *BabblerPlugin) getWeightedRootNode(babbler *Babbler) (*BabblerNode, *Ba
var w BabblerWord var w BabblerWord
err := p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) err := p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
return node, &w, nil return node, &w, nil
} }
} }
log.Fatalf("shouldn't happen") log.Fatal().Msg("failed to find weighted root word")
return nil, nil, errors.New("failed to find weighted root word") return nil, nil, nil
} }
func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode, *BabblerWord, error) { func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode, *BabblerWord, error) {
rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, fromNode.NodeId) rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, fromNode.NodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
defer rows.Close() defer rows.Close()
@ -471,7 +469,7 @@ func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode
var arc BabblerArc var arc BabblerArc
err = rows.StructScan(&arc) err = rows.StructScan(&arc)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
arcs = append(arcs, &arc) arcs = append(arcs, &arc)
@ -492,28 +490,28 @@ func (p *BabblerPlugin) getWeightedNextWord(fromNode *BabblerNode) (*BabblerNode
var node BabblerNode var node BabblerNode
err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.ToNodeId).StructScan(&node) err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.ToNodeId).StructScan(&node)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
var w BabblerWord var w BabblerWord
err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
return &node, &w, nil return &node, &w, nil
} }
} }
log.Fatalf("shouldn't happen") log.Fatal().Msg("failed to find weighted next word")
return nil, nil, errors.New("failed to find weighted next word") return nil, nil, nil
} }
func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNode, *BabblerWord, bool, error) { func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNode, *BabblerWord, bool, error) {
rows, err := p.db.Queryx(`select * from babblerArcs where toNodeId = ?;`, toNode.NodeId) rows, err := p.db.Queryx(`select * from babblerArcs where toNodeId = ?;`, toNode.NodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, false, err return nil, nil, false, err
} }
defer rows.Close() defer rows.Close()
@ -524,7 +522,7 @@ func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNo
var arc BabblerArc var arc BabblerArc
err = rows.StructScan(&arc) err = rows.StructScan(&arc)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, false, err return nil, nil, false, err
} }
arcs = append(arcs, &arc) arcs = append(arcs, &arc)
@ -551,39 +549,39 @@ func (p *BabblerPlugin) getWeightedPreviousWord(toNode *BabblerNode) (*BabblerNo
var node BabblerNode var node BabblerNode
err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.FromNodeId).StructScan(&node) err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, arc.FromNodeId).StructScan(&node)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, false, err return nil, nil, false, err
} }
var w BabblerWord var w BabblerWord
err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w) err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, node.WordId).StructScan(&w)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, false, err return nil, nil, false, err
} }
return &node, &w, false, nil return &node, &w, false, nil
} }
} }
log.Fatalf("shouldn't happen") log.Fatal().Msg("failed to find weighted previous word")
return nil, nil, false, errors.New("failed to find weighted previous word") return nil, nil, false, nil
} }
func (p *BabblerPlugin) verifyPhrase(babbler *Babbler, phrase []string) (*BabblerNode, *BabblerNode, error) { func (p *BabblerPlugin) verifyPhrase(babbler *Babbler, phrase []string) (*BabblerNode, *BabblerNode, error) {
curNode, err := p.getBabblerNode(babbler, phrase[0]) curNode, err := p.getBabblerNode(babbler, phrase[0])
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
firstNode := curNode firstNode := curNode
for i := 1; i < len(phrase); i++ { for i := 1; i < len(phrase); i++ {
nextNode, err := p.getBabblerNode(babbler, phrase[i]) nextNode, err := p.getBabblerNode(babbler, phrase[i])
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
_, err = p.getBabblerArc(curNode, nextNode) _, err = p.getBabblerArc(curNode, nextNode)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, nil, err return nil, nil, err
} }
curNode = nextNode curNode = nextNode
@ -599,7 +597,7 @@ func (p *BabblerPlugin) babble(who string) (string, error) {
func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, error) { func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, error) {
babbler, err := p.getBabbler(babblerName) babbler, err := p.getBabbler(babblerName)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", nil return "", nil
} }
@ -610,14 +608,14 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e
if len(seed) == 0 { if len(seed) == 0 {
curNode, curWord, err = p.getWeightedRootNode(babbler) curNode, curWord, err = p.getWeightedRootNode(babbler)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
words = append(words, curWord.Word) words = append(words, curWord.Word)
} else { } else {
_, curNode, err = p.verifyPhrase(babbler, seed) _, curNode, err = p.verifyPhrase(babbler, seed)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
} }
@ -625,7 +623,7 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e
for { for {
curNode, curWord, err = p.getWeightedNextWord(curNode) curNode, curWord, err = p.getWeightedNextWord(curNode)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
if curWord.Word == " " { if curWord.Word == " " {
@ -644,12 +642,12 @@ func (p *BabblerPlugin) babbleSeed(babblerName string, seed []string) (string, e
func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoName, otherName string) error { func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoName, otherName string) error {
intoNode, err := p.getOrCreateBabblerNode(intoBabbler, "<"+intoName+">") intoNode, err := p.getOrCreateBabblerNode(intoBabbler, "<"+intoName+">")
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
otherNode, err := p.getOrCreateBabblerNode(otherBabbler, "<"+otherName+">") otherNode, err := p.getOrCreateBabblerNode(otherBabbler, "<"+otherName+">")
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
@ -657,7 +655,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
rows, err := p.db.Queryx("select * from babblerNodes where babblerId = ?;", otherBabbler.BabblerId) rows, err := p.db.Queryx("select * from babblerNodes where babblerId = ?;", otherBabbler.BabblerId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
defer rows.Close() defer rows.Close()
@ -668,7 +666,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
var node BabblerNode var node BabblerNode
err = rows.StructScan(&node) err = rows.StructScan(&node)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
nodes = append(nodes, &node) nodes = append(nodes, &node)
@ -684,12 +682,12 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
if node.Root > 0 { if node.Root > 0 {
res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ?, root = 1 where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId) res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ?, root = 1 where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
} }
} else { } else {
res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ? where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId) res, err = p.db.Exec(`update babblerNodes set rootFrequency = rootFrequency + ? where babblerId = ? and wordId = ?;`, node.RootFrequency, intoBabbler.BabblerId, node.WordId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
} }
} }
@ -701,7 +699,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
if err != nil || rowsAffected == 0 { if err != nil || rowsAffected == 0 {
res, err = p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?,?,?,?) ;`, intoBabbler.BabblerId, node.WordId, node.Root, node.RootFrequency) res, err = p.db.Exec(`insert into babblerNodes (babblerId, wordId, root, rootFrequency) values (?,?,?,?) ;`, intoBabbler.BabblerId, node.WordId, node.Root, node.RootFrequency)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
} }
@ -709,7 +707,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
var updatedNode BabblerNode var updatedNode BabblerNode
err = p.db.QueryRowx(`select * from babblerNodes where babblerId = ? and wordId = ? LIMIT 1;`, intoBabbler.BabblerId, node.WordId).StructScan(&updatedNode) err = p.db.QueryRowx(`select * from babblerNodes where babblerId = ? and wordId = ? LIMIT 1;`, intoBabbler.BabblerId, node.WordId).StructScan(&updatedNode)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
@ -729,7 +727,7 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
var arc BabblerArc var arc BabblerArc
err = rows.StructScan(&arc) err = rows.StructScan(&arc)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return err return err
} }
arcs = append(arcs, &arc) arcs = append(arcs, &arc)
@ -749,13 +747,13 @@ func (p *BabblerPlugin) mergeBabblers(intoBabbler, otherBabbler *Babbler, intoNa
func (p *BabblerPlugin) babbleSeedSuffix(babblerName string, seed []string) (string, error) { func (p *BabblerPlugin) babbleSeedSuffix(babblerName string, seed []string) (string, error) {
babbler, err := p.getBabbler(babblerName) babbler, err := p.getBabbler(babblerName)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", nil return "", nil
} }
firstNode, curNode, err := p.verifyPhrase(babbler, seed) firstNode, curNode, err := p.verifyPhrase(babbler, seed)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
@ -766,7 +764,7 @@ func (p *BabblerPlugin) babbleSeedSuffix(babblerName string, seed []string) (str
for { for {
curNode, curWord, shouldTerminate, err = p.getWeightedPreviousWord(curNode) curNode, curWord, shouldTerminate, err = p.getWeightedPreviousWord(curNode)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
@ -795,7 +793,7 @@ func (p *BabblerPlugin) getNextArcs(babblerNodeId int64) ([]*BabblerArc, error)
arcs := []*BabblerArc{} arcs := []*BabblerArc{}
rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, babblerNodeId) rows, err := p.db.Queryx(`select * from babblerArcs where fromNodeId = ?;`, babblerNodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return arcs, err return arcs, err
} }
defer rows.Close() defer rows.Close()
@ -804,7 +802,7 @@ func (p *BabblerPlugin) getNextArcs(babblerNodeId int64) ([]*BabblerArc, error)
var arc BabblerArc var arc BabblerArc
err = rows.StructScan(&arc) err = rows.StructScan(&arc)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return []*BabblerArc{}, err return []*BabblerArc{}, err
} }
arcs = append(arcs, &arc) arcs = append(arcs, &arc)
@ -816,7 +814,7 @@ func (p *BabblerPlugin) getBabblerNodeById(nodeId int64) (*BabblerNode, error) {
var node BabblerNode var node BabblerNode
err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, nodeId).StructScan(&node) err := p.db.QueryRowx(`select * from babblerNodes where id = ? LIMIT 1;`, nodeId).StructScan(&node)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil, err return nil, err
} }
return &node, nil return &node, nil
@ -832,19 +830,19 @@ func shuffle(a []*BabblerArc) {
func (p *BabblerPlugin) babbleSeedBookends(babblerName string, start, end []string) (string, error) { func (p *BabblerPlugin) babbleSeedBookends(babblerName string, start, end []string) (string, error) {
babbler, err := p.getBabbler(babblerName) babbler, err := p.getBabbler(babblerName)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", nil return "", nil
} }
_, startWordNode, err := p.verifyPhrase(babbler, start) _, startWordNode, err := p.verifyPhrase(babbler, start)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
endWordNode, _, err := p.verifyPhrase(babbler, end) endWordNode, _, err := p.verifyPhrase(babbler, end)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
@ -898,13 +896,13 @@ func (p *BabblerPlugin) babbleSeedBookends(babblerName string, start, end []stri
for { for {
cur, err := p.getBabblerNodeById(curSearchNode.babblerNodeId) cur, err := p.getBabblerNodeById(curSearchNode.babblerNodeId)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
var w BabblerWord var w BabblerWord
err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, cur.WordId).StructScan(&w) err = p.db.QueryRowx(`select * from babblerWords where id = ? LIMIT 1;`, cur.WordId).StructScan(&w)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", err return "", err
} }
words = append(words, w.Word) words = append(words, w.Word)

View File

@ -7,7 +7,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"strconv" "strconv"
@ -15,6 +14,7 @@ import (
"time" "time"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/plugins/counter" "github.com/velour/catbase/plugins/counter"
@ -46,7 +46,7 @@ func New(b bot.Bot) *BeersPlugin {
lastCheckin integer, lastCheckin integer,
chanNick string chanNick string
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
p := &BeersPlugin{ p := &BeersPlugin{
Bot: b, Bot: b,
@ -147,13 +147,16 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf
channel: channel, channel: channel,
} }
log.Println("Creating Untappd user:", u.untappdUser, "nick:", u.chanNick) log.Info().
Str("untappdUser", u.untappdUser).
Str("nick", u.chanNick).
Msg("Creating Untappd user")
var count int var count int
err := p.db.QueryRow(`select count(*) from untappd err := p.db.QueryRow(`select count(*) from untappd
where untappdUser = ?`, u.untappdUser).Scan(&count) where untappdUser = ?`, u.untappdUser).Scan(&count)
if err != nil { if err != nil {
log.Println("Error registering untappd: ", err) log.Error().Err(err).Msgf("Error registering untappd")
} }
if count > 0 { if count > 0 {
p.Bot.Send(bot.Message, channel, "I'm already watching you.") p.Bot.Send(bot.Message, channel, "I'm already watching you.")
@ -171,7 +174,7 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf
u.chanNick, u.chanNick,
) )
if err != nil { if err != nil {
log.Println("Error registering untappd: ", err) log.Error().Err(err).Msgf("Error registering untappd")
p.Bot.Send(bot.Message, channel, "I can't see.") p.Bot.Send(bot.Message, channel, "I can't see.")
return true return true
} }
@ -184,7 +187,9 @@ func (p *BeersPlugin) message(kind bot.Kind, message msg.Message, args ...interf
} }
if message.Command && parts[0] == "checkuntappd" { if message.Command && parts[0] == "checkuntappd" {
log.Println("Checking untappd at request of user.") log.Info().
Str("user", message.User.Name).
Msgf("Checking untappd at request of user.")
p.checkUntappd(channel) p.checkUntappd(channel)
return true return true
} }
@ -210,7 +215,7 @@ func (p *BeersPlugin) setBeers(user string, amount int) {
ub := getUserBeers(p.db, user) ub := getUserBeers(p.db, user)
err := ub.Update(amount) err := ub.Update(amount)
if err != nil { if err != nil {
log.Println("Error saving beers: ", err) log.Error().Err(err).Msgf("Error saving beers")
} }
} }
@ -218,7 +223,7 @@ func (p *BeersPlugin) addBeers(user string, delta int) {
ub := getUserBeers(p.db, user) ub := getUserBeers(p.db, user)
err := ub.UpdateDelta(delta) err := ub.UpdateDelta(delta)
if err != nil { if err != nil {
log.Println("Error saving beers: ", err) log.Error().Err(err).Msgf("Error saving beers")
} }
} }
@ -325,14 +330,14 @@ func (p *BeersPlugin) pullUntappd() ([]checkin, error) {
} }
if resp.StatusCode == 500 { if resp.StatusCode == 500 {
log.Printf("Error querying untappd: %s, %s", resp.Status, body) log.Error().Msgf("Error querying untappd: %s, %s", resp.Status, body)
return []checkin{}, errors.New(resp.Status) return []checkin{}, errors.New(resp.Status)
} }
var beers Beers var beers Beers
err = json.Unmarshal(body, &beers) err = json.Unmarshal(body, &beers)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
return []checkin{}, err return []checkin{}, err
} }
return beers.Response.Checkins.Items, nil return beers.Response.Checkins.Items, nil
@ -341,31 +346,32 @@ func (p *BeersPlugin) pullUntappd() ([]checkin, error) {
func (p *BeersPlugin) checkUntappd(channel string) { func (p *BeersPlugin) checkUntappd(channel string) {
token := p.Bot.Config().Get("Untappd.Token", "NONE") token := p.Bot.Config().Get("Untappd.Token", "NONE")
if token == "NONE" { if token == "NONE" {
log.Println(`Set config value "untappd.token" if you wish to enable untappd`) log.Info().
Msg(`Set config value "untappd.token" if you wish to enable untappd`)
return return
} }
userMap := make(map[string]untappdUser) userMap := make(map[string]untappdUser)
rows, err := p.db.Query(`select id, untappdUser, channel, lastCheckin, chanNick from untappd;`) rows, err := p.db.Query(`select id, untappdUser, channel, lastCheckin, chanNick from untappd;`)
if err != nil { if err != nil {
log.Println("Error getting untappd users: ", err) log.Error().Err(err).Msg("Error getting untappd users")
return return
} }
for rows.Next() { for rows.Next() {
u := untappdUser{} u := untappdUser{}
err := rows.Scan(&u.id, &u.untappdUser, &u.channel, &u.lastCheckin, &u.chanNick) err := rows.Scan(&u.id, &u.untappdUser, &u.channel, &u.lastCheckin, &u.chanNick)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
userMap[u.untappdUser] = u userMap[u.untappdUser] = u
if u.chanNick == "" { if u.chanNick == "" {
log.Fatal("Empty chanNick for no good reason.") log.Fatal().Msg("Empty chanNick for no good reason.")
} }
} }
chks, err := p.pullUntappd() chks, err := p.pullUntappd()
if err != nil { if err != nil {
log.Println("Untappd ERROR: ", err) log.Error().Err(err).Msg("Untappd ERROR")
return return
} }
for i := len(chks); i > 0; i-- { for i := len(chks); i > 0; i-- {
@ -386,7 +392,8 @@ func (p *BeersPlugin) checkUntappd(channel string) {
if !ok { if !ok {
continue continue
} }
log.Printf("user.chanNick: %s, user.untappdUser: %s, checkin.User.User_name: %s", log.Debug().
Msgf("user.chanNick: %s, user.untappdUser: %s, checkin.User.User_name: %s",
user.chanNick, user.untappdUser, checkin.User.User_name) user.chanNick, user.untappdUser, checkin.User.User_name)
p.addBeers(user.chanNick, 1) p.addBeers(user.chanNick, 1)
drunken := p.getBeers(user.chanNick) drunken := p.getBeers(user.chanNick)
@ -413,10 +420,13 @@ func (p *BeersPlugin) checkUntappd(channel string) {
lastCheckin = ? lastCheckin = ?
where id = ?`, user.lastCheckin, user.id) where id = ?`, user.lastCheckin, user.id)
if err != nil { if err != nil {
log.Println("UPDATE ERROR!:", err) log.Error().Err(err).Msg("UPDATE ERROR!")
} }
log.Println("checkin id:", checkin.Checkin_id, "Message:", msg) log.Debug().
Int("checkin_id", checkin.Checkin_id).
Str("msg", msg).
Msg("checkin")
p.Bot.Send(bot.Message, channel, msg) p.Bot.Send(bot.Message, channel, msg)
} }
} }
@ -427,7 +437,7 @@ func (p *BeersPlugin) untappdLoop(channel string) {
return return
} }
log.Println("Checking every ", frequency, " seconds") log.Info().Msgf("Checking every %v seconds", frequency)
for { for {
time.Sleep(time.Duration(frequency) * time.Second) time.Sleep(time.Duration(frequency) * time.Second)

View File

@ -5,12 +5,13 @@ package counter
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"log"
"math/rand" "math/rand"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -112,7 +113,7 @@ func GetItem(db *sqlx.DB, nick, itemName string) (Item, error) {
if err := db.Get(&a, `select * from counter_alias where item=?`, itemName); err == nil { if err := db.Get(&a, `select * from counter_alias where item=?`, itemName); err == nil {
itemName = a.PointsTo itemName = a.PointsTo
} else { } else {
log.Println(err, a) log.Error().Err(err).Interface("alias", a)
} }
err := db.Get(&item, `select * from counter where nick = ? and item= ?`, err := db.Get(&item, `select * from counter where nick = ? and item= ?`,
@ -126,7 +127,11 @@ func GetItem(db *sqlx.DB, nick, itemName string) (Item, error) {
default: default:
return Item{}, err return Item{}, err
} }
log.Printf("Got item %s.%s: %#v", nick, itemName, item) log.Debug().
Str("nick", nick).
Str("itemName", itemName).
Interface("item", item).
Msg("got item")
return item, nil return item, nil
} }
@ -153,7 +158,10 @@ func (i *Item) Update(value int) error {
if i.ID == -1 { if i.ID == -1 {
i.Create() i.Create()
} }
log.Printf("Updating item: %#v, value: %d", i, value) log.Debug().
Interface("i", i).
Int("value", value).
Msg("Updating item")
_, err := i.Exec(`update counter set count = ? where id = ?`, i.Count, i.ID) _, err := i.Exec(`update counter set count = ? where id = ?`, i.Count, i.ID)
return err return err
} }
@ -212,7 +220,7 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
if len(parts) == 3 && strings.ToLower(parts[0]) == "mkalias" { if len(parts) == 3 && strings.ToLower(parts[0]) == "mkalias" {
if _, err := MkAlias(p.DB, parts[1], parts[2]); err != nil { if _, err := MkAlias(p.DB, parts[1], parts[2]); err != nil {
log.Println(err) log.Error().Err(err)
return false return false
} }
p.Bot.Send(bot.Message, channel, fmt.Sprintf("Created alias %s -> %s", p.Bot.Send(bot.Message, channel, fmt.Sprintf("Created alias %s -> %s",
@ -231,7 +239,7 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
its, err := cmd() its, err := cmd()
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
return false return false
} else if len(its) == 0 { } else if len(its) == 0 {
return false return false
@ -253,11 +261,14 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
} else if message.Command && message.Body == "reset me" { } else if message.Command && message.Body == "reset me" {
items, err := GetItems(p.DB, strings.ToLower(nick)) items, err := GetItems(p.DB, strings.ToLower(nick))
if err != nil { if err != nil {
log.Printf("Error getting items to reset %s: %s", nick, err) log.Error().
Err(err).
Str("nick", nick).
Msg("Error getting items to reset")
p.Bot.Send(bot.Message, channel, "Something is technically wrong with your counters.") p.Bot.Send(bot.Message, channel, "Something is technically wrong with your counters.")
return true return true
} }
log.Printf("Items: %+v", items) log.Debug().Msgf("Items: %+v", items)
for _, item := range items { for _, item := range items {
item.Delete() item.Delete()
} }
@ -272,11 +283,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
subject = strings.ToLower(parts[1]) subject = strings.ToLower(parts[1])
} }
log.Printf("Getting counter for %s", subject) log.Debug().
Str("subject", subject).
Msg("Getting counter")
// pull all of the items associated with "subject" // pull all of the items associated with "subject"
items, err := GetItems(p.DB, subject) items, err := GetItems(p.DB, subject)
if err != nil { if err != nil {
log.Fatalf("Error retrieving items for %s: %s", subject, err) log.Error().
Err(err).
Str("subject", subject).
Msg("Error retrieving items")
p.Bot.Send(bot.Message, channel, "Something went wrong finding that counter;") p.Bot.Send(bot.Message, channel, "Something went wrong finding that counter;")
return true return true
} }
@ -309,13 +325,21 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
it, err := GetItem(p.DB, subject, itemName) it, err := GetItem(p.DB, subject, itemName)
if err != nil { if err != nil {
log.Printf("Error getting item to remove %s.%s: %s", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error getting item to remove")
p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;") p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;")
return true return true
} }
err = it.Delete() err = it.Delete()
if err != nil { if err != nil {
log.Printf("Error removing item %s.%s: %s", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error removing item")
p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;") p.Bot.Send(bot.Message, channel, "Something went wrong removing that counter;")
return true return true
} }
@ -347,8 +371,11 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
subject, itemName)) subject, itemName))
return true return true
case err != nil: case err != nil:
log.Printf("Error retrieving item count for %s.%s: %s", log.Error().
subject, itemName, err) Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error retrieving item count")
return true return true
} }
@ -377,11 +404,15 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
// ++ those fuckers // ++ those fuckers
item, err := GetItem(p.DB, subject, itemName) item, err := GetItem(p.DB, subject, itemName)
if err != nil { if err != nil {
log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("error finding item")
// Item ain't there, I guess // Item ain't there, I guess
return false return false
} }
log.Printf("About to update item: %#v", item) log.Debug().Msgf("About to update item: %#v", item)
item.UpdateDelta(1) item.UpdateDelta(1)
p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject,
item.Count, item.Item)) item.Count, item.Item))
@ -390,7 +421,11 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
// -- those fuckers // -- those fuckers
item, err := GetItem(p.DB, subject, itemName) item, err := GetItem(p.DB, subject, itemName)
if err != nil { if err != nil {
log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error finding item")
// Item ain't there, I guess // Item ain't there, I guess
return false return false
} }
@ -417,12 +452,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
// += those fuckers // += those fuckers
item, err := GetItem(p.DB, subject, itemName) item, err := GetItem(p.DB, subject, itemName)
if err != nil { if err != nil {
log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error finding item")
// Item ain't there, I guess // Item ain't there, I guess
return false return false
} }
n, _ := strconv.Atoi(parts[2]) n, _ := strconv.Atoi(parts[2])
log.Printf("About to update item by %d: %#v", n, item) log.Debug().Msgf("About to update item by %d: %#v", n, item)
item.UpdateDelta(n) item.UpdateDelta(n)
p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject,
item.Count, item.Item)) item.Count, item.Item))
@ -431,12 +470,16 @@ func (p *CounterPlugin) message(kind bot.Kind, message msg.Message, args ...inte
// -= those fuckers // -= those fuckers
item, err := GetItem(p.DB, subject, itemName) item, err := GetItem(p.DB, subject, itemName)
if err != nil { if err != nil {
log.Printf("Error finding item %s.%s: %s.", subject, itemName, err) log.Error().
Err(err).
Str("subject", subject).
Str("itemName", itemName).
Msg("Error finding item")
// Item ain't there, I guess // Item ain't there, I guess
return false return false
} }
n, _ := strconv.Atoi(parts[2]) n, _ := strconv.Atoi(parts[2])
log.Printf("About to update item by -%d: %#v", n, item) log.Debug().Msgf("About to update item by -%d: %#v", n, item)
item.UpdateDelta(-n) item.UpdateDelta(-n)
p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject, p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s has %d %s.", subject,
item.Count, item.Item)) item.Count, item.Item))
@ -469,11 +512,14 @@ func (p *CounterPlugin) checkMatch(message msg.Message) bool {
// We will specifically allow :tea: to keep compatability // We will specifically allow :tea: to keep compatability
item, err := GetItem(p.DB, nick, itemName) item, err := GetItem(p.DB, nick, itemName)
if err != nil || (item.Count == 0 && item.Item != ":tea:") { if err != nil || (item.Count == 0 && item.Item != ":tea:") {
log.Printf("Error finding item %s.%s: %s.", nick, itemName, err) log.Error().
Err(err).
Str("itemName", itemName).
Msg("Error finding item")
// Item ain't there, I guess // Item ain't there, I guess
return false return false
} }
log.Printf("About to update item: %#v", item) log.Debug().Msgf("About to update item: %#v", item)
item.UpdateDelta(1) item.UpdateDelta(1)
p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s... %s has %d %s", p.Bot.Send(bot.Message, channel, fmt.Sprintf("%s... %s has %d %s",
strings.Join(everyDayImShuffling([]string{"bleep", "bloop", "blop"}), "-"), nick, item.Count, itemName)) strings.Join(everyDayImShuffling([]string{"bleep", "bloop", "blop"}), "-"), nick, item.Count, itemName))

View File

@ -2,11 +2,12 @@ package db
import ( import (
"fmt" "fmt"
"log"
"net/http" "net/http"
"os" "os"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/config" "github.com/velour/catbase/config"
@ -37,7 +38,7 @@ func (p *DBPlugin) serveQuery(w http.ResponseWriter, r *http.Request) {
f, err := os.Open(p.bot.Config().DBFile) f, err := os.Open(p.bot.Config().DBFile)
defer f.Close() defer f.Close()
if err != nil { if err != nil {
log.Printf("Error opening DB for web service: %s", err) log.Error().Err(err).Msg("Error opening DB for web service")
fmt.Fprintf(w, "Error opening DB") fmt.Fprintf(w, "Error opening DB")
return return
} }

View File

@ -5,11 +5,12 @@ package emojifyme
import ( import (
"encoding/json" "encoding/json"
"io/ioutil" "io/ioutil"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"strings" "strings"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
) )
@ -23,12 +24,12 @@ type EmojifyMePlugin struct {
func New(b bot.Bot) *EmojifyMePlugin { func New(b bot.Bot) *EmojifyMePlugin {
resp, err := http.Get("https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json") resp, err := http.Get("https://raw.githubusercontent.com/github/gemoji/master/db/emoji.json")
if err != nil { if err != nil {
log.Fatalf("Error generic emoji list: %s", err) log.Fatal().Err(err).Msg("Error generic emoji list")
} }
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if err != nil { if err != nil {
log.Fatalf("Error generic emoji list body: %s", err) log.Fatal().Err(err).Msg("Error generic emoji list body")
} }
type Emoji struct { type Emoji struct {
@ -38,7 +39,7 @@ func New(b bot.Bot) *EmojifyMePlugin {
var emoji []Emoji var emoji []Emoji
err = json.Unmarshal(body, &emoji) err = json.Unmarshal(body, &emoji)
if err != nil { if err != nil {
log.Fatalf("Error parsing emoji list: %s", err) log.Fatal().Err(err).Msg("Error parsing emoji list")
} }
emojiMap := map[string]string{} emojiMap := map[string]string{}

View File

@ -6,13 +6,14 @@ import (
"database/sql" "database/sql"
"fmt" "fmt"
"html/template" "html/template"
"log"
"math/rand" "math/rand"
"net/http" "net/http"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -166,7 +167,7 @@ func getFacts(db *sqlx.DB, fact string, tidbit string) ([]*Factoid, error) {
rows, err := db.Query(query, rows, err := db.Query(query,
"%"+fact+"%", "%"+tidbit+"%") "%"+fact+"%", "%"+tidbit+"%")
if err != nil { if err != nil {
log.Printf("Error regexping for facts: %s", err) log.Error().Err(err).Msg("Error regexping for facts")
return nil, err return nil, err
} }
for rows.Next() { for rows.Next() {
@ -286,7 +287,7 @@ func New(botInst bot.Bot) *FactoidPlugin {
accessed integer, accessed integer,
count integer count integer
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
if _, err := p.db.Exec(`create table if not exists factoid_alias ( if _, err := p.db.Exec(`create table if not exists factoid_alias (
@ -294,7 +295,7 @@ func New(botInst bot.Bot) *FactoidPlugin {
next string, next string,
primary key (fact, next) primary key (fact, next)
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
for _, channel := range botInst.Config().GetArray("channels", []string{}) { for _, channel := range botInst.Config().GetArray("channels", []string{}) {
@ -359,10 +360,10 @@ func (p *FactoidPlugin) learnFact(message msg.Message, fact, verb, tidbit string
where fact=? and verb=? and tidbit=?`, where fact=? and verb=? and tidbit=?`,
fact, verb, tidbit).Scan(&count) fact, verb, tidbit).Scan(&count)
if err != nil { if err != nil {
log.Println("Error counting facts: ", err) log.Error().Err(err).Msg("Error counting facts")
return fmt.Errorf("What?") return fmt.Errorf("What?")
} else if count.Valid && count.Int64 != 0 { } else if count.Valid && count.Int64 != 0 {
log.Println("User tried to relearn a fact.") log.Debug().Msg("User tried to relearn a fact.")
return fmt.Errorf("Look, I already know that.") return fmt.Errorf("Look, I already know that.")
} }
@ -378,7 +379,7 @@ func (p *FactoidPlugin) learnFact(message msg.Message, fact, verb, tidbit string
p.LastFact = &n p.LastFact = &n
err = n.Save(p.db) err = n.Save(p.db)
if err != nil { if err != nil {
log.Println("Error inserting fact: ", err) log.Error().Err(err).Msg("Error inserting fact")
return fmt.Errorf("My brain is overheating.") return fmt.Errorf("My brain is overheating.")
} }
@ -425,9 +426,10 @@ func (p *FactoidPlugin) sayFact(message msg.Message, fact Factoid) {
fact.Count += 1 fact.Count += 1
err := fact.Save(p.db) err := fact.Save(p.db)
if err != nil { if err != nil {
log.Printf("Could not update fact.\n") log.Error().
log.Printf("%#v\n", fact) Interface("fact", fact).
log.Println(err) Err(err).
Msg("could not update fact")
} }
p.LastFact = &fact p.LastFact = &fact
} }
@ -520,7 +522,10 @@ func (p *FactoidPlugin) forgetLastFact(message msg.Message) bool {
err := p.LastFact.delete(p.db) err := p.LastFact.delete(p.db)
if err != nil { if err != nil {
log.Println("Error removing fact: ", p.LastFact, err) log.Error().
Err(err).
Interface("LastFact", p.LastFact).
Msg("Error removing fact")
} }
fmt.Printf("Forgot #%d: %s %s %s\n", p.LastFact.ID.Int64, p.LastFact.Fact, fmt.Printf("Forgot #%d: %s %s %s\n", p.LastFact.ID.Int64, p.LastFact.Fact,
p.LastFact.Verb, p.LastFact.Tidbit) p.LastFact.Verb, p.LastFact.Tidbit)
@ -539,7 +544,11 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool {
parts = strings.Split(userexp, "/") parts = strings.Split(userexp, "/")
log.Printf("changeFact: %s %s %#v", trigger, userexp, parts) log.Debug().
Str("trigger", trigger).
Str("userexp", userexp).
Strs("parts", parts).
Msg("changefact")
if len(parts) == 4 { if len(parts) == 4 {
// replacement // replacement
@ -552,7 +561,10 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool {
// replacement // replacement
result, err := getFacts(p.db, trigger, parts[1]) result, err := getFacts(p.db, trigger, parts[1])
if err != nil { if err != nil {
log.Println("Error getting facts: ", trigger, err) log.Error().
Err(err).
Str("trigger", trigger).
Msg("Error getting facts")
} }
if userexp[len(userexp)-1] != 'g' { if userexp[len(userexp)-1] != 'g' {
result = result[:1] result = result[:1]
@ -578,7 +590,10 @@ func (p *FactoidPlugin) changeFact(message msg.Message) bool {
// search for a factoid and print it // search for a factoid and print it
result, err := getFacts(p.db, trigger, parts[1]) result, err := getFacts(p.db, trigger, parts[1])
if err != nil { if err != nil {
log.Println("Error getting facts: ", trigger, err) log.Error().
Err(err).
Str("trigger", trigger).
Msg("Error getting facts")
p.Bot.Send(bot.Message, message.Channel, "bzzzt") p.Bot.Send(bot.Message, message.Channel, "bzzzt")
return true return true
} }
@ -626,7 +641,9 @@ func (p *FactoidPlugin) message(kind bot.Kind, message msg.Message, args ...inte
} }
if strings.HasPrefix(strings.ToLower(message.Body), "alias") { if strings.HasPrefix(strings.ToLower(message.Body), "alias") {
log.Printf("Trying to learn an alias: %s", message.Body) log.Debug().
Str("alias", message.Body).
Msg("Trying to learn an alias")
m := strings.TrimPrefix(message.Body, "alias ") m := strings.TrimPrefix(message.Body, "alias ")
parts := strings.SplitN(m, "->", 2) parts := strings.SplitN(m, "->", 2)
if len(parts) != 2 { if len(parts) != 2 {
@ -647,7 +664,7 @@ func (p *FactoidPlugin) message(kind bot.Kind, message msg.Message, args ...inte
p.sayFact(message, *fact) p.sayFact(message, *fact)
return true return true
} }
log.Println("Got a nil fact.") log.Debug().Msg("Got a nil fact.")
} }
if strings.ToLower(message.Body) == "forget that" { if strings.ToLower(message.Body) == "forget that" {
@ -721,7 +738,7 @@ func (p *FactoidPlugin) factTimer(channel string) {
if success && tdelta > duration && earlier { if success && tdelta > duration && earlier {
fact := p.randomFact() fact := p.randomFact()
if fact == nil { if fact == nil {
log.Println("Didn't find a random fact to say") log.Debug().Msg("Didn't find a random fact to say")
continue continue
} }
@ -764,7 +781,7 @@ func (p *FactoidPlugin) serveQuery(w http.ResponseWriter, r *http.Request) {
if e := r.FormValue("entry"); e != "" { if e := r.FormValue("entry"); e != "" {
entries, err := getFacts(p.db, e, "") entries, err := getFacts(p.db, e, "")
if err != nil { if err != nil {
log.Println("Web error searching: ", err) log.Error().Err(err).Msg("Web error searching")
} }
context["Count"] = fmt.Sprintf("%d", len(entries)) context["Count"] = fmt.Sprintf("%d", len(entries))
context["Entries"] = entries context["Entries"] = entries
@ -772,10 +789,10 @@ func (p *FactoidPlugin) serveQuery(w http.ResponseWriter, r *http.Request) {
} }
t, err := template.New("factoidIndex").Funcs(funcMap).Parse(factoidIndex) t, err := template.New("factoidIndex").Funcs(funcMap).Parse(factoidIndex)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
} }
err = t.Execute(w, context) err = t.Execute(w, context)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
} }
} }

View File

@ -5,12 +5,12 @@ package first
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"log"
"regexp" "regexp"
"strings" "strings"
"time" "time"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
) )
@ -56,14 +56,19 @@ func New(b bot.Bot) *FirstPlugin {
nick string nick string
);`) );`)
if err != nil { if err != nil {
log.Fatal("Could not create first table: ", err) log.Fatal().
Err(err).
Msg("Could not create first table")
} }
log.Println("First plugin initialized with day:", midnight(time.Now())) log.Info().Msgf("First plugin initialized with day: %s",
midnight(time.Now()))
first, err := getLastFirst(b.DB()) first, err := getLastFirst(b.DB())
if err != nil { if err != nil {
log.Fatal("Could not initialize first plugin: ", err) log.Fatal().
Err(err).
Msg("Could not initialize first plugin")
} }
fp := &FirstPlugin{ fp := &FirstPlugin{
@ -96,13 +101,14 @@ func getLastFirst(db *sqlx.DB) (*FirstEntry, error) {
) )
switch { switch {
case err == sql.ErrNoRows || !id.Valid: case err == sql.ErrNoRows || !id.Valid:
log.Println("No previous first entries") log.Info().Msg("No previous first entries")
return nil, nil return nil, nil
case err != nil: case err != nil:
log.Println("Error on first query row: ", err) log.Warn().Err(err).Msg("Error on first query row")
return nil, err return nil, err
} }
log.Println(id, day, timeEntered, body, nick) log.Debug().Msgf("id: %v day %v time %v body %v nick %v",
id, day, timeEntered, body, nick)
return &FirstEntry{ return &FirstEntry{
id: id.Int64, id: id.Int64,
day: time.Unix(day.Int64, 0), day: time.Unix(day.Int64, 0),
@ -130,12 +136,18 @@ func (p *FirstPlugin) message(kind bot.Kind, message msg.Message, args ...interf
// This bot does not reply to anything // This bot does not reply to anything
if p.First == nil && p.allowed(message) { if p.First == nil && p.allowed(message) {
log.Printf("No previous first. Recording new first: %s", message.Body) log.Debug().
Str("body", message.Body).
Msg("No previous first. Recording new first")
p.recordFirst(message) p.recordFirst(message)
return false return false
} else if p.First != nil { } else if p.First != nil {
if isToday(p.First.time) && p.allowed(message) { if isToday(p.First.time) && p.allowed(message) {
log.Printf("Recording first: %s - %v vs %v", message.Body, p.First.time, time.Now()) log.Debug().
Str("body", message.Body).
Time("t0", p.First.time).
Time("t1", time.Now()).
Msg("Recording first")
p.recordFirst(message) p.recordFirst(message)
return false return false
} }
@ -156,22 +168,31 @@ func (p *FirstPlugin) allowed(message msg.Message) bool {
for _, msg := range p.Bot.Config().GetArray("Bad.Msgs", []string{}) { for _, msg := range p.Bot.Config().GetArray("Bad.Msgs", []string{}) {
match, err := regexp.MatchString(msg, strings.ToLower(message.Body)) match, err := regexp.MatchString(msg, strings.ToLower(message.Body))
if err != nil { if err != nil {
log.Println("Bad regexp: ", err) log.Error().Err(err).Msg("Bad regexp")
} }
if match { if match {
log.Println("Disallowing first: ", message.User.Name, ":", message.Body) log.Info().
Str("user", message.User.Name).
Str("body", message.Body).
Msg("Disallowing first")
return false return false
} }
} }
for _, host := range p.Bot.Config().GetArray("Bad.Hosts", []string{}) { for _, host := range p.Bot.Config().GetArray("Bad.Hosts", []string{}) {
if host == message.Host { if host == message.Host {
log.Println("Disallowing first: ", message.User.Name, ":", message.Body) log.Info().
Str("user", message.User.Name).
Str("body", message.Body).
Msg("Disallowing first")
return false return false
} }
} }
for _, nick := range p.Bot.Config().GetArray("Bad.Nicks", []string{}) { for _, nick := range p.Bot.Config().GetArray("Bad.Nicks", []string{}) {
if nick == message.User.Name { if nick == message.User.Name {
log.Println("Disallowing first: ", message.User.Name, ":", message.Body) log.Info().
Str("user", message.User.Name).
Str("body", message.Body).
Msg("Disallowing first")
return false return false
} }
} }
@ -179,17 +200,20 @@ func (p *FirstPlugin) allowed(message msg.Message) bool {
} }
func (p *FirstPlugin) recordFirst(message msg.Message) { func (p *FirstPlugin) recordFirst(message msg.Message) {
log.Println("Recording first: ", message.User.Name, ":", message.Body) log.Info().
Str("user", message.User.Name).
Str("body", message.Body).
Msg("Recording first")
p.First = &FirstEntry{ p.First = &FirstEntry{
day: midnight(time.Now()), day: midnight(time.Now()),
time: message.Time, time: message.Time,
body: message.Body, body: message.Body,
nick: message.User.Name, nick: message.User.Name,
} }
log.Printf("recordFirst: %+v", p.First.day) log.Info().Msgf("recordFirst: %+v", p.First.day)
err := p.First.save(p.db) err := p.First.save(p.db)
if err != nil { if err != nil {
log.Println("Error saving first entry: ", err) log.Error().Err(err).Msg("Error saving first entry")
return return
} }
p.announceFirst(message) p.announceFirst(message)

View File

@ -6,10 +6,11 @@ package inventory
import ( import (
"fmt" "fmt"
"log"
"regexp" "regexp"
"strings" "strings"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -53,7 +54,7 @@ func New(b bot.Bot) *InventoryPlugin {
);`) );`)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
b.Register(p, bot.Message, p.message) b.Register(p, bot.Message, p.message)
@ -79,13 +80,13 @@ func (p *InventoryPlugin) itemFilter(input string) string {
func (p *InventoryPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool { func (p *InventoryPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool {
m := message.Body m := message.Body
log.Printf("inventory trying to read %+v", message) log.Debug().Msgf("inventory trying to read %+v", message)
if message.Command { if message.Command {
if strings.ToLower(m) == "inventory" { if strings.ToLower(m) == "inventory" {
items := p.getAll() items := p.getAll()
say := "I'm not holding anything" say := "I'm not holding anything"
if len(items) > 0 { if len(items) > 0 {
log.Printf("I think I have more than 0 items: %+v, len(items)=%d", items, len(items)) log.Debug().Msgf("I think I have more than 0 items: %+v, len(items)=%d", items, len(items))
say = fmt.Sprintf("I'm currently holding %s", strings.Join(items, ", ")) say = fmt.Sprintf("I'm currently holding %s", strings.Join(items, ", "))
} }
p.bot.Send(bot.Message, message.Channel, say) p.bot.Send(bot.Message, message.Channel, say)
@ -95,30 +96,30 @@ func (p *InventoryPlugin) message(kind bot.Kind, message msg.Message, args ...in
// <Randall> Bucket[:,] take this (.+) // <Randall> Bucket[:,] take this (.+)
// <Randall> Bucket[:,] have a (.+) // <Randall> Bucket[:,] have a (.+)
if matches := p.r1.FindStringSubmatch(m); len(matches) > 0 { if matches := p.r1.FindStringSubmatch(m); len(matches) > 0 {
log.Printf("Found item to add: %s", matches[1]) log.Debug().Msgf("Found item to add: %s", matches[1])
return p.addItem(message, matches[1]) return p.addItem(message, matches[1])
} }
if matches := p.r2.FindStringSubmatch(m); len(matches) > 0 { if matches := p.r2.FindStringSubmatch(m); len(matches) > 0 {
log.Printf("Found item to add: %s", matches[1]) log.Debug().Msgf("Found item to add: %s", matches[1])
return p.addItem(message, matches[1]) return p.addItem(message, matches[1])
} }
} }
if message.Action { if message.Action {
log.Println("Inventory found an action") log.Debug().Msg("Inventory found an action")
// * Randall puts (.+) in Bucket([^a-zA-Z].*)? // * Randall puts (.+) in Bucket([^a-zA-Z].*)?
// * Randall gives Bucket (.+) // * Randall gives Bucket (.+)
// * Randall gives (.+) to Bucket([^a-zA-Z].*)? // * Randall gives (.+) to Bucket([^a-zA-Z].*)?
if matches := p.r3.FindStringSubmatch(m); len(matches) > 0 { if matches := p.r3.FindStringSubmatch(m); len(matches) > 0 {
log.Printf("Found item to add: %s", matches[1]) log.Debug().Msgf("Found item to add: %s", matches[1])
return p.addItem(message, matches[1]) return p.addItem(message, matches[1])
} }
if matches := p.r4.FindStringSubmatch(m); len(matches) > 0 { if matches := p.r4.FindStringSubmatch(m); len(matches) > 0 {
log.Printf("Found item to add: %s", matches[1]) log.Debug().Msgf("Found item to add: %s", matches[1])
return p.addItem(message, matches[1]) return p.addItem(message, matches[1])
} }
if matches := p.r5.FindStringSubmatch(m); len(matches) > 0 { if matches := p.r5.FindStringSubmatch(m); len(matches) > 0 {
log.Printf("Found item to add: %s", matches[1]) log.Debug().Msgf("Found item to add: %s", matches[1])
return p.addItem(message, matches[1]) return p.addItem(message, matches[1])
} }
} }
@ -131,12 +132,12 @@ func (p *InventoryPlugin) removeRandom() string {
&name, &name,
) )
if err != nil { if err != nil {
log.Printf("Error finding random entry: %s", err) log.Error().Err(err).Msgf("Error finding random entry")
return "IAMERROR" return "IAMERROR"
} }
_, err = p.Exec(`delete from inventory where item=?`, name) _, err = p.Exec(`delete from inventory where item=?`, name)
if err != nil { if err != nil {
log.Printf("Error finding random entry: %s", err) log.Error().Err(err).Msgf("Error finding random entry")
return "IAMERROR" return "IAMERROR"
} }
return name return name
@ -146,7 +147,7 @@ func (p *InventoryPlugin) count() int {
var output int var output int
err := p.QueryRow(`select count(*) as count from inventory`).Scan(&output) err := p.QueryRow(`select count(*) as count from inventory`).Scan(&output)
if err != nil { if err != nil {
log.Printf("Error checking for item: %s", err) log.Error().Err(err).Msg("Error checking for item")
return -1 return -1
} }
return output return output
@ -158,7 +159,7 @@ func (p *InventoryPlugin) random() string {
&name, &name,
) )
if err != nil { if err != nil {
log.Printf("Error finding random entry: %s", err) log.Error().Err(err).Msg("Error finding random entry")
return "IAMERROR" return "IAMERROR"
} }
return name return name
@ -167,7 +168,7 @@ func (p *InventoryPlugin) random() string {
func (p *InventoryPlugin) getAll() []string { func (p *InventoryPlugin) getAll() []string {
rows, err := p.Queryx(`select item from inventory`) rows, err := p.Queryx(`select item from inventory`)
if err != nil { if err != nil {
log.Printf("Error getting all items: %s", err) log.Error().Err(err).Msg("Error getting all items")
return []string{} return []string{}
} }
output := []string{} output := []string{}
@ -184,7 +185,7 @@ func (p *InventoryPlugin) exists(i string) bool {
var output int var output int
err := p.QueryRow(`select count(*) as count from inventory where item=?`, i).Scan(&output) err := p.QueryRow(`select count(*) as count from inventory where item=?`, i).Scan(&output)
if err != nil { if err != nil {
log.Printf("Error checking for item: %s", err) log.Error().Err(err).Msg("Error checking for item")
return false return false
} }
return output > 0 return output > 0
@ -193,7 +194,7 @@ func (p *InventoryPlugin) exists(i string) bool {
func (p *InventoryPlugin) remove(i string) { func (p *InventoryPlugin) remove(i string) {
_, err := p.Exec(`delete from inventory where item=?`, i) _, err := p.Exec(`delete from inventory where item=?`, i)
if err != nil { if err != nil {
log.Printf("Error inserting new inventory item: %s", err) log.Error().Msg("Error inserting new inventory item")
} }
} }
@ -209,7 +210,7 @@ func (p *InventoryPlugin) addItem(m msg.Message, i string) bool {
} }
_, err := p.Exec(`INSERT INTO inventory (item) values (?)`, i) _, err := p.Exec(`INSERT INTO inventory (item) values (?)`, i)
if err != nil { if err != nil {
log.Printf("Error inserting new inventory item: %s", err) log.Error().Err(err).Msg("Error inserting new inventory item")
} }
if removed != "" { if removed != "" {
p.bot.Send(bot.Action, m.Channel, fmt.Sprintf("dropped %s and took %s from %s", removed, i, m.User.Name)) p.bot.Send(bot.Action, m.Channel, fmt.Sprintf("dropped %s and took %s from %s", removed, i, m.User.Name))
@ -221,6 +222,6 @@ func (p *InventoryPlugin) addItem(m msg.Message, i string) bool {
func checkerr(e error) { func checkerr(e error) {
if e != nil { if e != nil {
log.Println(e) log.Error().Err(e)
} }
} }

View File

@ -2,10 +2,11 @@ package remember
import ( import (
"fmt" "fmt"
"log"
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -52,14 +53,14 @@ func (p *RememberPlugin) message(kind bot.Kind, message msg.Message, args ...int
snip := strings.Join(parts[2:], " ") snip := strings.Join(parts[2:], " ")
for i := len(p.log[message.Channel]) - 1; i >= 0; i-- { for i := len(p.log[message.Channel]) - 1; i >= 0; i-- {
entry := p.log[message.Channel][i] entry := p.log[message.Channel][i]
log.Printf("Comparing %s:%s with %s:%s", log.Debug().Msgf("Comparing %s:%s with %s:%s",
entry.User.Name, entry.Body, nick, snip) entry.User.Name, entry.Body, nick, snip)
if strings.ToLower(entry.User.Name) == strings.ToLower(nick) && if strings.ToLower(entry.User.Name) == strings.ToLower(nick) &&
strings.Contains( strings.Contains(
strings.ToLower(entry.Body), strings.ToLower(entry.Body),
strings.ToLower(snip), strings.ToLower(snip),
) { ) {
log.Printf("Found!") log.Debug().Msg("Found!")
var msg string var msg string
if entry.Action { if entry.Action {
@ -80,11 +81,13 @@ func (p *RememberPlugin) message(kind bot.Kind, message msg.Message, args ...int
Count: 0, Count: 0,
} }
if err := fact.Save(p.db); err != nil { if err := fact.Save(p.db); err != nil {
log.Println("ERROR!!!!:", err) log.Error().Err(err)
p.bot.Send(bot.Message, message.Channel, "Tell somebody I'm broke.") p.bot.Send(bot.Message, message.Channel, "Tell somebody I'm broke.")
} }
log.Println("Remembering factoid:", msg) log.Info().
Str("msg", msg).
Msg("Remembering factoid")
// sorry, not creative with names so we're reusing msg // sorry, not creative with names so we're reusing msg
msg = fmt.Sprintf("Okay, %s, remembering '%s'.", msg = fmt.Sprintf("Okay, %s, remembering '%s'.",
@ -134,7 +137,7 @@ func (p *RememberPlugin) randQuote() string {
&f.Count, &f.Count,
) )
if err != nil { if err != nil {
log.Println("Error getting quotes: ", err) log.Error().Err(err).Msg("Error getting quotes")
return "I had a problem getting your quote." return "I had a problem getting your quote."
} }
f.Created = time.Unix(tmpCreated, 0) f.Created = time.Unix(tmpCreated, 0)
@ -144,6 +147,6 @@ func (p *RememberPlugin) randQuote() string {
} }
func (p *RememberPlugin) recordMsg(message msg.Message) { func (p *RememberPlugin) recordMsg(message msg.Message) {
log.Printf("Logging message: %s: %s", message.User.Name, message.Body) log.Debug().Msgf("Logging message: %s: %s", message.User.Name, message.Body)
p.log[message.Channel] = append(p.log[message.Channel], message) p.log[message.Channel] = append(p.log[message.Channel], message)
} }

View File

@ -5,12 +5,13 @@ package reminder
import ( import (
"errors" "errors"
"fmt" "fmt"
"log"
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/jmoiron/sqlx" "github.com/jmoiron/sqlx"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
@ -39,7 +40,6 @@ type Reminder struct {
} }
func New(b bot.Bot) *ReminderPlugin { func New(b bot.Bot) *ReminderPlugin {
log.SetFlags(log.LstdFlags | log.Lshortfile)
if _, err := b.DB().Exec(`create table if not exists reminders ( if _, err := b.DB().Exec(`create table if not exists reminders (
id integer primary key, id integer primary key,
fromWho string, fromWho string,
@ -48,7 +48,7 @@ func New(b bot.Bot) *ReminderPlugin {
remindWhen string, remindWhen string,
channel string channel string
);`); err != nil { );`); err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
dur, _ := time.ParseDuration("1h") dur, _ := time.ParseDuration("1h")
@ -205,7 +205,7 @@ func (p *ReminderPlugin) getNextReminder() *Reminder {
defer p.mutex.Unlock() defer p.mutex.Unlock()
rows, err := p.db.Query("select id, fromWho, toWho, what, remindWhen, channel from reminders order by remindWhen asc limit 1;") rows, err := p.db.Query("select id, fromWho, toWho, what, remindWhen, channel from reminders order by remindWhen asc limit 1;")
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil return nil
} }
defer rows.Close() defer rows.Close()
@ -214,19 +214,19 @@ func (p *ReminderPlugin) getNextReminder() *Reminder {
var reminder *Reminder var reminder *Reminder
for rows.Next() { for rows.Next() {
if once { if once {
log.Print("somehow got multiple rows") log.Debug().Msg("somehow got multiple rows")
} }
reminder = &Reminder{} reminder = &Reminder{}
var when string var when string
err := rows.Scan(&reminder.id, &reminder.from, &reminder.who, &reminder.what, &when, &reminder.channel) err := rows.Scan(&reminder.id, &reminder.from, &reminder.who, &reminder.what, &when, &reminder.channel)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil return nil
} }
reminder.when, err = time.Parse(TIMESTAMP, when) reminder.when, err = time.Parse(TIMESTAMP, when)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return nil return nil
} }
@ -243,7 +243,7 @@ func (p *ReminderPlugin) addReminder(reminder *Reminder) error {
reminder.from, reminder.who, reminder.what, reminder.when.Format(TIMESTAMP), reminder.channel) reminder.from, reminder.who, reminder.what, reminder.when.Format(TIMESTAMP), reminder.channel)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
} }
return err return err
} }
@ -253,7 +253,7 @@ func (p *ReminderPlugin) deleteReminder(id int64) error {
defer p.mutex.Unlock() defer p.mutex.Unlock()
res, err := p.db.Exec(`delete from reminders where id = ?;`, id) res, err := p.db.Exec(`delete from reminders where id = ?;`, id)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
} else { } else {
if affected, err := res.RowsAffected(); err != nil { if affected, err := res.RowsAffected(); err != nil {
return err return err
@ -275,7 +275,7 @@ func (p *ReminderPlugin) getRemindersFormatted(filter string) (string, error) {
var total int var total int
err := p.db.Get(&total, countString) err := p.db.Get(&total, countString)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", nil return "", nil
} }
@ -285,7 +285,7 @@ func (p *ReminderPlugin) getRemindersFormatted(filter string) (string, error) {
rows, err := p.db.Query(queryString) rows, err := p.db.Query(queryString)
if err != nil { if err != nil {
log.Print(err) log.Error().Err(err)
return "", nil return "", nil
} }
defer rows.Close() defer rows.Close()
@ -348,9 +348,10 @@ func reminderer(p *ReminderPlugin) {
p.Bot.Send(bot.Message, reminder.channel, message) p.Bot.Send(bot.Message, reminder.channel, message)
if err := p.deleteReminder(reminder.id); err != nil { if err := p.deleteReminder(reminder.id); err != nil {
log.Print(reminder.id) log.Error().
log.Print(err) Int64("id", reminder.id).
log.Fatal("this will cause problems, we need to stop now.") Err(err).
Msg("this will cause problems, we need to stop now.")
} }
} }

View File

@ -2,12 +2,13 @@ package sisyphus
import ( import (
"fmt" "fmt"
"log"
"math/rand" "math/rand"
"strconv" "strconv"
"strings" "strings"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
) )
@ -192,7 +193,7 @@ func (p *SisyphusPlugin) replyMessage(kind bot.Kind, message msg.Message, args .
if strings.ToLower(message.User.Name) != strings.ToLower(p.Bot.Config().Get("Nick", "bot")) { if strings.ToLower(message.User.Name) != strings.ToLower(p.Bot.Config().Get("Nick", "bot")) {
if g, ok := p.listenFor[identifier]; ok { if g, ok := p.listenFor[identifier]; ok {
log.Printf("got message on %s: %+v", identifier, message) log.Debug().Msgf("got message on %s: %+v", identifier, message)
if g.ended { if g.ended {
return false return false

View File

@ -5,12 +5,13 @@ package talker
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/config" "github.com/velour/catbase/config"
@ -172,9 +173,9 @@ func (p *TalkerPlugin) allCows() []string {
func (p *TalkerPlugin) registerWeb() { func (p *TalkerPlugin) registerWeb() {
http.HandleFunc("/slash/cowsay", func(w http.ResponseWriter, r *http.Request) { http.HandleFunc("/slash/cowsay", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm() r.ParseForm()
log.Printf("Cowsay:\n%+v", r.PostForm.Get("text")) log.Debug().Msgf("Cowsay:\n%+v", r.PostForm.Get("text"))
channel := r.PostForm.Get("channel_id") channel := r.PostForm.Get("channel_id")
log.Printf("channel: %s", channel) log.Debug().Msgf("channel: %s", channel)
msg, err := p.cowSay(r.PostForm.Get("text")) msg, err := p.cowSay(r.PostForm.Get("text"))
if err != nil { if err != nil {
p.Bot.Send(bot.Message, channel, fmt.Sprintf("Error running cowsay: %s", err)) p.Bot.Send(bot.Message, channel, fmt.Sprintf("Error running cowsay: %s", err))

View File

@ -5,13 +5,13 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"text/template" "text/template"
"time" "time"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
"github.com/velour/catbase/config" "github.com/velour/catbase/config"
@ -110,12 +110,12 @@ func (p *TwitchPlugin) serveStreaming(w http.ResponseWriter, r *http.Request) {
t, err := template.New("streaming").Parse(page) t, err := template.New("streaming").Parse(page)
if err != nil { if err != nil {
log.Println("Could not parse template!", err) log.Error().Err(err).Msg("Could not parse template!")
return return
} }
err = t.Execute(w, context) err = t.Execute(w, context)
if err != nil { if err != nil {
log.Println("Could not execute template!", err) log.Error().Err(err).Msg("Could not execute template!")
} }
} }
@ -154,11 +154,11 @@ func (p *TwitchPlugin) help(kind bot.Kind, message msg.Message, args ...interfac
func (p *TwitchPlugin) twitchLoop(channel string) { func (p *TwitchPlugin) twitchLoop(channel string) {
frequency := p.config.GetInt("Twitch.Freq", 60) frequency := p.config.GetInt("Twitch.Freq", 60)
if p.config.Get("twitch.clientid", "") == "" || p.config.Get("twitch.authorization", "") == "" { if p.config.Get("twitch.clientid", "") == "" || p.config.Get("twitch.authorization", "") == "" {
log.Println("Disabling twitch autochecking.") log.Info().Msgf("Disabling twitch autochecking.")
return return
} }
log.Println("Checking every ", frequency, " seconds") log.Info().Msgf("Checking every %d seconds", frequency)
for { for {
time.Sleep(time.Duration(frequency) * time.Second) time.Sleep(time.Duration(frequency) * time.Second)
@ -193,14 +193,14 @@ func getRequest(url, clientID, authorization string) ([]byte, bool) {
return body, true return body, true
errCase: errCase:
log.Println(err) log.Error().Err(err)
return []byte{}, false return []byte{}, false
} }
func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPrintStatus bool) { func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPrintStatus bool) {
baseURL, err := url.Parse("https://api.twitch.tv/helix/streams") baseURL, err := url.Parse("https://api.twitch.tv/helix/streams")
if err != nil { if err != nil {
log.Println("Error parsing twitch stream URL") log.Error().Msg("Error parsing twitch stream URL")
return return
} }
@ -212,7 +212,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
cid := p.config.Get("Twitch.ClientID", "") cid := p.config.Get("Twitch.ClientID", "")
auth := p.config.Get("Twitch.Authorization", "") auth := p.config.Get("Twitch.Authorization", "")
if cid == auth && cid == "" { if cid == auth && cid == "" {
log.Println("Twitch plugin not enabled.") log.Info().Msgf("Twitch plugin not enabled.")
return return
} }
@ -224,7 +224,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
var s stream var s stream
err = json.Unmarshal(body, &s) err = json.Unmarshal(body, &s)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
return return
} }
@ -254,7 +254,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
if gameID == "" { if gameID == "" {
t, err := template.New("notStreaming").Parse(notStreamingTpl) t, err := template.New("notStreaming").Parse(notStreamingTpl)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
p.Bot.Send(bot.Message, channel, err) p.Bot.Send(bot.Message, channel, err)
t = template.Must(template.New("notStreaming").Parse(notStreamingTplFallback)) t = template.Must(template.New("notStreaming").Parse(notStreamingTplFallback))
} }
@ -263,7 +263,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
} else { } else {
t, err := template.New("isStreaming").Parse(isStreamingTpl) t, err := template.New("isStreaming").Parse(isStreamingTpl)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
p.Bot.Send(bot.Message, channel, err) p.Bot.Send(bot.Message, channel, err)
t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback))
} }
@ -274,7 +274,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
if twitcher.gameID != "" { if twitcher.gameID != "" {
t, err := template.New("stoppedStreaming").Parse(stoppedStreamingTpl) t, err := template.New("stoppedStreaming").Parse(stoppedStreamingTpl)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
p.Bot.Send(bot.Message, channel, err) p.Bot.Send(bot.Message, channel, err)
t = template.Must(template.New("stoppedStreaming").Parse(stoppedStreamingTplFallback)) t = template.Must(template.New("stoppedStreaming").Parse(stoppedStreamingTplFallback))
} }
@ -286,7 +286,7 @@ func (p *TwitchPlugin) checkTwitch(channel string, twitcher *Twitcher, alwaysPri
if twitcher.gameID != gameID { if twitcher.gameID != gameID {
t, err := template.New("isStreaming").Parse(isStreamingTpl) t, err := template.New("isStreaming").Parse(isStreamingTpl)
if err != nil { if err != nil {
log.Println(err) log.Error().Err(err)
p.Bot.Send(bot.Message, channel, err) p.Bot.Send(bot.Message, channel, err)
t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback)) t = template.Must(template.New("isStreaming").Parse(isStreamingTplFallback))
} }

View File

@ -8,12 +8,13 @@ import (
"bytes" "bytes"
"go/build" "go/build"
"io" "io"
"log"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"sync" "sync"
"github.com/rs/zerolog/log"
"github.com/velour/catbase/bot" "github.com/velour/catbase/bot"
"github.com/velour/catbase/bot/msg" "github.com/velour/catbase/bot/msg"
) )
@ -52,7 +53,7 @@ func (p *ZorkPlugin) runZork(ch string) error {
var w io.WriteCloser var w io.WriteCloser
cmd.Stdin, w = io.Pipe() cmd.Stdin, w = io.Pipe()
log.Printf("zork running %v\n", cmd) log.Info().Msgf("zork running %v", cmd)
if err := cmd.Start(); err != nil { if err := cmd.Start(); err != nil {
w.Close() w.Close()
return err return err
@ -83,20 +84,20 @@ func (p *ZorkPlugin) runZork(ch string) error {
}() }()
go func() { go func() {
if err := cmd.Wait(); err != nil { if err := cmd.Wait(); err != nil {
log.Printf("zork exited: %v\n", err) log.Error().Err(err).Msg("zork exited")
} }
p.Lock() p.Lock()
p.zorks[ch] = nil p.zorks[ch] = nil
p.Unlock() p.Unlock()
}() }()
log.Printf("zork is running in %s\n", ch) log.Info().Msgf("zork is running in %s\n", ch)
p.zorks[ch] = w p.zorks[ch] = w
return nil return nil
} }
func (p *ZorkPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool { func (p *ZorkPlugin) message(kind bot.Kind, message msg.Message, args ...interface{}) bool {
m := strings.ToLower(message.Body) m := strings.ToLower(message.Body)
log.Printf("got message [%s]\n", m) log.Debug().Msgf("got message [%s]", m)
if ts := strings.Fields(m); len(ts) < 1 || ts[0] != "zork" { if ts := strings.Fields(m); len(ts) < 1 || ts[0] != "zork" {
return false return false
} }
@ -111,7 +112,7 @@ func (p *ZorkPlugin) message(kind bot.Kind, message msg.Message, args ...interfa
return true return true
} }
} }
log.Printf("zorking, [%s]\n", m) log.Debug().Msgf("zorking, [%s]", m)
io.WriteString(p.zorks[ch], m+"\n") io.WriteString(p.zorks[ch], m+"\n")
return true return true
} }

View File

@ -5,12 +5,14 @@ import (
"flag" "flag"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
) )
var ( var (
@ -20,9 +22,10 @@ var (
func main() { func main() {
flag.Parse() flag.Parse()
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
if *token == "" { if *token == "" {
log.Printf("No token provided.") log.Fatal().Msg("No token provided.")
return return
} }
@ -35,7 +38,7 @@ func main() {
func getFiles() map[string]string { func getFiles() map[string]string {
files := fileResp{} files := fileResp{}
log.Printf("Getting files") log.Debug().Msgf("Getting files")
body := mkReq("https://slack.com/api/emoji.list", body := mkReq("https://slack.com/api/emoji.list",
"token", *token, "token", *token,
) )
@ -43,9 +46,9 @@ func getFiles() map[string]string {
err := json.Unmarshal(body, &files) err := json.Unmarshal(body, &files)
checkErr(err) checkErr(err)
log.Printf("Ok: %v", files.Ok) log.Debug().Msgf("Ok: %v", files.Ok)
if !files.Ok { if !files.Ok {
log.Println(files) log.Debug().Msgf("%+v", files)
} }
return files.Files return files.Files
@ -55,7 +58,7 @@ func downloadFile(n, f string) {
url := strings.Replace(f, "\\", "", -1) // because fuck slack url := strings.Replace(f, "\\", "", -1) // because fuck slack
if strings.HasPrefix(url, "alias:") { if strings.HasPrefix(url, "alias:") {
log.Printf("Skipping alias: %s", url) log.Debug().Msgf("Skipping alias: %s", url)
return return
} }
@ -66,7 +69,7 @@ func downloadFile(n, f string) {
fname := filepath.Join(*path, n+"."+ext) fname := filepath.Join(*path, n+"."+ext)
log.Printf("Downloading from: %s", url) log.Debug().Msgf("Downloading from: %s", url)
client := &http.Client{} client := &http.Client{}
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
@ -82,18 +85,18 @@ func downloadFile(n, f string) {
defer out.Close() defer out.Close()
io.Copy(out, resp.Body) io.Copy(out, resp.Body)
log.Printf("Downloaded %s", f) log.Debug().Msgf("Downloaded %s", f)
} }
func checkErr(err error) { func checkErr(err error) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
} }
func mkReq(path string, arg ...string) []byte { func mkReq(path string, arg ...string) []byte {
if len(arg)%2 != 0 { if len(arg)%2 != 0 {
log.Fatal("Bad request arg number.") log.Fatal().Msg("Bad request arg number.")
} }
u, err := url.Parse(path) u, err := url.Parse(path)

View File

@ -5,13 +5,15 @@ import (
"flag" "flag"
"io" "io"
"io/ioutil" "io/ioutil"
"log"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path/filepath" "path/filepath"
"strconv" "strconv"
"strings" "strings"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
) )
var ( var (
@ -24,6 +26,7 @@ var (
func main() { func main() {
flag.Parse() flag.Parse()
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
for { for {
files, count := getFiles() files, count := getFiles()
@ -40,7 +43,7 @@ func main() {
func getFiles() ([]slackFile, int) { func getFiles() ([]slackFile, int) {
files := fileResp{} files := fileResp{}
log.Printf("Getting files") log.Debug().Msg("Getting files")
body := mkReq("https://slack.com/api/files.list", body := mkReq("https://slack.com/api/files.list",
"token", *token, "token", *token,
"count", strconv.Itoa(*limit), "count", strconv.Itoa(*limit),
@ -50,9 +53,11 @@ func getFiles() ([]slackFile, int) {
err := json.Unmarshal(body, &files) err := json.Unmarshal(body, &files)
checkErr(err) checkErr(err)
log.Printf("Ok: %v, Count: %d", files.Ok, files.Paging.Count) log.Info().
Int("count", files.Paging.Count).
Bool("ok", files.Ok)
if !files.Ok { if !files.Ok {
log.Println(files) log.Error().Interface("files", files)
} }
return files.Files, files.Paging.Pages return files.Files, files.Paging.Pages
@ -69,18 +74,24 @@ func deleteFile(f slackFile) {
checkErr(err) checkErr(err)
if !del.Ok { if !del.Ok {
log.Println(body) log.Fatal().
log.Fatal("Couldn't delete " + f.ID) Bytes("body", body).
Str("id", f.ID).
Msg("Couldn't delete")
} }
log.Printf("Deleted %s", f.ID) log.Info().
Str("id", f.ID).
Msg("Deleted")
} }
func downloadFile(f slackFile) { func downloadFile(f slackFile) {
url := strings.Replace(f.URLPrivateDownload, "\\", "", -1) // because fuck slack url := strings.Replace(f.URLPrivateDownload, "\\", "", -1) // because fuck slack
fname := filepath.Join(*path, f.ID+f.Name) fname := filepath.Join(*path, f.ID+f.Name)
log.Printf("Downloading from: %s", url) log.Info().
Str("url", url).
Msg("Downloading")
client := &http.Client{} client := &http.Client{}
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
@ -96,18 +107,20 @@ func downloadFile(f slackFile) {
defer out.Close() defer out.Close()
io.Copy(out, resp.Body) io.Copy(out, resp.Body)
log.Printf("Downloaded %s", f.ID) log.Info().
Str("id", f.ID).
Msg("Downloaded")
} }
func checkErr(err error) { func checkErr(err error) {
if err != nil { if err != nil {
log.Fatal(err) log.Fatal().Err(err)
} }
} }
func mkReq(path string, arg ...string) []byte { func mkReq(path string, arg ...string) []byte {
if len(arg)%2 != 0 { if len(arg)%2 != 0 {
log.Fatal("Bad request arg number.") log.Fatal().Msg("Bad request arg number.")
} }
u, err := url.Parse(path) u, err := url.Parse(path)