maubot/matrix/event.go

99 lines
2.7 KiB
Go
Raw Normal View History

2018-06-13 22:41:05 +00:00
// maubot - A plugin-based Matrix bot system written in Go.
// Copyright (C) 2018 Tulir Asokan
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package matrix
import (
"encoding/json"
"maubot.xyz"
2018-06-13 22:41:05 +00:00
"maunium.net/go/gomatrix"
)
type Event struct {
*maubot.Event
2018-06-13 22:41:05 +00:00
Client *Client
}
func roundtripContent(rawContent map[string]interface{}) (content maubot.Content) {
if len(rawContent) == 0 {
content.Raw = rawContent
return
}
data, _ := json.Marshal(&rawContent)
json.Unmarshal(data, &content)
content.Raw = rawContent
return
}
func (client *Client) ParseEvent(mxEvent *gomatrix.Event) *Event {
var stateKey string
if mxEvent.StateKey != nil {
stateKey = *mxEvent.StateKey
}
event := &Event{
Client: client,
}
mbEvent := &maubot.Event{
EventFuncs: event,
StateKey: stateKey,
Sender: mxEvent.Sender,
Type: maubot.EventType(mxEvent.Type),
Timestamp: mxEvent.Timestamp,
ID: mxEvent.ID,
RoomID: mxEvent.RoomID,
Content: roundtripContent(mxEvent.Content),
Redacts: mxEvent.Redacts,
Unsigned: maubot.Unsigned{
PrevContent: roundtripContent(mxEvent.Unsigned.PrevContent),
PrevSender: mxEvent.Unsigned.PrevSender,
ReplacesState: mxEvent.Unsigned.ReplacesState,
Age: mxEvent.Unsigned.Age,
},
}
RemoveReplyFallback(mbEvent)
event.Event = mbEvent
return event
}
2018-06-14 10:36:53 +00:00
func (evt *Event) MarkRead() error {
return evt.Client.MarkRead(evt.RoomID, evt.ID)
}
2018-06-13 22:41:05 +00:00
func (evt *Event) Reply(text string) (string, error) {
return evt.ReplyContent(RenderMarkdown(text))
2018-06-13 22:41:05 +00:00
}
func (evt *Event) ReplyContent(content maubot.Content) (string, error) {
return evt.SendContent(SetReply(content, evt))
}
2018-06-13 22:41:05 +00:00
func (evt *Event) SendMessage(text string) (string, error) {
return evt.SendContent(RenderMarkdown(text))
}
func (evt *Event) SendContent(content maubot.Content) (string, error) {
return evt.SendRawEvent(maubot.EventMessage, content)
2018-06-13 22:41:05 +00:00
}
func (evt *Event) SendRawEvent(evtType maubot.EventType, content interface{}) (string, error) {
resp, err := evt.Client.SendMessageEvent(evt.RoomID, string(evtType), content)
2018-06-13 22:41:05 +00:00
if err != nil {
return "", err
}
return resp.EventID, nil
}