vyvanse/cmd/logworker/main.go

90 lines
2.2 KiB
Go

package main
import (
"context"
"encoding/json"
"git.xeserv.us/xena/gorqlite"
"git.xeserv.us/xena/vyvanse/internal/dao"
"github.com/Xe/ln"
"github.com/bwmarrin/discordgo"
"github.com/drone/mq/stomp"
"github.com/namsral/flag"
opentracing "github.com/opentracing/opentracing-go"
zipkin "github.com/openzipkin/zipkin-go-opentracing"
)
var (
token = flag.String("token", "", "discord bot token")
zipkinURL = flag.String("zipkin-url", "", "URL for Zipkin traces")
databaseURL = flag.String("database-url", "http://", "URL for database (rqlite)")
mqURL = flag.String("mq-url", "tcp://mq:9000", "URL for STOMP server")
)
func main() {
flag.Parse()
if *zipkinURL != "" {
collector, err := zipkin.NewHTTPCollector(*zipkinURL)
if err != nil {
ln.FatalErr(context.Background(), err)
}
tracer, err := zipkin.NewTracer(
zipkin.NewRecorder(collector, false, "logworker:5000", "logworker"))
if err != nil {
ln.FatalErr(context.Background(), err)
}
opentracing.SetGlobalTracer(tracer)
}
ctx := context.Background()
db, err := gorqlite.Open(*databaseURL)
if err != nil {
ln.FatalErr(ctx, err)
}
ls := dao.NewLogs(db)
err = ls.Migrate(ctx)
if err != nil {
ln.FatalErr(ctx, err, ln.F{"action": "migrate logs table"})
}
mq, err := stomp.Dial(*mqURL)
if err != nil {
ln.FatalErr(ctx, err, ln.F{"url": *mqURL})
}
mq.Subscribe("/topic/message_create", stomp.HandlerFunc(func(m *stomp.Message) {
sp, ctx := opentracing.StartSpanFromContext(m.Context(), "logworker.topic.message.create")
defer sp.Finish()
msg := &discordgo.Message{}
err := json.Unmarshal(m.Msg, msg)
if err != nil {
ln.Error(ctx, err, ln.F{"action": "can't unmarshal message body to a discordgo message"})
return
}
f := ln.F{
"stomp_id": string(m.ID),
"channel_id": msg.ChannelID,
"message_id": msg.ID,
"message_author": msg.Author.ID,
"message_author_name": msg.Author.Username,
"message_author_is_bot": msg.Author.Bot,
}
err = ls.Add(ctx, msg)
if err != nil {
ln.Error(ctx, err, f, ln.F{"action": "can't add discordgo message to the database"})
}
}))
for {
select {}
}
}