package bot import ( log "github.com/sirupsen/logrus" "dev.sum7.eu/genofire/yaja/client" "dev.sum7.eu/genofire/yaja/xmpp" "dev.sum7.eu/genofire/yaja/xmpp/base" ) type Bot struct { AutoSubscribe bool Logging *log.Entry Handlers []Handler client *client.Client jid *xmppbase.JID password string } func NewBot(jid *xmppbase.JID, password string) *Bot { bot := Bot{ jid: jid, password: password, Logging: log.WithField("jid", jid.String()), } bot.Handlers = append(bot.Handlers, &SubscribeHander{Disabled: &bot.AutoSubscribe}) return &bot } func (bot *Bot) Start() { if bot.client == nil { bot.client = &client.Client{ JID: bot.jid, Logging: bot.Logging, } if bot.client.Connect(bot.password) != nil { bot.Logging.Fatal("was not able to connect") } go func() { if err := bot.client.Start(); err != nil { bot.Logging.Fatal("was not able to reconnect") } }() } bot.run() } func (bot *Bot) run() { for { element, more := bot.client.Recv() if !more { bot.Logging.Info("could not recv msg, closed") return } handled := false switch element.(type) { case *xmpp.PresenceClient: pres := element.(*xmpp.PresenceClient) for _, f := range bot.Handlers { if f.Presence(bot, pres) { handled = true break } } case *xmpp.MessageClient: msg := element.(*xmpp.MessageClient) for _, f := range bot.Handlers { if f.Message(bot, msg) { handled = true break } } case *xmpp.IQClient: iq := element.(*xmpp.IQClient) for _, f := range bot.Handlers { if f.IQ(bot, iq) { handled = true break } } } if handled { bot.Logging.Debugf("recv handled: %v", element) } else { bot.Logging.Infof("recv unhandled: %v", element) } } }