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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
|
// Discordgo - Discord bindings for Go
// Available at https://github.com/bwmarrin/discordgo
// Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file contains all structures for the discordgo package. These
// may be moved about later into separate files but I find it easier to have
// them all located together.
package discordgo
import (
"encoding/json"
"net/http"
"sync"
"time"
"github.com/gorilla/websocket"
)
// A Session represents a connection to the Discord API.
type Session struct {
sync.RWMutex
// General configurable settings.
// Authentication token for this session
Token string
MFA bool
// Debug for printing JSON request/responses
Debug bool // Deprecated, will be removed.
LogLevel int
// Should the session reconnect the websocket on errors.
ShouldReconnectOnError bool
// Should the session request compressed websocket data.
Compress bool
// Sharding
ShardID int
ShardCount int
// Should state tracking be enabled.
// State tracking is the best way for getting the the users
// active guilds and the members of the guilds.
StateEnabled bool
// Whether or not to call event handlers synchronously.
// e.g false = launch event handlers in their own goroutines.
SyncEvents bool
// Exposed but should not be modified by User.
// Whether the Data Websocket is ready
DataReady bool // NOTE: Maye be deprecated soon
// Max number of REST API retries
MaxRestRetries int
// Status stores the currect status of the websocket connection
// this is being tested, may stay, may go away.
status int32
// Whether the Voice Websocket is ready
VoiceReady bool // NOTE: Deprecated.
// Whether the UDP Connection is ready
UDPReady bool // NOTE: Deprecated
// Stores a mapping of guild id's to VoiceConnections
VoiceConnections map[string]*VoiceConnection
// Managed state object, updated internally with events when
// StateEnabled is true.
State *State
// The http client used for REST requests
Client *http.Client
// Stores the last HeartbeatAck that was recieved (in UTC)
LastHeartbeatAck time.Time
// used to deal with rate limits
Ratelimiter *RateLimiter
// Event handlers
handlersMu sync.RWMutex
handlers map[string][]*eventHandlerInstance
onceHandlers map[string][]*eventHandlerInstance
// The websocket connection.
wsConn *websocket.Conn
// When nil, the session is not listening.
listening chan interface{}
// sequence tracks the current gateway api websocket sequence number
sequence *int64
// stores sessions current Discord Gateway
gateway string
// stores session ID of current Gateway connection
sessionID string
// used to make sure gateway websocket writes do not happen concurrently
wsMutex sync.Mutex
}
// A VoiceRegion stores data for a specific voice region server.
type VoiceRegion struct {
ID string `json:"id"`
Name string `json:"name"`
Hostname string `json:"sample_hostname"`
Port int `json:"sample_port"`
}
// A VoiceICE stores data for voice ICE servers.
type VoiceICE struct {
TTL string `json:"ttl"`
Servers []*ICEServer `json:"servers"`
}
// A ICEServer stores data for a specific voice ICE server.
type ICEServer struct {
URL string `json:"url"`
Username string `json:"username"`
Credential string `json:"credential"`
}
// A Invite stores all data related to a specific Discord Guild or Channel invite.
type Invite struct {
Guild *Guild `json:"guild"`
Channel *Channel `json:"channel"`
Inviter *User `json:"inviter"`
Code string `json:"code"`
CreatedAt Timestamp `json:"created_at"`
MaxAge int `json:"max_age"`
Uses int `json:"uses"`
MaxUses int `json:"max_uses"`
Revoked bool `json:"revoked"`
Temporary bool `json:"temporary"`
Unique bool `json:"unique"`
}
// ChannelType is the type of a Channel
type ChannelType int
// Block contains known ChannelType values
const (
ChannelTypeGuildText ChannelType = iota
ChannelTypeDM
ChannelTypeGuildVoice
ChannelTypeGroupDM
ChannelTypeGuildCategory
)
// A Channel holds all data related to an individual Discord channel.
type Channel struct {
ID string `json:"id"`
GuildID string `json:"guild_id"`
Name string `json:"name"`
Topic string `json:"topic"`
Type ChannelType `json:"type"`
LastMessageID string `json:"last_message_id"`
NSFW bool `json:"nsfw"`
Position int `json:"position"`
Bitrate int `json:"bitrate"`
Recipients []*User `json:"recipients"`
Messages []*Message `json:"-"`
PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites"`
ParentID string `json:"parent_id"`
}
// A ChannelEdit holds Channel Feild data for a channel edit.
type ChannelEdit struct {
Name string `json:"name,omitempty"`
Topic string `json:"topic,omitempty"`
NSFW bool `json:"nsfw,omitempty"`
Position int `json:"position"`
Bitrate int `json:"bitrate,omitempty"`
UserLimit int `json:"user_limit,omitempty"`
PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites,omitempty"`
ParentID string `json:"parent_id,omitempty"`
}
// A PermissionOverwrite holds permission overwrite data for a Channel
type PermissionOverwrite struct {
ID string `json:"id"`
Type string `json:"type"`
Deny int `json:"deny"`
Allow int `json:"allow"`
}
// Emoji struct holds data related to Emoji's
type Emoji struct {
ID string `json:"id"`
Name string `json:"name"`
Roles []string `json:"roles"`
Managed bool `json:"managed"`
RequireColons bool `json:"require_colons"`
Animated bool `json:"animated"`
}
// APIName returns an correctly formatted API name for use in the MessageReactions endpoints.
func (e *Emoji) APIName() string {
if e.ID != "" && e.Name != "" {
return e.Name + ":" + e.ID
}
if e.Name != "" {
return e.Name
}
return e.ID
}
// VerificationLevel type definition
type VerificationLevel int
// Constants for VerificationLevel levels from 0 to 3 inclusive
const (
VerificationLevelNone VerificationLevel = iota
VerificationLevelLow
VerificationLevelMedium
VerificationLevelHigh
)
// A Guild holds all data related to a specific Discord Guild. Guilds are also
// sometimes referred to as Servers in the Discord client.
type Guild struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Region string `json:"region"`
AfkChannelID string `json:"afk_channel_id"`
EmbedChannelID string `json:"embed_channel_id"`
OwnerID string `json:"owner_id"`
JoinedAt Timestamp `json:"joined_at"`
Splash string `json:"splash"`
AfkTimeout int `json:"afk_timeout"`
MemberCount int `json:"member_count"`
VerificationLevel VerificationLevel `json:"verification_level"`
EmbedEnabled bool `json:"embed_enabled"`
Large bool `json:"large"` // ??
DefaultMessageNotifications int `json:"default_message_notifications"`
Roles []*Role `json:"roles"`
Emojis []*Emoji `json:"emojis"`
Members []*Member `json:"members"`
Presences []*Presence `json:"presences"`
Channels []*Channel `json:"channels"`
VoiceStates []*VoiceState `json:"voice_states"`
Unavailable bool `json:"unavailable"`
}
// A UserGuild holds a brief version of a Guild
type UserGuild struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Owner bool `json:"owner"`
Permissions int `json:"permissions"`
}
// A GuildParams stores all the data needed to update discord guild settings
type GuildParams struct {
Name string `json:"name,omitempty"`
Region string `json:"region,omitempty"`
VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
DefaultMessageNotifications int `json:"default_message_notifications,omitempty"` // TODO: Separate type?
AfkChannelID string `json:"afk_channel_id,omitempty"`
AfkTimeout int `json:"afk_timeout,omitempty"`
Icon string `json:"icon,omitempty"`
OwnerID string `json:"owner_id,omitempty"`
Splash string `json:"splash,omitempty"`
}
// A Role stores information about Discord guild member roles.
type Role struct {
ID string `json:"id"`
Name string `json:"name"`
Managed bool `json:"managed"`
Mentionable bool `json:"mentionable"`
Hoist bool `json:"hoist"`
Color int `json:"color"`
Position int `json:"position"`
Permissions int `json:"permissions"`
}
// Roles are a collection of Role
type Roles []*Role
func (r Roles) Len() int {
return len(r)
}
func (r Roles) Less(i, j int) bool {
return r[i].Position > r[j].Position
}
func (r Roles) Swap(i, j int) {
r[i], r[j] = r[j], r[i]
}
// A VoiceState stores the voice states of Guilds
type VoiceState struct {
UserID string `json:"user_id"`
SessionID string `json:"session_id"`
ChannelID string `json:"channel_id"`
GuildID string `json:"guild_id"`
Suppress bool `json:"suppress"`
SelfMute bool `json:"self_mute"`
SelfDeaf bool `json:"self_deaf"`
Mute bool `json:"mute"`
Deaf bool `json:"deaf"`
}
// A Presence stores the online, offline, or idle and game status of Guild members.
type Presence struct {
User *User `json:"user"`
Status Status `json:"status"`
Game *Game `json:"game"`
Nick string `json:"nick"`
Roles []string `json:"roles"`
Since *int `json:"since"`
}
// GameType is the type of "game" (see GameType* consts) in the Game struct
type GameType int
// Valid GameType values
const (
GameTypeGame GameType = iota
GameTypeStreaming
)
// A Game struct holds the name of the "playing .." game for a user
type Game struct {
Name string `json:"name"`
Type GameType `json:"type"`
URL string `json:"url,omitempty"`
Details string `json:"details,omitempty"`
State string `json:"state,omitempty"`
TimeStamps TimeStamps `json:"timestamps,omitempty"`
Assets Assets `json:"assets,omitempty"`
ApplicationID string `json:"application_id,omitempty"`
Instance int8 `json:"instance,omitempty"`
// TODO: Party and Secrets (unknown structure)
}
// A TimeStamps struct contains start and end times used in the rich presence "playing .." Game
type TimeStamps struct {
EndTimestamp int64 `json:"end,omitempty"`
StartTimestamp int64 `json:"start,omitempty"`
}
// UnmarshalJSON unmarshals JSON into TimeStamps struct
func (t *TimeStamps) UnmarshalJSON(b []byte) error {
temp := struct {
End float64 `json:"end,omitempty"`
Start float64 `json:"start,omitempty"`
}{}
err := json.Unmarshal(b, &temp)
if err != nil {
return err
}
t.EndTimestamp = int64(temp.End)
t.StartTimestamp = int64(temp.Start)
return nil
}
// An Assets struct contains assets and labels used in the rich presence "playing .." Game
type Assets struct {
LargeImageID string `json:"large_image,omitempty"`
SmallImageID string `json:"small_image,omitempty"`
LargeText string `json:"large_text,omitempty"`
SmallText string `json:"small_text,omitempty"`
}
// A Member stores user information for Guild members.
type Member struct {
GuildID string `json:"guild_id"`
JoinedAt string `json:"joined_at"`
Nick string `json:"nick"`
Deaf bool `json:"deaf"`
Mute bool `json:"mute"`
User *User `json:"user"`
Roles []string `json:"roles"`
}
// A Settings stores data for a specific users Discord client settings.
type Settings struct {
RenderEmbeds bool `json:"render_embeds"`
InlineEmbedMedia bool `json:"inline_embed_media"`
InlineAttachmentMedia bool `json:"inline_attachment_media"`
EnableTtsCommand bool `json:"enable_tts_command"`
MessageDisplayCompact bool `json:"message_display_compact"`
ShowCurrentGame bool `json:"show_current_game"`
ConvertEmoticons bool `json:"convert_emoticons"`
Locale string `json:"locale"`
Theme string `json:"theme"`
GuildPositions []string `json:"guild_positions"`
RestrictedGuilds []string `json:"restricted_guilds"`
FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
Status Status `json:"status"`
DetectPlatformAccounts bool `json:"detect_platform_accounts"`
DeveloperMode bool `json:"developer_mode"`
}
// Status type definition
type Status string
// Constants for Status with the different current available status
const (
StatusOnline Status = "online"
StatusIdle Status = "idle"
StatusDoNotDisturb Status = "dnd"
StatusInvisible Status = "invisible"
StatusOffline Status = "offline"
)
// FriendSourceFlags stores ... TODO :)
type FriendSourceFlags struct {
All bool `json:"all"`
MutualGuilds bool `json:"mutual_guilds"`
MutualFriends bool `json:"mutual_friends"`
}
// A Relationship between the logged in user and Relationship.User
type Relationship struct {
User *User `json:"user"`
Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
ID string `json:"id"`
}
// A TooManyRequests struct holds information received from Discord
// when receiving a HTTP 429 response.
type TooManyRequests struct {
Bucket string `json:"bucket"`
Message string `json:"message"`
RetryAfter time.Duration `json:"retry_after"`
}
// A ReadState stores data on the read state of channels.
type ReadState struct {
MentionCount int `json:"mention_count"`
LastMessageID string `json:"last_message_id"`
ID string `json:"id"`
}
// An Ack is used to ack messages
type Ack struct {
Token string `json:"token"`
}
// A GuildRole stores data for guild roles.
type GuildRole struct {
Role *Role `json:"role"`
GuildID string `json:"guild_id"`
}
// A GuildBan stores data for a guild ban.
type GuildBan struct {
Reason string `json:"reason"`
User *User `json:"user"`
}
// A GuildIntegration stores data for a guild integration.
type GuildIntegration struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
Syncing bool `json:"syncing"`
RoleID string `json:"role_id"`
ExpireBehavior int `json:"expire_behavior"`
ExpireGracePeriod int `json:"expire_grace_period"`
User *User `json:"user"`
Account *GuildIntegrationAccount `json:"account"`
SyncedAt int `json:"synced_at"`
}
// A GuildIntegrationAccount stores data for a guild integration account.
type GuildIntegrationAccount struct {
ID string `json:"id"`
Name string `json:"name"`
}
// A GuildEmbed stores data for a guild embed.
type GuildEmbed struct {
Enabled bool `json:"enabled"`
ChannelID string `json:"channel_id"`
}
// A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
type UserGuildSettingsChannelOverride struct {
Muted bool `json:"muted"`
MessageNotifications int `json:"message_notifications"`
ChannelID string `json:"channel_id"`
}
// A UserGuildSettings stores data for a users guild settings.
type UserGuildSettings struct {
SupressEveryone bool `json:"suppress_everyone"`
Muted bool `json:"muted"`
MobilePush bool `json:"mobile_push"`
MessageNotifications int `json:"message_notifications"`
GuildID string `json:"guild_id"`
ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
}
// A UserGuildSettingsEdit stores data for editing UserGuildSettings
type UserGuildSettingsEdit struct {
SupressEveryone bool `json:"suppress_everyone"`
Muted bool `json:"muted"`
MobilePush bool `json:"mobile_push"`
MessageNotifications int `json:"message_notifications"`
ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
}
// An APIErrorMessage is an api error message returned from discord
type APIErrorMessage struct {
Code int `json:"code"`
Message string `json:"message"`
}
// Webhook stores the data for a webhook.
type Webhook struct {
ID string `json:"id"`
GuildID string `json:"guild_id"`
ChannelID string `json:"channel_id"`
User *User `json:"user"`
Name string `json:"name"`
Avatar string `json:"avatar"`
Token string `json:"token"`
}
// WebhookParams is a struct for webhook params, used in the WebhookExecute command.
type WebhookParams struct {
Content string `json:"content,omitempty"`
Username string `json:"username,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
TTS bool `json:"tts,omitempty"`
File string `json:"file,omitempty"`
Embeds []*MessageEmbed `json:"embeds,omitempty"`
}
// MessageReaction stores the data for a message reaction.
type MessageReaction struct {
UserID string `json:"user_id"`
MessageID string `json:"message_id"`
Emoji Emoji `json:"emoji"`
ChannelID string `json:"channel_id"`
}
// GatewayBotResponse stores the data for the gateway/bot response
type GatewayBotResponse struct {
URL string `json:"url"`
Shards int `json:"shards"`
}
// Constants for the different bit offsets of text channel permissions
const (
PermissionReadMessages = 1 << (iota + 10)
PermissionSendMessages
PermissionSendTTSMessages
PermissionManageMessages
PermissionEmbedLinks
PermissionAttachFiles
PermissionReadMessageHistory
PermissionMentionEveryone
PermissionUseExternalEmojis
)
// Constants for the different bit offsets of voice permissions
const (
PermissionVoiceConnect = 1 << (iota + 20)
PermissionVoiceSpeak
PermissionVoiceMuteMembers
PermissionVoiceDeafenMembers
PermissionVoiceMoveMembers
PermissionVoiceUseVAD
)
// Constants for general management.
const (
PermissionChangeNickname = 1 << (iota + 26)
PermissionManageNicknames
PermissionManageRoles
PermissionManageWebhooks
PermissionManageEmojis
)
// Constants for the different bit offsets of general permissions
const (
PermissionCreateInstantInvite = 1 << iota
PermissionKickMembers
PermissionBanMembers
PermissionAdministrator
PermissionManageChannels
PermissionManageServer
PermissionAddReactions
PermissionViewAuditLogs
PermissionAllText = PermissionReadMessages |
PermissionSendMessages |
PermissionSendTTSMessages |
PermissionManageMessages |
PermissionEmbedLinks |
PermissionAttachFiles |
PermissionReadMessageHistory |
PermissionMentionEveryone
PermissionAllVoice = PermissionVoiceConnect |
PermissionVoiceSpeak |
PermissionVoiceMuteMembers |
PermissionVoiceDeafenMembers |
PermissionVoiceMoveMembers |
PermissionVoiceUseVAD
PermissionAllChannel = PermissionAllText |
PermissionAllVoice |
PermissionCreateInstantInvite |
PermissionManageRoles |
PermissionManageChannels |
PermissionAddReactions |
PermissionViewAuditLogs
PermissionAll = PermissionAllChannel |
PermissionKickMembers |
PermissionBanMembers |
PermissionManageServer |
PermissionAdministrator
)
// Block contains Discord JSON Error Response codes
const (
ErrCodeUnknownAccount = 10001
ErrCodeUnknownApplication = 10002
ErrCodeUnknownChannel = 10003
ErrCodeUnknownGuild = 10004
ErrCodeUnknownIntegration = 10005
ErrCodeUnknownInvite = 10006
ErrCodeUnknownMember = 10007
ErrCodeUnknownMessage = 10008
ErrCodeUnknownOverwrite = 10009
ErrCodeUnknownProvider = 10010
ErrCodeUnknownRole = 10011
ErrCodeUnknownToken = 10012
ErrCodeUnknownUser = 10013
ErrCodeUnknownEmoji = 10014
ErrCodeBotsCannotUseEndpoint = 20001
ErrCodeOnlyBotsCanUseEndpoint = 20002
ErrCodeMaximumGuildsReached = 30001
ErrCodeMaximumFriendsReached = 30002
ErrCodeMaximumPinsReached = 30003
ErrCodeMaximumGuildRolesReached = 30005
ErrCodeTooManyReactions = 30010
ErrCodeUnauthorized = 40001
ErrCodeMissingAccess = 50001
ErrCodeInvalidAccountType = 50002
ErrCodeCannotExecuteActionOnDMChannel = 50003
ErrCodeEmbedCisabled = 50004
ErrCodeCannotEditFromAnotherUser = 50005
ErrCodeCannotSendEmptyMessage = 50006
ErrCodeCannotSendMessagesToThisUser = 50007
ErrCodeCannotSendMessagesInVoiceChannel = 50008
ErrCodeChannelVerificationLevelTooHigh = 50009
ErrCodeOAuth2ApplicationDoesNotHaveBot = 50010
ErrCodeOAuth2ApplicationLimitReached = 50011
ErrCodeInvalidOAuthState = 50012
ErrCodeMissingPermissions = 50013
ErrCodeInvalidAuthenticationToken = 50014
ErrCodeNoteTooLong = 50015
ErrCodeTooFewOrTooManyMessagesToDelete = 50016
ErrCodeCanOnlyPinMessageToOriginatingChannel = 50019
ErrCodeCannotExecuteActionOnSystemMessage = 50021
ErrCodeMessageProvidedTooOldForBulkDelete = 50034
ErrCodeInvalidFormBody = 50035
ErrCodeInviteAcceptedToGuildApplicationsBotNotIn = 50036
ErrCodeReactionBlocked = 90001
)
|