ccchatbot/mqtt/bot.go

70 lines
1.8 KiB
Go

package mqtt
import (
"fmt"
"github.com/mattn/go-shellwords"
"gosrc.io/xmpp"
"gosrc.io/xmpp/stanza"
)
var botCommands map[string]func(*Service, xmpp.Sender, stanza.Attrs, []string) bool
func (s *Service) HandleBotMessage(c xmpp.Sender, msg stanza.Message) bool {
msgParts, err := shellwords.Parse(msg.Body)
if err != nil {
return false
}
if len(msgParts) <= 0 || msgParts[0][0] != '.' {
return false
}
command := msgParts[0][1:]
if f, ok := botCommands[command]; ok {
attrs := stanza.Attrs{To: msg.From, Type: msg.Type}
if msg.Type == stanza.MessageTypeGroupchat {
jid, _ := xmpp.NewJid(msg.From)
attrs.To = jid.Bare()
}
return f(s, c, attrs, msgParts[1:])
}
return false
}
func init() {
botCommands = make(map[string]func(*Service, xmpp.Sender, stanza.Attrs, []string) bool)
botCommands["sub"] = func(s *Service, c xmpp.Sender, replyAttrs stanza.Attrs, leftCommands []string) bool {
c.Send(stanza.Message{
Attrs: replyAttrs,
Body: "not supported yet:\n.sub <topic>",
})
return true
}
botCommands["unsub"] = func(s *Service, c xmpp.Sender, replyAttrs stanza.Attrs, leftCommands []string) bool {
c.Send(stanza.Message{
Attrs: replyAttrs,
Body: "not supported yet:\n.unsub <topic>",
})
return true
}
botCommands["pub"] = func(s *Service, c xmpp.Sender, replyAttrs stanza.Attrs, leftCommands []string) bool {
if len(leftCommands) != 2 {
c.Send(stanza.Message{
Attrs: replyAttrs,
Body: "wrong arguments: need format:\n.pub <topic> <payload>",
})
return true
}
topic := leftCommands[0]
payload := leftCommands[1]
token := s.client.Publish(topic, 0, false, payload)
token.Wait()
c.Send(stanza.Message{
Attrs: replyAttrs,
Body: fmt.Sprintf("published in %s : %s", topic, payload),
})
return true
}
}