nunbot/main.go
2022-08-03 15:44:59 -04:00

125 lines
2.7 KiB
Go

package main
import (
"log"
"os"
"os/signal"
"strconv"
"sync"
mbl "git.saintnet.tech/stryan/matrixbotlib"
"maunium.net/go/mautrix"
"maunium.net/go/mautrix/event"
)
//GitTag is current git tag
var GitTag string
//GitCommit is current git commit
var GitCommit string
func main() {
conf, err := mbl.LoadMatrixClientConfig("config.yaml")
if err != nil {
conf, err = mbl.LoadMatrixClientConfig("/etc/nunbot/config.yaml")
if err != nil {
panic(err)
}
}
dataFilter := &mautrix.Filter{
AccountData: mautrix.FilterPart{
Limit: 20,
NotTypes: []event.Type{
event.NewEventType("nun.batch"),
},
},
}
matrixClient, err := mbl.NewMatrixClient(conf, nil)
if err != nil {
panic(err)
}
store := mautrix.NewAccountDataStore("nun.batch", matrixClient)
_, err = matrixClient.CreateFilter(dataFilter)
if err != nil {
//don't want to continue if we can't keep state
panic(err)
}
var nun *nunWatch
matrixClient.Store = store
syncer := matrixClient.Syncer.(*mautrix.DefaultSyncer)
mbl.AcceptAllRoomInvites(matrixClient)
syncer.OnEventType(event.EventMessage, func(source mautrix.EventSource, evt *event.Event) {
if evt.Sender == matrixClient.UserID {
return //ignore events from self
}
cmd, err := mbl.ParseCommand(evt, "nun")
if err != nil {
if err != mbl.ErrCmdParseNoPrefix {
log.Printf("invalid command: %v", err)
}
return
}
switch cmd[0] {
case "version":
// print version
if GitTag != "" {
matrixClient.SendText(evt.RoomID, "NunBot version "+GitTag)
} else {
matrixClient.SendText(evt.RoomID, "NunBot version "+GitCommit)
}
case "timer":
if len(cmd) <= 1 {
matrixClient.SendText(evt.RoomID, "!nun timer [time in minutes to wait between tries]")
return
}
time, err := strconv.Atoi(cmd[1])
if err != nil {
matrixClient.SendText(evt.RoomID, "!nun timer needs integer timer")
return
}
nun.SetTimer(time)
matrixClient.SendText(evt.RoomID, "timer set")
case "help":
matrixClient.SendText(evt.RoomID, "Supported commands: version, help,timer")
default:
//command not found
matrixClient.SendText(evt.RoomID, "command not recognized")
}
})
var wg sync.WaitGroup
stop := make(chan bool)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
log.Println("trying to shutdown cleanly")
matrixClient.StopSync()
stop <- true
}()
nun = newNunWatch(stop, matrixClient, 2)
wg.Add(1)
go func() {
err = matrixClient.Sync()
if err != nil {
log.Println(err)
}
wg.Done()
log.Println("matrix client shutdown")
}()
wg.Add(1)
go func() {
nun.Main()
wg.Done()
log.Println("nun watch shutdown")
}()
log.Println("nunbot running")
wg.Wait()
log.Println("shutting down")
}