structs.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. func (g *Game) UnmarshalJSON(bytes []byte) error {
  246. temp := &struct {
  247. Name string `json:"name"`
  248. Type json.RawMessage `json:"type"`
  249. URL string `json:"url"`
  250. }{}
  251. err := json.Unmarshal(bytes, temp)
  252. if err != nil {
  253. return err
  254. }
  255. g.Name = temp.Name
  256. g.URL = temp.URL
  257. if temp.Type != nil {
  258. err = json.Unmarshal(temp.Type, &g.Type)
  259. if err == nil {
  260. return nil
  261. }
  262. s := ""
  263. err = json.Unmarshal(temp.Type, &s)
  264. if err == nil {
  265. g.Type, err = strconv.Atoi(s)
  266. }
  267. return err
  268. }
  269. return nil
  270. }
  271. // A Member stores user information for Guild members.
  272. type Member struct {
  273. GuildID string `json:"guild_id"`
  274. JoinedAt string `json:"joined_at"`
  275. Nick string `json:"nick"`
  276. Deaf bool `json:"deaf"`
  277. Mute bool `json:"mute"`
  278. User *User `json:"user"`
  279. Roles []string `json:"roles"`
  280. }
  281. // A User stores all data for an individual Discord user.
  282. type User struct {
  283. ID string `json:"id"`
  284. Email string `json:"email"`
  285. Username string `json:"username"`
  286. Avatar string `json:"Avatar"`
  287. Discriminator string `json:"discriminator"`
  288. Token string `json:"token"`
  289. Verified bool `json:"verified"`
  290. MFAEnabled bool `json:"mfa_enabled"`
  291. Bot bool `json:"bot"`
  292. }
  293. // A Settings stores data for a specific users Discord client settings.
  294. type Settings struct {
  295. RenderEmbeds bool `json:"render_embeds"`
  296. InlineEmbedMedia bool `json:"inline_embed_media"`
  297. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  298. EnableTtsCommand bool `json:"enable_tts_command"`
  299. MessageDisplayCompact bool `json:"message_display_compact"`
  300. ShowCurrentGame bool `json:"show_current_game"`
  301. ConvertEmoticons bool `json:"convert_emoticons"`
  302. Locale string `json:"locale"`
  303. Theme string `json:"theme"`
  304. GuildPositions []string `json:"guild_positions"`
  305. RestrictedGuilds []string `json:"restricted_guilds"`
  306. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  307. Status Status `json:"status"`
  308. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  309. DeveloperMode bool `json:"developer_mode"`
  310. }
  311. // Status type defination
  312. type Status string
  313. // Constants for Status with the different current available status
  314. const (
  315. StatusOnline Status = "online"
  316. StatusIdle Status = "idle"
  317. StatusDoNotDisturb Status = "dnd"
  318. StatusInvisible Status = "invisible"
  319. StatusOffline Status = "offline"
  320. )
  321. // FriendSourceFlags stores ... TODO :)
  322. type FriendSourceFlags struct {
  323. All bool `json:"all"`
  324. MutualGuilds bool `json:"mutual_guilds"`
  325. MutualFriends bool `json:"mutual_friends"`
  326. }
  327. // An Event provides a basic initial struct for all websocket event.
  328. type Event struct {
  329. Operation int `json:"op"`
  330. Sequence int `json:"s"`
  331. Type string `json:"t"`
  332. RawData json.RawMessage `json:"d"`
  333. Struct interface{} `json:"-"`
  334. }
  335. // A Ready stores all data for the websocket READY event.
  336. type Ready struct {
  337. Version int `json:"v"`
  338. SessionID string `json:"session_id"`
  339. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  340. User *User `json:"user"`
  341. ReadState []*ReadState `json:"read_state"`
  342. PrivateChannels []*Channel `json:"private_channels"`
  343. Guilds []*Guild `json:"guilds"`
  344. // Undocumented fields
  345. Settings *Settings `json:"user_settings"`
  346. UserGuildSettings []*UserGuildSettings `json:"user_guild_settings"`
  347. Relationships []*Relationship `json:"relationships"`
  348. Presences []*Presence `json:"presences"`
  349. }
  350. // A Relationship between the logged in user and Relationship.User
  351. type Relationship struct {
  352. User *User `json:"user"`
  353. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  354. ID string `json:"id"`
  355. }
  356. // A TooManyRequests struct holds information received from Discord
  357. // when receiving a HTTP 429 response.
  358. type TooManyRequests struct {
  359. Bucket string `json:"bucket"`
  360. Message string `json:"message"`
  361. RetryAfter time.Duration `json:"retry_after"`
  362. }
  363. // A ReadState stores data on the read state of channels.
  364. type ReadState struct {
  365. MentionCount int `json:"mention_count"`
  366. LastMessageID string `json:"last_message_id"`
  367. ID string `json:"id"`
  368. }
  369. // A TypingStart stores data for the typing start websocket event.
  370. type TypingStart struct {
  371. UserID string `json:"user_id"`
  372. ChannelID string `json:"channel_id"`
  373. Timestamp int `json:"timestamp"`
  374. }
  375. // A PresenceUpdate stores data for the presence update websocket event.
  376. type PresenceUpdate struct {
  377. Presence
  378. GuildID string `json:"guild_id"`
  379. Roles []string `json:"roles"`
  380. }
  381. // A MessageAck stores data for the message ack websocket event.
  382. type MessageAck struct {
  383. MessageID string `json:"message_id"`
  384. ChannelID string `json:"channel_id"`
  385. }
  386. // An Ack is used to ack messages
  387. type Ack struct {
  388. Token string `json:"token"`
  389. }
  390. // A GuildIntegrationsUpdate stores data for the guild integrations update
  391. // websocket event.
  392. type GuildIntegrationsUpdate struct {
  393. GuildID string `json:"guild_id"`
  394. }
  395. // A GuildRole stores data for guild role websocket events.
  396. type GuildRole struct {
  397. Role *Role `json:"role"`
  398. GuildID string `json:"guild_id"`
  399. }
  400. // A GuildRoleDelete stores data for the guild role delete websocket event.
  401. type GuildRoleDelete struct {
  402. RoleID string `json:"role_id"`
  403. GuildID string `json:"guild_id"`
  404. }
  405. // A GuildBan stores data for a guild ban.
  406. type GuildBan struct {
  407. Reason string `json:"reason"`
  408. User *User `json:"user"`
  409. }
  410. // A GuildEmojisUpdate stores data for a guild emoji update event.
  411. type GuildEmojisUpdate struct {
  412. GuildID string `json:"guild_id"`
  413. Emojis []*Emoji `json:"emojis"`
  414. }
  415. // A GuildMembersChunk stores data for the Guild Members Chunk websocket event.
  416. type GuildMembersChunk struct {
  417. GuildID string `json:"guild_id"`
  418. Members []*Member `json:"members"`
  419. }
  420. // A GuildIntegration stores data for a guild integration.
  421. type GuildIntegration struct {
  422. ID string `json:"id"`
  423. Name string `json:"name"`
  424. Type string `json:"type"`
  425. Enabled bool `json:"enabled"`
  426. Syncing bool `json:"syncing"`
  427. RoleID string `json:"role_id"`
  428. ExpireBehavior int `json:"expire_behavior"`
  429. ExpireGracePeriod int `json:"expire_grace_period"`
  430. User *User `json:"user"`
  431. Account *GuildIntegrationAccount `json:"account"`
  432. SyncedAt int `json:"synced_at"`
  433. }
  434. // A GuildIntegrationAccount stores data for a guild integration account.
  435. type GuildIntegrationAccount struct {
  436. ID string `json:"id"`
  437. Name string `json:"name"`
  438. }
  439. // A GuildEmbed stores data for a guild embed.
  440. type GuildEmbed struct {
  441. Enabled bool `json:"enabled"`
  442. ChannelID string `json:"channel_id"`
  443. }
  444. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  445. type UserGuildSettingsChannelOverride struct {
  446. Muted bool `json:"muted"`
  447. MessageNotifications int `json:"message_notifications"`
  448. ChannelID string `json:"channel_id"`
  449. }
  450. // A UserGuildSettings stores data for a users guild settings.
  451. type UserGuildSettings struct {
  452. SupressEveryone bool `json:"suppress_everyone"`
  453. Muted bool `json:"muted"`
  454. MobilePush bool `json:"mobile_push"`
  455. MessageNotifications int `json:"message_notifications"`
  456. GuildID string `json:"guild_id"`
  457. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  458. }
  459. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  460. type UserGuildSettingsEdit struct {
  461. SupressEveryone bool `json:"suppress_everyone"`
  462. Muted bool `json:"muted"`
  463. MobilePush bool `json:"mobile_push"`
  464. MessageNotifications int `json:"message_notifications"`
  465. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  466. }
  467. // An APIErrorMessage is an api error message returned from discord
  468. type APIErrorMessage struct {
  469. Code int `json:"code"`
  470. Message string `json:"message"`
  471. }
  472. // ChannelPinsUpdate stores data for the channel pins update event
  473. type ChannelPinsUpdate struct {
  474. LastPinTimestamp string `json:"last_pin_timestamp"`
  475. ChannelID string `json:"channel_id"`
  476. }
  477. // Webhook stores the data for a webhook.
  478. type Webhook struct {
  479. ID string `json:"id"`
  480. GuildID string `json:"guild_id"`
  481. ChannelID string `json:"channel_id"`
  482. User *User `json:"user"`
  483. Name string `json:"name"`
  484. Avatar string `json:"avatar"`
  485. Token string `json:"token"`
  486. }
  487. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  488. type WebhookParams struct {
  489. Content string `json:"content,omitempty"`
  490. Username string `json:"username,omitempty"`
  491. AvatarURL string `json:"avatar_url,omitempty"`
  492. TTS bool `json:"tts,omitempty"`
  493. File string `json:"file,omitempty"`
  494. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  495. }
  496. // MessageReaction stores the data for a message reaction.
  497. type MessageReaction struct {
  498. UserID string `json:"user_id"`
  499. MessageID string `json:"message_id"`
  500. Emoji Emoji `json:"emoji"`
  501. ChannelID string `json:"channel_id"`
  502. }
  503. // Constants for the different bit offsets of text channel permissions
  504. const (
  505. PermissionReadMessages = 1 << (iota + 10)
  506. PermissionSendMessages
  507. PermissionSendTTSMessages
  508. PermissionManageMessages
  509. PermissionEmbedLinks
  510. PermissionAttachFiles
  511. PermissionReadMessageHistory
  512. PermissionMentionEveryone
  513. PermissionUseExternalEmojis
  514. )
  515. // Constants for the different bit offsets of voice permissions
  516. const (
  517. PermissionVoiceConnect = 1 << (iota + 20)
  518. PermissionVoiceSpeak
  519. PermissionVoiceMuteMembers
  520. PermissionVoiceDeafenMembers
  521. PermissionVoiceMoveMembers
  522. PermissionVoiceUseVAD
  523. )
  524. // Constants for general management.
  525. const (
  526. PermissionChangeNickname = 1 << (iota + 26)
  527. PermissionManageNicknames
  528. PermissionManageRoles
  529. PermissionManageWebhooks
  530. PermissionManageEmojis
  531. )
  532. // Constants for the different bit offsets of general permissions
  533. const (
  534. PermissionCreateInstantInvite = 1 << iota
  535. PermissionKickMembers
  536. PermissionBanMembers
  537. PermissionAdministrator
  538. PermissionManageChannels
  539. PermissionManageServer
  540. PermissionAllText = PermissionReadMessages |
  541. PermissionSendMessages |
  542. PermissionSendTTSMessages |
  543. PermissionManageMessages |
  544. PermissionEmbedLinks |
  545. PermissionAttachFiles |
  546. PermissionReadMessageHistory |
  547. PermissionMentionEveryone
  548. PermissionAllVoice = PermissionVoiceConnect |
  549. PermissionVoiceSpeak |
  550. PermissionVoiceMuteMembers |
  551. PermissionVoiceDeafenMembers |
  552. PermissionVoiceMoveMembers |
  553. PermissionVoiceUseVAD
  554. PermissionAllChannel = PermissionAllText |
  555. PermissionAllVoice |
  556. PermissionCreateInstantInvite |
  557. PermissionManageRoles |
  558. PermissionManageChannels
  559. PermissionAll = PermissionAllChannel |
  560. PermissionKickMembers |
  561. PermissionBanMembers |
  562. PermissionManageServer
  563. )