structs.go 20 KB

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