forked from andersfylling/disgord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
587 lines (505 loc) · 18.9 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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
package disgord
import (
"context"
"errors"
"fmt"
"github.com/andersfylling/disgord/internal/endpoint"
"github.com/andersfylling/disgord/internal/httd"
)
// different message activity types
const (
_ = iota
MessageActivityTypeJoin
MessageActivityTypeSpectate
MessageActivityTypeListen
MessageActivityTypeJoinRequest
)
// MessageFlag https://discord.com/developers/docs/resources/channel#message-object-message-flags
type MessageFlag uint
const (
MessageFlagCrossposted MessageFlag = 1 << iota
MessageFlagIsCrosspost
MessageFlagSupressEmbeds
MessageFlagSourceMessageDeleted
MessageFlagUrgent
)
// The different message types usually generated by Discord. eg. "a new user joined"
type MessageType uint // TODO: once auto generated, un-export this.
const (
MessageTypeDefault MessageType = iota
MessageTypeRecipientAdd
MessageTypeRecipientRemove
MessageTypeCall
MessageTypeChannelNameChange
MessageTypeChannelIconChange
MessageTypeChannelPinnedMessage
MessageTypeGuildMemberJoin
MessageTypeUserPremiumGuildSubscription
MessageTypeUserPremiumGuildSubscriptionTier1
MessageTypeUserPremiumGuildSubscriptionTier2
MessageTypeUserPremiumGuildSubscriptionTier3
MessageTypeChannelFollowAdd
_
MessageTypeGuildDiscoveryDisqualified
MessageTypeGuildDiscoveryRequalified
_
_
_
MessageTypeReply
MessageTypeApplicationCommand
)
const (
AttachmentSpoilerPrefix = "SPOILER_"
)
// MessageActivity https://discord.com/developers/docs/resources/channel#message-object-message-activity-structure
type MessageActivity struct {
Type int `json:"type"`
PartyID string `json:"party_id"`
}
type MentionChannel struct {
ID Snowflake `json:"id"`
GuildID Snowflake `json:"guild_id"`
Type ChannelType `json:"type"`
Name string `json:"name"`
}
var _ Copier = (*MentionChannel)(nil)
var _ DeepCopier = (*MentionChannel)(nil)
type MessageReference struct {
MessageID Snowflake `json:"message_id"`
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
}
type MessageComponentType = int
const (
_ MessageComponentType = iota
MessageComponentActionRow
MessageComponentButton
)
type ButtonStyle = int
const (
_ ButtonStyle = iota
Primary
Secondary
Success
Danger
Link
)
type MessageComponent struct {
Type MessageComponentType `json:"type"`
Style ButtonStyle `json:"style"`
Label string `json:"label"`
Emoji *Emoji `json:"emoji"`
CustomID string `json:"custom_id"`
Url string `json:"url"`
Disabled bool `json:"disabled"`
Components []*MessageComponent `json:"components"`
}
var _ Copier = (*MessageComponent)(nil)
var _ DeepCopier = (*MessageComponent)(nil)
// MessageApplication https://discord.com/developers/docs/resources/channel#message-object-message-application-structure
type MessageApplication struct {
ID Snowflake `json:"id"`
CoverImage string `json:"cover_image"`
Description string `json:"description"`
Icon string `json:"icon"`
Name string `json:"name"`
}
type MessageStickerFormatType int
const (
_ MessageStickerFormatType = iota
MessageStickerFormatPNG
MessageStickerFormatAPNG
MessageStickerFormatLOTTIE
)
type MessageSticker struct {
ID Snowflake `json:"id"`
PackID Snowflake `json:"pack_id"`
Name string `json:"name"`
Description string `json:"description"`
Tags string `json:"tags"`
Asset string `json:"asset"`
PreviewAsset string `json:"preview_asset"`
FormatType MessageStickerFormatType `json:"format_type"`
}
var _ Copier = (*MessageSticker)(nil)
var _ DeepCopier = (*MessageSticker)(nil)
// Message https://discord.com/developers/docs/resources/channel#message-object-message-structure
type Message struct {
ID Snowflake `json:"id"`
ChannelID Snowflake `json:"channel_id"`
GuildID Snowflake `json:"guild_id"`
Author *User `json:"author"`
Member *Member `json:"member"`
Content string `json:"content"`
Timestamp Time `json:"timestamp"`
EditedTimestamp Time `json:"edited_timestamp"` // ?
Tts bool `json:"tts"`
MentionEveryone bool `json:"mention_everyone"`
Mentions []*User `json:"mentions"`
MentionRoles []Snowflake `json:"mention_roles"`
MentionChannels []*MentionChannel `json:"mention_channels"`
Attachments []*Attachment `json:"attachments"`
Embeds []*Embed `json:"embeds"`
Reactions []*Reaction `json:"reactions"` // ?
Nonce interface{} `json:"nonce"` // NOT A SNOWFLAKE! DONT TOUCH!
Pinned bool `json:"pinned"`
WebhookID Snowflake `json:"webhook_id"` // ?
Type MessageType `json:"type"`
Activity MessageActivity `json:"activity"`
Application MessageApplication `json:"application"`
MessageReference *MessageReference `json:"message_reference"`
ReferencedMessage *Message `json:"referenced_message"`
Flags MessageFlag `json:"flags"`
Stickers []*MessageSticker `json:"stickers"`
Components []*MessageComponent `json:"components"`
Interaction *MessageInteraction `json:"interaction"`
// SpoilerTagContent is only true if the entire message text is tagged as a spoiler (aka completely wrapped in ||)
SpoilerTagContent bool `json:"-"`
SpoilerTagAllAttachments bool `json:"-"`
HasSpoilerImage bool `json:"-"`
}
var _ Reseter = (*Message)(nil)
var _ fmt.Stringer = (*Message)(nil)
var _ internalUpdater = (*Message)(nil)
var _ Copier = (*Message)(nil)
var _ DeepCopier = (*Message)(nil)
func (m *Message) String() string {
return "message{" + m.ID.String() + "}"
}
// DiscordURL returns the Discord link to the message. This can be used to jump
// directly to a message from within the client.
//
// Example: https://discord.com/channels/319567980491046913/644376487331495967/646925626523254795
func (m *Message) DiscordURL() (string, error) {
if m.ID.IsZero() {
return "", errors.New("missing message ID")
}
if m.GuildID.IsZero() {
return "", errors.New("missing guild ID")
}
if m.ChannelID.IsZero() {
return "", errors.New("missing channel ID")
}
return fmt.Sprintf(
"https://discord.com/channels/%d/%d/%d",
m.GuildID, m.ChannelID, m.ID,
), nil
}
func (m *Message) updateInternals() {
if len(m.Content) >= len("||||") {
prefix := m.Content[0:2]
suffix := m.Content[len(m.Content)-2 : len(m.Content)]
m.SpoilerTagContent = prefix+suffix == "||||"
}
m.SpoilerTagAllAttachments = len(m.Attachments) > 0
for i := range m.Attachments {
m.Attachments[i].updateInternals()
if !m.Attachments[i].SpoilerTag {
m.SpoilerTagAllAttachments = false
break
} else {
m.HasSpoilerImage = true
}
}
if m.Author != nil && m.Member != nil {
m.Member.UserID = m.Author.ID
}
}
// IsDirectMessage checks if the message is from a direct message channel.
//
// WARNING! Note that, when fetching messages using the REST API the
// guildID might be empty -> giving a false positive.
func (m *Message) IsDirectMessage() bool {
return m.Type == MessageTypeDefault && m.GuildID.IsZero()
}
// Send sends this message to discord.
func (m *Message) Send(ctx context.Context, s Session, flags ...Flag) (msg *Message, err error) {
nonce := fmt.Sprint(m.Nonce)
if len(nonce) > 25 {
return nil, errors.New("nonce can not be more than 25 characters")
}
// TODO: attachments
params := &CreateMessageParams{
Content: m.Content,
Tts: m.Tts,
Nonce: nonce,
// File: ...
// Embed: ...
}
if len(m.Embeds) > 0 {
params.Embed = &Embed{}
_ = DeepCopyOver(params.Embed, m.Embeds[0])
}
channelID := m.ChannelID
msg, err = s.Channel(channelID).WithContext(ctx).CreateMessage(params, flags...)
return
}
// Reply input any type as an reply. int, string, an object, etc.
func (m *Message) Reply(ctx context.Context, s Session, data ...interface{}) (*Message, error) {
return s.WithContext(ctx).SendMsg(m.ChannelID, data...)
}
func (m *Message) React(ctx context.Context, s Session, emoji interface{}, flags ...Flag) error {
if m.ID.IsZero() {
return errors.New("missing message ID")
} else if m.ChannelID.IsZero() {
return errors.New("missing channel ID")
}
return s.Channel(m.ChannelID).Message(m.ID).Reaction(emoji).WithContext(ctx).Create(flags...)
}
func (m *Message) Unreact(ctx context.Context, s Session, emoji interface{}, flags ...Flag) error {
if m.ID.IsZero() {
return errors.New("missing message ID")
} else if m.ChannelID.IsZero() {
return errors.New("missing channel ID")
}
return s.Channel(m.ChannelID).Message(m.ID).Reaction(emoji).WithContext(ctx).DeleteOwn(flags...)
}
// AddReaction adds a reaction to the message
//func (m *Message) AddReaction(reaction *Reaction) {}
// RemoveReaction removes a reaction from the message
//func (m *Message) RemoveReaction(id Snowflake) {}
//////////////////////////////////////////////////////
//
// REST Methods
//
//////////////////////////////////////////////////////
type MessageQueryBuilder interface {
WithContext(ctx context.Context) MessageQueryBuilder
// PinMessageID Pin a message by its ID and channel ID. Requires the 'MANAGE_MESSAGES' permission.
Pin(flags ...Flag) error
// UnpinMessageID Delete a pinned message in a channel. Requires the 'MANAGE_MESSAGES' permission.
Unpin(flags ...Flag) error
// GetMessage Returns a specific message in the channel. If operating on a guild channel, this endpoints
// requires the 'READ_MESSAGE_HISTORY' permission to be present on the current user.
// Returns a message object on success.
Get(flags ...Flag) (*Message, error)
// UpdateMessage Edit a previously sent message. You can only edit messages that have been sent by the
// current user. Returns a message object. Fires a Message Update Gateway event.
UpdateBuilder(flags ...Flag) *updateMessageBuilder
SetContent(content string) (*Message, error)
SetEmbed(embed *Embed) (*Message, error)
CrossPost(flags ...Flag) (*Message, error)
// Deprecated: use UpdateBuilder instead
Update(flags ...Flag) *updateMessageBuilder
// DeleteMessage Delete a message. If operating on a guild channel and trying to delete a message that was not
// sent by the current user, this endpoint requires the 'MANAGE_MESSAGES' permission. Fires a Message Delete Gateway event.
Delete(flags ...Flag) error
// DeleteAllReactions Deletes all reactions on a message. This endpoint requires the 'MANAGE_MESSAGES'
// permission to be present on the current user.
DeleteAllReactions(flags ...Flag) error
Reaction(emoji interface{}) ReactionQueryBuilder
}
func (c channelQueryBuilder) Message(id Snowflake) MessageQueryBuilder {
return &messageQueryBuilder{client: c.client, cid: c.cid, mid: id}
}
type messageQueryBuilder struct {
ctx context.Context
client *Client
cid Snowflake
mid Snowflake
}
func (m messageQueryBuilder) WithContext(ctx context.Context) MessageQueryBuilder {
m.ctx = ctx
return &m
}
// Get Returns a specific message in the channel. If operating on a guild channel, this endpoints
// requires the 'READ_MESSAGE_HISTORY' permission to be present on the current user.
// Returns a message object on success.
// Method GET
// Endpoint /channels/{channel.id}/messages/{message.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#get-channel-message
// Reviewed 2018-06-10
// Comment -
func (m messageQueryBuilder) Get(flags ...Flag) (*Message, error) {
if m.cid.IsZero() {
err := errors.New("channelID must be set to get channel messages")
return nil, err
}
if m.mid.IsZero() {
err := errors.New("messageID must be set to get a specific message from a channel")
return nil, err
}
if !ignoreCache(flags...) {
if msg, _ := m.client.cache.GetMessage(m.cid, m.mid); msg != nil {
return msg, nil
}
}
r := m.client.newRESTRequest(&httd.Request{
Endpoint: endpoint.ChannelMessage(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
r.pool = m.client.pool.message
r.factory = func() interface{} {
return &Message{}
}
return getMessage(r.Execute)
}
// Update Edit a previously sent message. You can only edit messages that have been sent by the
// current user. Returns a message object. Fires a Message Update Gateway event.
// Method PATCH
// Endpoint /channels/{channel.id}/messages/{message.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#edit-message
// Reviewed 2018-06-10
// Comment All parameters to this endpoint are optional.
func (m messageQueryBuilder) UpdateBuilder(flags ...Flag) (builder *updateMessageBuilder) {
builder = &updateMessageBuilder{}
builder.r.itemFactory = func() interface{} {
return &Message{}
}
builder.r.flags = flags
builder.r.addPrereq(m.cid.IsZero(), "channelID must be set to get channel messages")
builder.r.addPrereq(m.mid.IsZero(), "msgID must be set to edit the message")
builder.r.setup(m.client.req, &httd.Request{
Method: httd.MethodPatch,
Ctx: m.ctx,
Endpoint: "/channels/" + m.cid.String() + "/messages/" + m.mid.String(),
ContentType: httd.ContentTypeJSON,
}, nil)
return builder
}
// Delete If operating on a guild channel and trying to delete a message that was not
// sent by the current user, this endpoint requires the 'MANAGE_MESSAGES' permission. Returns a 204 empty response
// on success. Fires a Message Delete Gateway event.
// Method DELETE
// Endpoint /channels/{channel.id}/messages/{message.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#delete-message
// Reviewed 2018-06-10
// Comment -
func (m messageQueryBuilder) Delete(flags ...Flag) (err error) {
if m.cid.IsZero() {
err = errors.New("channelID must be set to get channel messages")
return
}
if m.mid.IsZero() {
err = errors.New("msgID must be set to delete the message")
return
}
r := m.client.newRESTRequest(&httd.Request{
Method: httd.MethodDelete,
Endpoint: endpoint.ChannelMessage(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
_, err = r.Execute()
return err
}
// Pin a message by its ID and channel ID. Requires the 'MANAGE_MESSAGES' permission.
// Returns a 204 empty response on success.
// Method PUT
// Endpoint /channels/{channel.id}/pins/{message.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#add-pinned-channel-message
// Reviewed 2018-06-10
// Comment -
func (m messageQueryBuilder) Pin(flags ...Flag) (err error) {
r := m.client.newRESTRequest(&httd.Request{
Method: httd.MethodPut,
Endpoint: endpoint.ChannelPin(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
_, err = r.Execute()
return err
}
// UnpinMessageID [REST] Delete a pinned message in a channel. Requires the 'MANAGE_MESSAGES' permission.
// Returns a 204 empty response on success. Returns a 204 empty response on success.
// Method DELETE
// Endpoint /channels/{channel.id}/pins/{message.id}
// Discord documentation https://discord.com/developers/docs/resources/channel#delete-pinned-channel-message
// Reviewed 2018-06-10
// Comment -
func (m messageQueryBuilder) Unpin(flags ...Flag) (err error) {
if m.cid.IsZero() {
return errors.New("channelID must be set to target the correct channel")
}
if m.mid.IsZero() {
return errors.New("messageID must be set to target the specific channel message")
}
r := m.client.newRESTRequest(&httd.Request{
Method: httd.MethodDelete,
Endpoint: endpoint.ChannelPin(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
_, err = r.Execute()
return err
}
// CrossPost Crosspost a message in a News Channel to following channels.
// Method POST
// Endpoint /channels/{channel.id}/messages/{message.id}/crosspost
// Discord documentation https://discord.com/developers/docs/resources/channel#crosspost-message
// Reviewed 2021-04-07
// Comment -
func (m messageQueryBuilder) CrossPost(flags ...Flag) (*Message, error) {
if m.cid.IsZero() {
return nil, errors.New("channelID must be set to target the correct channel")
}
if m.mid.IsZero() {
return nil, errors.New("messageID must be set to target the specific channel message")
}
r := m.client.newRESTRequest(&httd.Request{
Method: httd.MethodPost,
Endpoint: endpoint.ChannelMessageCrossPost(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
r.pool = m.client.pool.message
r.factory = func() interface{} {
return &Message{}
}
msg, err := r.Execute()
if err != nil {
return nil, err
}
return msg.(*Message), nil
}
// DeleteAllReactions [REST] Deletes all reactions on a message. This endpoint requires the 'MANAGE_MESSAGES'
// permission to be present on the current user.
// Method DELETE
// Endpoint /channels/{channel.id}/messages/{message.id}/reactions
// Discord documentation https://discord.com/developers/docs/resources/channel#delete-all-reactions
// Reviewed 2019-01-28
func (m messageQueryBuilder) DeleteAllReactions(flags ...Flag) error {
if m.cid.IsZero() {
return errors.New("channelID must be set to target the correct channel")
}
if m.mid.IsZero() {
return errors.New("messageID must be set to target the specific channel message")
}
r := m.client.newRESTRequest(&httd.Request{
Method: httd.MethodDelete,
Endpoint: endpoint.ChannelMessageReactions(m.cid, m.mid),
Ctx: m.ctx,
}, flags)
_, err := r.Execute()
return err
}
//////////////////////////////////////////////////////
//
// REST Wrappers
//
//////////////////////////////////////////////////////
func (m messageQueryBuilder) SetContent(content string) (*Message, error) {
builder := m.WithContext(m.ctx).UpdateBuilder()
return builder.
SetContent(content).
Execute()
}
func (m messageQueryBuilder) SetEmbed(embed *Embed) (*Message, error) {
builder := m.WithContext(m.ctx).UpdateBuilder()
return builder.
SetEmbed(embed).
Execute()
}
//////////////////////////////////////////////////////
//
// REST Builders
//
//////////////////////////////////////////////////////
// updateMessageBuilder, params here
// https://discord.com/developers/docs/resources/channel#edit-message-json-params
//generate-rest-params: content:string, embed:*Embed,
//generate-rest-basic-execute: message:*Message,
type updateMessageBuilder struct {
r RESTBuilder
}
// SetAllowedMentions sets the allowed mentions for the updateMessageBuilder then returns the builder to allow chaining.
func (b *updateMessageBuilder) SetAllowedMentions(mentions *AllowedMentions) *updateMessageBuilder {
b.r.param("allowed_mentions", mentions)
return b
}