Files
signalbot/message.go
T
2026-11-20 15:41:31 +01:00

85 lines
2.1 KiB
Go

package signalbot
import (
"context"
"encoding/base64"
"encoding/json"
"time"
)
// Message is an incoming text message.
type Message struct {
// From is the sender's phone number, or its ACI UUID when the number is
// not shared.
From string
// GroupID is the group the message was posted in ("group.<base64>", same
// format as Groups and Send), or "" for a direct message.
GroupID string
Text string
Timestamp time.Time
client *Client
}
// Reply sends text to the conversation the message came from: the group
// if GroupID is set, the sender otherwise.
func (m Message) Reply(ctx context.Context, text string) error {
to := m.GroupID
if to == "" {
to = m.From
}
return m.client.Send(ctx, to, text)
}
// envelope is the subset of a signal-cli "receive" notification we use.
type envelope struct {
Envelope struct {
SourceNumber *string `json:"sourceNumber"`
SourceUUID string `json:"sourceUuid"`
Timestamp int64 `json:"timestamp"`
DataMessage *struct {
Message *string `json:"message"`
GroupInfo *struct {
GroupID string `json:"groupId"`
} `json:"groupInfo"`
} `json:"dataMessage"`
} `json:"envelope"`
}
// parseEnvelope extracts a text message from a websocket frame. It reports
// false for anything that is not a non-empty text message from someone else.
// The returned Message has no client set.
func parseEnvelope(data []byte, self Account) (Message, bool) {
var e envelope
if json.Unmarshal(data, &e) != nil {
return Message{}, false
}
env := e.Envelope
dm := env.DataMessage
if dm == nil || dm.Message == nil || *dm.Message == "" {
return Message{}, false
}
var number string
if env.SourceNumber != nil {
number = *env.SourceNumber
}
if isSelf(self, []string{number, env.SourceUUID}) {
return Message{}, false
}
m := Message{
From: number,
Text: *dm.Message,
Timestamp: time.UnixMilli(env.Timestamp),
}
if m.From == "" {
m.From = env.SourceUUID
}
if m.From == "" {
return Message{}, false
}
if dm.GroupInfo != nil && dm.GroupInfo.GroupID != "" {
m.GroupID = "group." + base64.StdEncoding.EncodeToString([]byte(dm.GroupInfo.GroupID))
}
return m, true
}