statbot/statbot.go

108 lines
2.7 KiB
Go

package main
import (
"encoding/json"
"fmt"
"log"
"os"
"time"
)
const programName = "statbot"
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: statbot slack-bot-token\n")
os.Exit(1)
}
writeToLog("\n\n\n== " + time.Now().Format(time.RFC3339) + " ==\n")
// start a websocket-based Real Time API session
var slack *Slack
var err error
if err = initDatabase(); err != nil {
panic(err)
}
if slack, err = CreateSlack(os.Args[1]); err != nil {
panic(err)
}
fmt.Println("statbot ready, ^C exits")
for {
// read each incoming message
m, err := slack.getMessage()
if err != nil {
log.Fatal(err)
}
processMessage(slack, &m)
}
}
func processMessage(slack *Slack, m *Message) {
if mb, me := json.Marshal(m); me == nil {
// Write the JSON representation to the log
writeToLog(string(mb) + "\n")
}
// TODO: Handle reaction_added messages
// TODO: Handle reaction_removed messages
if m.Type == "message" {
// Check if we know who the user is
usr, err := getUserInfo(m.User)
// If the user information hasn't been updated in the past day, update it.
if err != nil || usr.LastUpdated.IsZero() || time.Since(usr.LastUpdated) > (time.Hour*24) {
if u, ue := slack.getUserInfo(m.User); ue == nil {
saveUserInfo(u)
}
}
// If 'channel' is defined, save the message to the 'channels' bucket
if m.Channel != "" {
// Check if we know what the channel is
chnl, err := getChannelInfo(m.Channel)
// If the channel information hasn't been updated in the past day, update it.
if err != nil || chnl.LastUpdated.IsZero() || time.Since(chnl.LastUpdated) > (time.Hour*24) {
// Either we don't have this channel, or it's a direct message
if c, ce := slack.getChannelInfo(m.Channel); ce != nil {
// Invalid channel, save as a direct message
saveUserMessage(m.User, m)
} else {
// Save channel info
saveChannelInfo(c)
// And save the channel message
saveChannelMessage(m.Channel, m)
}
}
}
// check if we're mentioned
/*
if m.Type == "message" && strings.HasPrefix(m.Text, "<@"+slack.id+">") {
parts := strings.Fields(m.Text)
if len(parts) == 3 && parts[1] == "stock" {
// looks good, get the quote and reply with the result
go func(m Message) {
m.Text = getQuote(parts[2])
postMessage(ws, m)
}(m)
// NOTE: the Message object is copied, this is intentional
} else {
// huh?
m.Text = fmt.Sprintf("Beep boop beep, that does not compute\n")
postMessage(ws, m)
}
}
*/
}
}
func writeToLog(d string) {
f, err := os.OpenFile("statbot.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0664)
if err != nil {
panic(err)
}
f.WriteString(d)
f.Close()
}