structs.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015-2016 Bruce Marriner <bruce@sqls.net>. All rights reserved.
  4. // Use of this source code is governed by a BSD-style
  5. // license that can be found in the LICENSE file.
  6. // This file contains all structures for the discordgo package. These
  7. // may be moved about later into separate files but I find it easier to have
  8. // them all located together.
  9. package discordgo
  10. import (
  11. "encoding/json"
  12. "reflect"
  13. "strconv"
  14. "sync"
  15. "time"
  16. "github.com/gorilla/websocket"
  17. )
  18. // A Session represents a connection to the Discord API.
  19. type Session struct {
  20. sync.RWMutex
  21. // General configurable settings.
  22. // Authentication token for this session
  23. Token string
  24. // Debug for printing JSON request/responses
  25. Debug bool // Deprecated, will be removed.
  26. LogLevel int
  27. // Should the session reconnect the websocket on errors.
  28. ShouldReconnectOnError bool
  29. // Should the session request compressed websocket data.
  30. Compress bool
  31. // Sharding
  32. ShardID int
  33. ShardCount int
  34. // Should state tracking be enabled.
  35. // State tracking is the best way for getting the the users
  36. // active guilds and the members of the guilds.
  37. StateEnabled bool
  38. // Exposed but should not be modified by User.
  39. // Whether the Data Websocket is ready
  40. DataReady bool // NOTE: Maye be deprecated soon
  41. // Max number of REST API retries
  42. MaxRestRetries int
  43. // Status stores the currect status of the websocket connection
  44. // this is being tested, may stay, may go away.
  45. status int32
  46. // Whether the Voice Websocket is ready
  47. VoiceReady bool // NOTE: Deprecated.
  48. // Whether the UDP Connection is ready
  49. UDPReady bool // NOTE: Deprecated
  50. // Stores a mapping of guild id's to VoiceConnections
  51. VoiceConnections map[string]*VoiceConnection
  52. // Managed state object, updated internally with events when
  53. // StateEnabled is true.
  54. State *State
  55. handlersMu sync.RWMutex
  56. // This is a mapping of event struct to a reflected value
  57. // for event handlers.
  58. // We store the reflected value instead of the function
  59. // reference as it is more performant, instead of re-reflecting
  60. // the function each event.
  61. handlers map[interface{}][]reflect.Value
  62. // The websocket connection.
  63. wsConn *websocket.Conn
  64. // When nil, the session is not listening.
  65. listening chan interface{}
  66. // used to deal with rate limits
  67. ratelimiter *RateLimiter
  68. // sequence tracks the current gateway api websocket sequence number
  69. sequence int
  70. // stores sessions current Discord Gateway
  71. gateway string
  72. // stores session ID of current Gateway connection
  73. sessionID string
  74. // used to make sure gateway websocket writes do not happen concurrently
  75. wsMutex sync.Mutex
  76. }
  77. type rateLimitMutex struct {
  78. sync.Mutex
  79. url map[string]*sync.Mutex
  80. // bucket map[string]*sync.Mutex // TODO :)
  81. }
  82. // A Resumed struct holds the data received in a RESUMED event
  83. type Resumed struct {
  84. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  85. Trace []string `json:"_trace"`
  86. }
  87. // A VoiceRegion stores data for a specific voice region server.
  88. type VoiceRegion struct {
  89. ID string `json:"id"`
  90. Name string `json:"name"`
  91. Hostname string `json:"sample_hostname"`
  92. Port int `json:"sample_port"`
  93. }
  94. // A VoiceICE stores data for voice ICE servers.
  95. type VoiceICE struct {
  96. TTL string `json:"ttl"`
  97. Servers []*ICEServer `json:"servers"`
  98. }
  99. // A ICEServer stores data for a specific voice ICE server.
  100. type ICEServer struct {
  101. URL string `json:"url"`
  102. Username string `json:"username"`
  103. Credential string `json:"credential"`
  104. }
  105. // A Invite stores all data related to a specific Discord Guild or Channel invite.
  106. type Invite struct {
  107. Guild *Guild `json:"guild"`
  108. Channel *Channel `json:"channel"`
  109. Inviter *User `json:"inviter"`
  110. Code string `json:"code"`
  111. CreatedAt Timestamp `json:"created_at"`
  112. MaxAge int `json:"max_age"`
  113. Uses int `json:"uses"`
  114. MaxUses int `json:"max_uses"`
  115. XkcdPass string `json:"xkcdpass"`
  116. Revoked bool `json:"revoked"`
  117. Temporary bool `json:"temporary"`
  118. }
  119. // A Channel holds all data related to an individual Discord channel.
  120. type Channel struct {
  121. ID string `json:"id"`
  122. GuildID string `json:"guild_id"`
  123. Name string `json:"name"`
  124. Topic string `json:"topic"`
  125. Type string `json:"type"`
  126. LastMessageID string `json:"last_message_id"`
  127. Position int `json:"position"`
  128. Bitrate int `json:"bitrate"`
  129. IsPrivate bool `json:"is_private"`
  130. Recipient *User `json:"recipient"`
  131. Messages []*Message `json:"-"`
  132. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites"`
  133. }
  134. // A PermissionOverwrite holds permission overwrite data for a Channel
  135. type PermissionOverwrite struct {
  136. ID string `json:"id"`
  137. Type string `json:"type"`
  138. Deny int `json:"deny"`
  139. Allow int `json:"allow"`
  140. }
  141. // Emoji struct holds data related to Emoji's
  142. type Emoji struct {
  143. ID string `json:"id"`
  144. Name string `json:"name"`
  145. Roles []string `json:"roles"`
  146. Managed bool `json:"managed"`
  147. RequireColons bool `json:"require_colons"`
  148. }
  149. // APIName returns an correctly formatted API name for use in the MessageReactions endpoints.
  150. func (e *Emoji) APIName() string {
  151. if e.ID != "" && e.Name != "" {
  152. return e.Name + ":" + e.ID
  153. }
  154. if e.Name != "" {
  155. return e.Name
  156. }
  157. return e.ID
  158. }
  159. // VerificationLevel type defination
  160. type VerificationLevel int
  161. // Constants for VerificationLevel levels from 0 to 3 inclusive
  162. const (
  163. VerificationLevelNone VerificationLevel = iota
  164. VerificationLevelLow
  165. VerificationLevelMedium
  166. VerificationLevelHigh
  167. )
  168. // A Guild holds all data related to a specific Discord Guild. Guilds are also
  169. // sometimes referred to as Servers in the Discord client.
  170. type Guild struct {
  171. ID string `json:"id"`
  172. Name string `json:"name"`
  173. Icon string `json:"icon"`
  174. Region string `json:"region"`
  175. AfkChannelID string `json:"afk_channel_id"`
  176. EmbedChannelID string `json:"embed_channel_id"`
  177. OwnerID string `json:"owner_id"`
  178. JoinedAt Timestamp `json:"joined_at"`
  179. Splash string `json:"splash"`
  180. AfkTimeout int `json:"afk_timeout"`
  181. MemberCount int `json:"member_count"`
  182. VerificationLevel VerificationLevel `json:"verification_level"`
  183. EmbedEnabled bool `json:"embed_enabled"`
  184. Large bool `json:"large"` // ??
  185. DefaultMessageNotifications int `json:"default_message_notifications"`
  186. Roles []*Role `json:"roles"`
  187. Emojis []*Emoji `json:"emojis"`
  188. Members []*Member `json:"members"`
  189. Presences []*Presence `json:"presences"`
  190. Channels []*Channel `json:"channels"`
  191. VoiceStates []*VoiceState `json:"voice_states"`
  192. Unavailable bool `json:"unavailable"`
  193. }
  194. // A UserGuild holds a brief version of a Guild
  195. type UserGuild struct {
  196. ID string `json:"id"`
  197. Name string `json:"name"`
  198. Icon string `json:"icon"`
  199. Owner bool `json:"owner"`
  200. Permissions int `json:"permissions"`
  201. }
  202. // A GuildParams stores all the data needed to update discord guild settings
  203. type GuildParams struct {
  204. Name string `json:"name"`
  205. Region string `json:"region"`
  206. VerificationLevel *VerificationLevel `json:"verification_level"`
  207. }
  208. // A Role stores information about Discord guild member roles.
  209. type Role struct {
  210. ID string `json:"id"`
  211. Name string `json:"name"`
  212. Managed bool `json:"managed"`
  213. Mentionable bool `json:"mentionable"`
  214. Hoist bool `json:"hoist"`
  215. Color int `json:"color"`
  216. Position int `json:"position"`
  217. Permissions int `json:"permissions"`
  218. }
  219. // A VoiceState stores the voice states of Guilds
  220. type VoiceState struct {
  221. UserID string `json:"user_id"`
  222. SessionID string `json:"session_id"`
  223. ChannelID string `json:"channel_id"`
  224. GuildID string `json:"guild_id"`
  225. Suppress bool `json:"suppress"`
  226. SelfMute bool `json:"self_mute"`
  227. SelfDeaf bool `json:"self_deaf"`
  228. Mute bool `json:"mute"`
  229. Deaf bool `json:"deaf"`
  230. }
  231. // A Presence stores the online, offline, or idle and game status of Guild members.
  232. type Presence struct {
  233. User *User `json:"user"`
  234. Status Status `json:"status"`
  235. Game *Game `json:"game"`
  236. Nick string `json:"nick"`
  237. Roles []string `json:"roles"`
  238. }
  239. // A Game struct holds the name of the "playing .." game for a user
  240. type Game struct {
  241. Name string `json:"name"`
  242. Type int `json:"type"`
  243. URL string `json:"url"`
  244. }
  245. // UnmarshalJSON unmarshals json to Game struct
  246. func (g *Game) UnmarshalJSON(bytes []byte) error {
  247. temp := &struct {
  248. Name string `json:"name"`
  249. Type json.RawMessage `json:"type"`
  250. URL string `json:"url"`
  251. }{}
  252. err := json.Unmarshal(bytes, temp)
  253. if err != nil {
  254. return err
  255. }
  256. g.Name = temp.Name
  257. g.URL = temp.URL
  258. if temp.Type != nil {
  259. err = json.Unmarshal(temp.Type, &g.Type)
  260. if err == nil {
  261. return nil
  262. }
  263. s := ""
  264. err = json.Unmarshal(temp.Type, &s)
  265. if err == nil {
  266. g.Type, err = strconv.Atoi(s)
  267. }
  268. return err
  269. }
  270. return nil
  271. }
  272. // A Member stores user information for Guild members.
  273. type Member struct {
  274. GuildID string `json:"guild_id"`
  275. JoinedAt string `json:"joined_at"`
  276. Nick string `json:"nick"`
  277. Deaf bool `json:"deaf"`
  278. Mute bool `json:"mute"`
  279. User *User `json:"user"`
  280. Roles []string `json:"roles"`
  281. }
  282. // A User stores all data for an individual Discord user.
  283. type User struct {
  284. ID string `json:"id"`
  285. Email string `json:"email"`
  286. Username string `json:"username"`
  287. Avatar string `json:"Avatar"`
  288. Discriminator string `json:"discriminator"`
  289. Token string `json:"token"`
  290. Verified bool `json:"verified"`
  291. MFAEnabled bool `json:"mfa_enabled"`
  292. Bot bool `json:"bot"`
  293. }
  294. // A Settings stores data for a specific users Discord client settings.
  295. type Settings struct {
  296. RenderEmbeds bool `json:"render_embeds"`
  297. InlineEmbedMedia bool `json:"inline_embed_media"`
  298. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  299. EnableTtsCommand bool `json:"enable_tts_command"`
  300. MessageDisplayCompact bool `json:"message_display_compact"`
  301. ShowCurrentGame bool `json:"show_current_game"`
  302. ConvertEmoticons bool `json:"convert_emoticons"`
  303. Locale string `json:"locale"`
  304. Theme string `json:"theme"`
  305. GuildPositions []string `json:"guild_positions"`
  306. RestrictedGuilds []string `json:"restricted_guilds"`
  307. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  308. Status Status `json:"status"`
  309. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  310. DeveloperMode bool `json:"developer_mode"`
  311. }
  312. // Status type defination
  313. type Status string
  314. // Constants for Status with the different current available status
  315. const (
  316. StatusOnline Status = "online"
  317. StatusIdle Status = "idle"
  318. StatusDoNotDisturb Status = "dnd"
  319. StatusInvisible Status = "invisible"
  320. StatusOffline Status = "offline"
  321. )
  322. // FriendSourceFlags stores ... TODO :)
  323. type FriendSourceFlags struct {
  324. All bool `json:"all"`
  325. MutualGuilds bool `json:"mutual_guilds"`
  326. MutualFriends bool `json:"mutual_friends"`
  327. }
  328. // An Event provides a basic initial struct for all websocket event.
  329. type Event struct {
  330. Operation int `json:"op"`
  331. Sequence int `json:"s"`
  332. Type string `json:"t"`
  333. RawData json.RawMessage `json:"d"`
  334. Struct interface{} `json:"-"`
  335. }
  336. // A Ready stores all data for the websocket READY event.
  337. type Ready struct {
  338. Version int `json:"v"`
  339. SessionID string `json:"session_id"`
  340. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  341. User *User `json:"user"`
  342. ReadState []*ReadState `json:"read_state"`
  343. PrivateChannels []*Channel `json:"private_channels"`
  344. Guilds []*Guild `json:"guilds"`
  345. // Undocumented fields
  346. Settings *Settings `json:"user_settings"`
  347. UserGuildSettings []*UserGuildSettings `json:"user_guild_settings"`
  348. Relationships []*Relationship `json:"relationships"`
  349. Presences []*Presence `json:"presences"`
  350. }
  351. // A Relationship between the logged in user and Relationship.User
  352. type Relationship struct {
  353. User *User `json:"user"`
  354. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  355. ID string `json:"id"`
  356. }
  357. // A TooManyRequests struct holds information received from Discord
  358. // when receiving a HTTP 429 response.
  359. type TooManyRequests struct {
  360. Bucket string `json:"bucket"`
  361. Message string `json:"message"`
  362. RetryAfter time.Duration `json:"retry_after"`
  363. }
  364. // A ReadState stores data on the read state of channels.
  365. type ReadState struct {
  366. MentionCount int `json:"mention_count"`
  367. LastMessageID string `json:"last_message_id"`
  368. ID string `json:"id"`
  369. }
  370. // A TypingStart stores data for the typing start websocket event.
  371. type TypingStart struct {
  372. UserID string `json:"user_id"`
  373. ChannelID string `json:"channel_id"`
  374. Timestamp int `json:"timestamp"`
  375. }
  376. // A PresenceUpdate stores data for the presence update websocket event.
  377. type PresenceUpdate struct {
  378. Presence
  379. GuildID string `json:"guild_id"`
  380. Roles []string `json:"roles"`
  381. }
  382. // A MessageAck stores data for the message ack websocket event.
  383. type MessageAck struct {
  384. MessageID string `json:"message_id"`
  385. ChannelID string `json:"channel_id"`
  386. }
  387. // An Ack is used to ack messages
  388. type Ack struct {
  389. Token string `json:"token"`
  390. }
  391. // A GuildIntegrationsUpdate stores data for the guild integrations update
  392. // websocket event.
  393. type GuildIntegrationsUpdate struct {
  394. GuildID string `json:"guild_id"`
  395. }
  396. // A GuildRole stores data for guild role websocket events.
  397. type GuildRole struct {
  398. Role *Role `json:"role"`
  399. GuildID string `json:"guild_id"`
  400. }
  401. // A GuildRoleDelete stores data for the guild role delete websocket event.
  402. type GuildRoleDelete struct {
  403. RoleID string `json:"role_id"`
  404. GuildID string `json:"guild_id"`
  405. }
  406. // A GuildBan stores data for a guild ban.
  407. type GuildBan struct {
  408. Reason string `json:"reason"`
  409. User *User `json:"user"`
  410. }
  411. // A GuildEmojisUpdate stores data for a guild emoji update event.
  412. type GuildEmojisUpdate struct {
  413. GuildID string `json:"guild_id"`
  414. Emojis []*Emoji `json:"emojis"`
  415. }
  416. // A GuildMembersChunk stores data for the Guild Members Chunk websocket event.
  417. type GuildMembersChunk struct {
  418. GuildID string `json:"guild_id"`
  419. Members []*Member `json:"members"`
  420. }
  421. // A GuildIntegration stores data for a guild integration.
  422. type GuildIntegration struct {
  423. ID string `json:"id"`
  424. Name string `json:"name"`
  425. Type string `json:"type"`
  426. Enabled bool `json:"enabled"`
  427. Syncing bool `json:"syncing"`
  428. RoleID string `json:"role_id"`
  429. ExpireBehavior int `json:"expire_behavior"`
  430. ExpireGracePeriod int `json:"expire_grace_period"`
  431. User *User `json:"user"`
  432. Account *GuildIntegrationAccount `json:"account"`
  433. SyncedAt int `json:"synced_at"`
  434. }
  435. // A GuildIntegrationAccount stores data for a guild integration account.
  436. type GuildIntegrationAccount struct {
  437. ID string `json:"id"`
  438. Name string `json:"name"`
  439. }
  440. // A GuildEmbed stores data for a guild embed.
  441. type GuildEmbed struct {
  442. Enabled bool `json:"enabled"`
  443. ChannelID string `json:"channel_id"`
  444. }
  445. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  446. type UserGuildSettingsChannelOverride struct {
  447. Muted bool `json:"muted"`
  448. MessageNotifications int `json:"message_notifications"`
  449. ChannelID string `json:"channel_id"`
  450. }
  451. // A UserGuildSettings stores data for a users guild settings.
  452. type UserGuildSettings struct {
  453. SupressEveryone bool `json:"suppress_everyone"`
  454. Muted bool `json:"muted"`
  455. MobilePush bool `json:"mobile_push"`
  456. MessageNotifications int `json:"message_notifications"`
  457. GuildID string `json:"guild_id"`
  458. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  459. }
  460. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  461. type UserGuildSettingsEdit struct {
  462. SupressEveryone bool `json:"suppress_everyone"`
  463. Muted bool `json:"muted"`
  464. MobilePush bool `json:"mobile_push"`
  465. MessageNotifications int `json:"message_notifications"`
  466. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  467. }
  468. // An APIErrorMessage is an api error message returned from discord
  469. type APIErrorMessage struct {
  470. Code int `json:"code"`
  471. Message string `json:"message"`
  472. }
  473. // ChannelPinsUpdate stores data for the channel pins update event
  474. type ChannelPinsUpdate struct {
  475. LastPinTimestamp string `json:"last_pin_timestamp"`
  476. ChannelID string `json:"channel_id"`
  477. }
  478. // Webhook stores the data for a webhook.
  479. type Webhook struct {
  480. ID string `json:"id"`
  481. GuildID string `json:"guild_id"`
  482. ChannelID string `json:"channel_id"`
  483. User *User `json:"user"`
  484. Name string `json:"name"`
  485. Avatar string `json:"avatar"`
  486. Token string `json:"token"`
  487. }
  488. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  489. type WebhookParams struct {
  490. Content string `json:"content,omitempty"`
  491. Username string `json:"username,omitempty"`
  492. AvatarURL string `json:"avatar_url,omitempty"`
  493. TTS bool `json:"tts,omitempty"`
  494. File string `json:"file,omitempty"`
  495. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  496. }
  497. // MessageReaction stores the data for a message reaction.
  498. type MessageReaction struct {
  499. UserID string `json:"user_id"`
  500. MessageID string `json:"message_id"`
  501. Emoji Emoji `json:"emoji"`
  502. ChannelID string `json:"channel_id"`
  503. }
  504. // Constants for the different bit offsets of text channel permissions
  505. const (
  506. PermissionReadMessages = 1 << (iota + 10)
  507. PermissionSendMessages
  508. PermissionSendTTSMessages
  509. PermissionManageMessages
  510. PermissionEmbedLinks
  511. PermissionAttachFiles
  512. PermissionReadMessageHistory
  513. PermissionMentionEveryone
  514. PermissionUseExternalEmojis
  515. )
  516. // Constants for the different bit offsets of voice permissions
  517. const (
  518. PermissionVoiceConnect = 1 << (iota + 20)
  519. PermissionVoiceSpeak
  520. PermissionVoiceMuteMembers
  521. PermissionVoiceDeafenMembers
  522. PermissionVoiceMoveMembers
  523. PermissionVoiceUseVAD
  524. )
  525. // Constants for general management.
  526. const (
  527. PermissionChangeNickname = 1 << (iota + 26)
  528. PermissionManageNicknames
  529. PermissionManageRoles
  530. PermissionManageWebhooks
  531. PermissionManageEmojis
  532. )
  533. // Constants for the different bit offsets of general permissions
  534. const (
  535. PermissionCreateInstantInvite = 1 << iota
  536. PermissionKickMembers
  537. PermissionBanMembers
  538. PermissionAdministrator
  539. PermissionManageChannels
  540. PermissionManageServer
  541. PermissionAllText = PermissionReadMessages |
  542. PermissionSendMessages |
  543. PermissionSendTTSMessages |
  544. PermissionManageMessages |
  545. PermissionEmbedLinks |
  546. PermissionAttachFiles |
  547. PermissionReadMessageHistory |
  548. PermissionMentionEveryone
  549. PermissionAllVoice = PermissionVoiceConnect |
  550. PermissionVoiceSpeak |
  551. PermissionVoiceMuteMembers |
  552. PermissionVoiceDeafenMembers |
  553. PermissionVoiceMoveMembers |
  554. PermissionVoiceUseVAD
  555. PermissionAllChannel = PermissionAllText |
  556. PermissionAllVoice |
  557. PermissionCreateInstantInvite |
  558. PermissionManageRoles |
  559. PermissionManageChannels
  560. PermissionAll = PermissionAllChannel |
  561. PermissionKickMembers |
  562. PermissionBanMembers |
  563. PermissionManageServer
  564. )