-
Notifications
You must be signed in to change notification settings - Fork 87
/
message.go
448 lines (401 loc) · 10.4 KB
/
message.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package user
import (
"errors"
"fmt"
"regexp"
"sort"
"strings"
"time"
"github.com/wechaty/go-wechaty/wechaty-puppet/filebox"
"github.com/wechaty/go-wechaty/wechaty-puppet/helper"
"github.com/wechaty/go-wechaty/wechaty-puppet/schemas"
"github.com/wechaty/go-wechaty/wechaty/config"
_interface "github.com/wechaty/go-wechaty/wechaty/interface"
)
type Message struct {
_interface.IAccessory
id string
payload *schemas.MessagePayload
}
// NewMessage ...
func NewMessage(id string, accessory _interface.IAccessory) _interface.IMessage {
return &Message{
IAccessory: accessory,
id: id,
}
}
func (m *Message) Ready() (err error) {
if m.IsReady() {
return nil
}
m.payload, err = m.GetPuppet().MessagePayload(m.id)
if err != nil {
return err
}
talkerId := m.payload.TalkerId
roomId := m.payload.RoomId
listenerId := m.payload.ListenerId
if roomId != "" {
if err := m.GetWechaty().Room().Load(roomId).Ready(false); err != nil {
return err
}
}
if talkerId != "" {
if err := m.GetWechaty().Contact().Load(talkerId).Ready(false); err != nil {
return err
}
}
if listenerId != "" {
if err := m.GetWechaty().Contact().Load(listenerId).Ready(false); err != nil {
return err
}
}
return nil
}
func (m *Message) IsReady() bool {
return m.payload != nil
}
// String() message to print string
func (m *Message) String() string {
talkerStr := ""
roomStr := ""
talker := m.Talker()
if talker != nil {
talkerStr = "🗣" + talker.String()
}
room := m.Room()
if room != nil {
roomStr = "@👥'" + room.String()
}
str := fmt.Sprintf("Message#%s[%s%s]", m.Type(), talkerStr, roomStr)
switch m.Type() {
case schemas.MessageTypeText, schemas.MessageTypeUnknown:
r := []rune(m.Text())
if len(r) > 70 {
r = r[0:70]
}
str += "\t" + string(r)
}
return str
}
// Room get the room from the message.
func (m *Message) Room() _interface.IRoom {
roomId := m.payload.RoomId
if roomId == "" {
return nil
}
return m.GetWechaty().Room().Load(roomId)
}
// Type get the type from the message.
func (m *Message) Type() schemas.MessageType {
return m.payload.Type
}
// From get the sender from a message
// Deprecated: please use Talker()
func (m *Message) From() _interface.IContact {
return m.Talker()
}
// Talker Get the talker of a message.
func (m *Message) Talker() _interface.IContact {
if m.payload.TalkerId == "" {
return nil
}
return m.GetWechaty().Contact().Load(m.payload.TalkerId)
}
// Text get the text content of the message
func (m *Message) Text() string {
return m.payload.Text
}
// Self check if a message is sent by self
func (m *Message) Self() bool {
userID := m.GetPuppet().SelfID()
talker := m.Talker()
//TODO talker 为 nil 的情况,群公告消息
if talker == nil {
return false
}
return userID == talker.ID()
}
func (m *Message) Age() time.Duration {
return time.Since(m.Date())
}
// Date sent date
func (m *Message) Date() time.Time {
return m.payload.Timestamp
}
// Say reply a Text or Media File message to the sender.
// Support msg:
// string
// Contact
// filebox.FileBox
// UrlLink
// MiniProgram
// Location
func (m *Message) Say(sayable interface{}) (_interface.IMessage, error) {
conversationId, err := m.sayId()
if err != nil {
return nil, err
}
var messageID string
switch v := sayable.(type) {
case string:
messageID, err = m.GetPuppet().MessageSendText(conversationId, v)
case *Contact:
messageID, err = m.GetPuppet().MessageSendContact(conversationId, v.Id)
case *filebox.FileBox:
messageID, err = m.GetPuppet().MessageSendFile(conversationId, v)
case *UrlLink:
messageID, err = m.GetPuppet().MessageSendURL(conversationId, v.payload)
case *MiniProgram:
messageID, err = m.GetPuppet().MessageSendMiniProgram(conversationId, v.payload)
case *Location:
messageID, err = m.GetPuppet().MessageSendLocation(conversationId, v.payload)
default:
return nil, fmt.Errorf("unknown msg: %v", sayable)
}
if err != nil {
return nil, err
}
if messageID == "" {
return nil, nil
}
message := m.GetWechaty().Message().Load(messageID)
if err := message.Ready(); err != nil {
return nil, err
}
return message, nil
}
func (m *Message) sayId() (string, error) {
room := m.Room()
if room != nil {
return room.ID(), nil
}
talker := m.Talker()
if talker != nil {
return talker.ID(), nil
}
return "", errors.New("neither room nor talker? ")
}
// To get the destination of the message
// Deprecated: please use Listener()
func (m *Message) To() _interface.IContact {
return m.Listener()
}
/*
Listener Get the destination of the message.
listener() will return nil if a message is in a room
use Room() to get the room.
*/
func (m *Message) Listener() _interface.IContact {
if m.payload.ListenerId == "" {
return nil
}
return m.GetWechaty().Contact().Load(m.payload.ListenerId)
}
// ToRecalled get the recalled message
func (m *Message) ToRecalled() (_interface.IMessage, error) {
if m.Type() != schemas.MessageTypeRecalled {
return nil, errors.New("can not call toRecalled() on message which is not recalled type")
}
originalMessageId := m.Text()
if originalMessageId == "" {
return nil, errors.New("can not find recalled message")
}
message := m.GetWechaty().Message().Load(originalMessageId)
err := message.Ready()
if err != nil {
return nil, err
}
return message, nil
}
// Recall recall a message
func (m *Message) Recall() (bool, error) {
recall, err := m.GetPuppet().MessageRecall(m.id)
if err != nil {
return false, err
}
return recall, nil
}
// MentionList get message mentioned contactList.
func (m *Message) MentionList() []_interface.IContact {
room := m.Room()
if m.Type() != schemas.MessageTypeText || room == nil {
return nil
}
var contactList []_interface.IContact
if len(m.payload.MentionIdList) > 0 {
async := helper.NewAsync(helper.DefaultWorkerNum)
for _, id := range m.payload.MentionIdList {
id := id
async.AddTask(func() (interface{}, error) {
contact := m.GetWechaty().Contact().Load(id)
return contact, contact.Ready(false)
})
}
for _, v := range async.Result() {
if v.Err != nil {
continue
}
contactList = append(contactList, v.Value.(_interface.IContact))
}
return contactList
}
atList := config.AtSeparatorRegex.Split(m.Text(), -1)
if len(atList) == 0 {
return nil
}
var mentionNameList []string
for _, v := range atList {
if !strings.Contains(v, "@") {
continue
}
for _, v := range m.multipleAt(v) {
if v == "" {
continue
}
mentionNameList = append(mentionNameList, v)
}
}
async := helper.NewAsync(helper.DefaultWorkerNum)
for _, name := range mentionNameList {
name := name
async.AddTask(func() (interface{}, error) {
return room.MemberAll(name)
})
}
for _, v := range async.Result() {
if v.Err != nil {
continue
}
contactList = append(contactList, v.Value.([]_interface.IContact)...)
}
return contactList
}
// convert 'hello@a@b@c' to [ 'c', 'b@c', 'a@b@c' ]
func (m *Message) multipleAt(str string) []string {
r, _ := regexp.Compile("^.*?@")
strs := strings.Split(r.ReplaceAllString(str, "@"), "@")
var name string
var nameList []string
var filterStrs []string
for _, mentionName := range strs {
if mentionName == "" {
continue
}
filterStrs = append(filterStrs, mentionName)
}
//reverse
sort.Slice(filterStrs, func(i, j int) bool {
return filterStrs[i] > filterStrs[j]
})
for _, mentionName := range filterStrs {
name = mentionName + "@" + name
r := []rune(name)
nameList = append(nameList, string(r[0:len(r)-1]))
}
return nameList
}
func (m *Message) MentionText() string {
text := m.Text()
room := m.Room()
mentionList := m.MentionList()
if room == nil || len(mentionList) == 0 {
return text
}
toAliasName := func(member _interface.IContact) string {
alias, _ := room.Alias(member)
if alias != "" {
return alias
}
return member.Name()
}
var mentionNameList []string
for _, v := range mentionList {
mentionNameList = append(mentionNameList, toAliasName(v))
}
for _, v := range mentionNameList {
reg := regexp.MustCompile("@" + regexp.QuoteMeta(v) + "(\u2005|\u0020|$)")
text = reg.ReplaceAllString(text, "")
}
return strings.TrimSpace(text)
}
func (m *Message) MentionSelf() bool {
selfID := m.GetPuppet().SelfID()
mentionList := m.MentionList()
for _, v := range mentionList {
if v.ID() == selfID {
return true
}
}
return false
}
// Forward Forward the received message.
func (m *Message) Forward(contactOrRoomId string) error {
_, err := m.GetPuppet().MessageForward(contactOrRoomId, m.id)
return err
}
// ToFileBox extract the Media File from the Message, and put it into the FileBox.
func (m *Message) ToFileBox() (*filebox.FileBox, error) {
if m.Type() == schemas.MessageTypeText {
return nil, errors.New("text message no file")
}
return m.GetPuppet().MessageFile(m.id)
}
// ToImage extract the Image File from the Message, so that we can use different image sizes.
func (m *Message) ToImage() (_interface.IImage, error) {
if m.Type() != schemas.MessageTypeImage {
return nil, errors.New("not a image type message")
}
return m.GetWechaty().Image().Create(m.id), nil
}
// ToContact Get Share Card of the Message
// Extract the Contact Card from the Message, and encapsulate it into Contact class
func (m *Message) ToContact() (_interface.IContact, error) {
if m.Type() != schemas.MessageTypeContact {
return nil, errors.New("message not a ShareCard")
}
contactID, err := m.GetPuppet().MessageContact(m.id)
if err != nil {
return nil, err
}
contact := m.GetWechaty().Contact().Load(contactID)
err = contact.Ready(false)
if err != nil {
return nil, err
}
return contact, nil
}
func (m *Message) ToUrlLink() (*UrlLink, error) {
if m.Type() != schemas.MessageTypeURL {
return nil, errors.New("message not a Url Link")
}
urlPayload, err := m.GetPuppet().MessageURL(m.id)
if err != nil {
return nil, err
}
return NewUrlLink(urlPayload), nil
}
func (m *Message) ToMiniProgram() (*MiniProgram, error) {
if m.Type() != schemas.MessageTypeMiniProgram {
return nil, errors.New("message not a MiniProgram")
}
miniProgramPayload, err := m.GetPuppet().MessageMiniProgram(m.id)
if err != nil {
return nil, err
}
return NewMiniProgram(miniProgramPayload), nil
}
func (m *Message) ToLocation() (*Location, error) {
if m.Type() != schemas.MessageTypeLocation {
return nil, errors.New("message not a Location")
}
payload, err := m.GetPuppet().MessageLocation(m.id)
if err != nil {
return nil, err
}
return NewLocation(payload), nil
}
// ID message id
func (m *Message) ID() string {
return m.id
}