ccchatbot/main.go

93 lines
2.1 KiB
Go
Raw Normal View History

2019-08-06 13:31:58 -05:00
package main
import (
"flag"
"os"
"os/signal"
"syscall"
"dev.sum7.eu/genofire/golang-lib/file"
"github.com/bdlm/log"
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
2019-08-07 05:27:18 -05:00
"dev.sum7.eu/ccchb/ccchatbot/mqtt"
2019-08-06 13:31:58 -05:00
"dev.sum7.eu/ccchb/ccchatbot/runtime"
)
var config = Config{}
func main() {
configFile := "config.toml"
flag.StringVar(&configFile, "config", configFile, "path of configuration file")
flag.Parse()
if err := file.ReadTOML(configFile, &config); err != nil {
log.WithField("tip", "maybe call me with: ccchatbot --config /etc/ccchatbot.conf").Panicf("error on read config: %s", err)
}
log.SetLevel(config.LogLevel)
2019-08-07 05:27:18 -05:00
var mqttService *mqtt.Service
if config.MQTT != nil {
mqttService = mqtt.Connect(config.MQTT)
}
2019-08-06 13:31:58 -05:00
router := xmpp.NewRouter()
router.HandleFunc("presence", handlePresence)
router.HandleFunc("message", func(s xmpp.Sender, p stanza.Packet) {
msg, ok := p.(stanza.Message)
if !ok {
log.Errorf("ignoring wrong routed packet: %T", p)
return
}
2019-08-07 05:27:18 -05:00
if ok := config.Schalter.HandleBotMessage(s, msg); ok {
return
}
if mqttService != nil {
if ok := mqttService.HandleBotMessage(s, msg); ok {
return
}
2019-08-06 13:31:58 -05:00
}
2019-08-07 05:27:18 -05:00
log.Debugf("no bot has handle message of %s: %s", msg.From, msg.Body)
2019-08-06 13:31:58 -05:00
})
var err error
client, err := xmpp.NewClient(xmpp.Config{
Address: config.XMPP.Host,
Jid: config.XMPP.JID,
Password: config.XMPP.Password,
}, router)
2019-08-07 05:27:18 -05:00
config.Schalter.ChangeEvent = append(config.Schalter.ChangeEvent, config.Schalter.XMPPChangeEvent(client))
if mqttService != nil {
config.Schalter.ChangeEvent = append(config.Schalter.ChangeEvent, mqttService.HandleSchalterStateChange)
}
2019-08-06 13:31:58 -05:00
if err != nil {
log.Panicf("error on startup xmpp client: %s", err)
}
cm := xmpp.NewStreamManager(client, func(s xmpp.Sender) {
2019-08-06 17:08:11 -05:00
config.Schalter.Start(s)
2019-08-06 13:31:58 -05:00
})
go func() {
err := cm.Run()
log.Panic("closed connection:", err)
}()
// Wait for system signal
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigs
2019-08-07 05:27:18 -05:00
if mqttService != nil {
mqttService.Close()
}
2019-08-06 17:08:11 -05:00
config.Schalter.Close()
2019-08-06 13:31:58 -05:00
runtime.LeaveAllMUCs(client)
log.Infof("closed by receiving: %s", sig)
}