structs.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  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. ratelimiter *RateLimiter
  67. // sequence tracks the current gateway api websocket sequence number
  68. sequence int
  69. // stores sessions current Discord Gateway
  70. gateway string
  71. // stores session ID of current Gateway connection
  72. sessionID string
  73. // used to make sure gateway websocket writes do not happen concurrently
  74. wsMutex sync.Mutex
  75. }
  76. type rateLimitMutex struct {
  77. sync.Mutex
  78. url map[string]*sync.Mutex
  79. // bucket map[string]*sync.Mutex // TODO :)
  80. }
  81. // A Resumed struct holds the data received in a RESUMED event
  82. type Resumed struct {
  83. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  84. Trace []string `json:"_trace"`
  85. }
  86. // A VoiceRegion stores data for a specific voice region server.
  87. type VoiceRegion struct {
  88. ID string `json:"id"`
  89. Name string `json:"name"`
  90. Hostname string `json:"sample_hostname"`
  91. Port int `json:"sample_port"`
  92. }
  93. // A VoiceICE stores data for voice ICE servers.
  94. type VoiceICE struct {
  95. TTL string `json:"ttl"`
  96. Servers []*ICEServer `json:"servers"`
  97. }
  98. // A ICEServer stores data for a specific voice ICE server.
  99. type ICEServer struct {
  100. URL string `json:"url"`
  101. Username string `json:"username"`
  102. Credential string `json:"credential"`
  103. }
  104. // A Invite stores all data related to a specific Discord Guild or Channel invite.
  105. type Invite struct {
  106. Guild *Guild `json:"guild"`
  107. Channel *Channel `json:"channel"`
  108. Inviter *User `json:"inviter"`
  109. Code string `json:"code"`
  110. CreatedAt Timestamp `json:"created_at"`
  111. MaxAge int `json:"max_age"`
  112. Uses int `json:"uses"`
  113. MaxUses int `json:"max_uses"`
  114. XkcdPass string `json:"xkcdpass"`
  115. Revoked bool `json:"revoked"`
  116. Temporary bool `json:"temporary"`
  117. }
  118. // A Channel holds all data related to an individual Discord channel.
  119. type Channel struct {
  120. ID string `json:"id"`
  121. GuildID string `json:"guild_id"`
  122. Name string `json:"name"`
  123. Topic string `json:"topic"`
  124. Type string `json:"type"`
  125. LastMessageID string `json:"last_message_id"`
  126. Position int `json:"position"`
  127. Bitrate int `json:"bitrate"`
  128. IsPrivate bool `json:"is_private"`
  129. Recipient *User `json:"recipient"`
  130. Messages []*Message `json:"-"`
  131. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites"`
  132. }
  133. // A PermissionOverwrite holds permission overwrite data for a Channel
  134. type PermissionOverwrite struct {
  135. ID string `json:"id"`
  136. Type string `json:"type"`
  137. Deny int `json:"deny"`
  138. Allow int `json:"allow"`
  139. }
  140. // Emoji struct holds data related to Emoji's
  141. type Emoji struct {
  142. ID string `json:"id"`
  143. Name string `json:"name"`
  144. Roles []string `json:"roles"`
  145. Managed bool `json:"managed"`
  146. RequireColons bool `json:"require_colons"`
  147. }
  148. // APIName returns an correctly formatted API name for use in the MessageReactions endpoints.
  149. func (e *Emoji) APIName() string {
  150. if e.ID != "" && e.Name != "" {
  151. return e.Name + ":" + e.ID
  152. }
  153. if e.Name != "" {
  154. return e.Name
  155. }
  156. return e.ID
  157. }
  158. // VerificationLevel type defination
  159. type VerificationLevel int
  160. // Constants for VerificationLevel levels from 0 to 3 inclusive
  161. const (
  162. VerificationLevelNone VerificationLevel = iota
  163. VerificationLevelLow
  164. VerificationLevelMedium
  165. VerificationLevelHigh
  166. )
  167. // A Guild holds all data related to a specific Discord Guild. Guilds are also
  168. // sometimes referred to as Servers in the Discord client.
  169. type Guild struct {
  170. ID string `json:"id"`
  171. Name string `json:"name"`
  172. Icon string `json:"icon"`
  173. Region string `json:"region"`
  174. AfkChannelID string `json:"afk_channel_id"`
  175. EmbedChannelID string `json:"embed_channel_id"`
  176. OwnerID string `json:"owner_id"`
  177. JoinedAt Timestamp `json:"joined_at"`
  178. Splash string `json:"splash"`
  179. AfkTimeout int `json:"afk_timeout"`
  180. VerificationLevel VerificationLevel `json:"verification_level"`
  181. EmbedEnabled bool `json:"embed_enabled"`
  182. Large bool `json:"large"` // ??
  183. DefaultMessageNotifications int `json:"default_message_notifications"`
  184. Roles []*Role `json:"roles"`
  185. Emojis []*Emoji `json:"emojis"`
  186. Members []*Member `json:"members"`
  187. Presences []*Presence `json:"presences"`
  188. Channels []*Channel `json:"channels"`
  189. VoiceStates []*VoiceState `json:"voice_states"`
  190. Unavailable bool `json:"unavailable"`
  191. }
  192. // A UserGuild holds a brief version of a Guild
  193. type UserGuild struct {
  194. ID string `json:"id"`
  195. Name string `json:"name"`
  196. Icon string `json:"icon"`
  197. Owner bool `json:"owner"`
  198. Permissions int `json:"permissions"`
  199. }
  200. // A GuildParams stores all the data needed to update discord guild settings
  201. type GuildParams struct {
  202. Name string `json:"name"`
  203. Region string `json:"region"`
  204. VerificationLevel *VerificationLevel `json:"verification_level"`
  205. }
  206. // A Role stores information about Discord guild member roles.
  207. type Role struct {
  208. ID string `json:"id"`
  209. Name string `json:"name"`
  210. Managed bool `json:"managed"`
  211. Mentionable bool `json:"mentionable"`
  212. Hoist bool `json:"hoist"`
  213. Color int `json:"color"`
  214. Position int `json:"position"`
  215. Permissions int `json:"permissions"`
  216. }
  217. // A VoiceState stores the voice states of Guilds
  218. type VoiceState struct {
  219. UserID string `json:"user_id"`
  220. SessionID string `json:"session_id"`
  221. ChannelID string `json:"channel_id"`
  222. GuildID string `json:"guild_id"`
  223. Suppress bool `json:"suppress"`
  224. SelfMute bool `json:"self_mute"`
  225. SelfDeaf bool `json:"self_deaf"`
  226. Mute bool `json:"mute"`
  227. Deaf bool `json:"deaf"`
  228. }
  229. // A Presence stores the online, offline, or idle and game status of Guild members.
  230. type Presence struct {
  231. User *User `json:"user"`
  232. Status Status `json:"status"`
  233. Game *Game `json:"game"`
  234. }
  235. // A Game struct holds the name of the "playing .." game for a user
  236. type Game struct {
  237. Name string `json:"name"`
  238. Type int `json:"type"`
  239. URL string `json:"url"`
  240. }
  241. // A Member stores user information for Guild members.
  242. type Member struct {
  243. GuildID string `json:"guild_id"`
  244. JoinedAt string `json:"joined_at"`
  245. Nick string `json:"nick"`
  246. Deaf bool `json:"deaf"`
  247. Mute bool `json:"mute"`
  248. User *User `json:"user"`
  249. Roles []string `json:"roles"`
  250. }
  251. // A User stores all data for an individual Discord user.
  252. type User struct {
  253. ID string `json:"id"`
  254. Email string `json:"email"`
  255. Username string `json:"username"`
  256. Avatar string `json:"Avatar"`
  257. Discriminator string `json:"discriminator"`
  258. Token string `json:"token"`
  259. Verified bool `json:"verified"`
  260. MFAEnabled bool `json:"mfa_enabled"`
  261. Bot bool `json:"bot"`
  262. }
  263. // A Settings stores data for a specific users Discord client settings.
  264. type Settings struct {
  265. RenderEmbeds bool `json:"render_embeds"`
  266. InlineEmbedMedia bool `json:"inline_embed_media"`
  267. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  268. EnableTtsCommand bool `json:"enable_tts_command"`
  269. MessageDisplayCompact bool `json:"message_display_compact"`
  270. ShowCurrentGame bool `json:"show_current_game"`
  271. ConvertEmoticons bool `json:"convert_emoticons"`
  272. Locale string `json:"locale"`
  273. Theme string `json:"theme"`
  274. GuildPositions []string `json:"guild_positions"`
  275. RestrictedGuilds []string `json:"restricted_guilds"`
  276. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  277. Status Status `json:"status"`
  278. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  279. DeveloperMode bool `json:"developer_mode"`
  280. }
  281. // Status type defination
  282. type Status string
  283. // Constants for Status with the different current available status
  284. const (
  285. StatusOnline Status = "online"
  286. StatusIdle Status = "idle"
  287. StatusDoNotDisturb Status = "dnd"
  288. StatusInvisible Status = "invisible"
  289. StatusOffline Status = "offline"
  290. )
  291. // FriendSourceFlags stores ... TODO :)
  292. type FriendSourceFlags struct {
  293. All bool `json:"all"`
  294. MutualGuilds bool `json:"mutual_guilds"`
  295. MutualFriends bool `json:"mutual_friends"`
  296. }
  297. // An Event provides a basic initial struct for all websocket event.
  298. type Event struct {
  299. Operation int `json:"op"`
  300. Sequence int `json:"s"`
  301. Type string `json:"t"`
  302. RawData json.RawMessage `json:"d"`
  303. Struct interface{} `json:"-"`
  304. }
  305. // A Ready stores all data for the websocket READY event.
  306. type Ready struct {
  307. Version int `json:"v"`
  308. SessionID string `json:"session_id"`
  309. HeartbeatInterval time.Duration `json:"heartbeat_interval"`
  310. User *User `json:"user"`
  311. ReadState []*ReadState `json:"read_state"`
  312. PrivateChannels []*Channel `json:"private_channels"`
  313. Guilds []*Guild `json:"guilds"`
  314. // Undocumented fields
  315. Settings *Settings `json:"user_settings"`
  316. UserGuildSettings []*UserGuildSettings `json:"user_guild_settings"`
  317. Relationships []*Relationship `json:"relationships"`
  318. Presences []*Presence `json:"presences"`
  319. }
  320. // A Relationship between the logged in user and Relationship.User
  321. type Relationship struct {
  322. User *User `json:"user"`
  323. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  324. ID string `json:"id"`
  325. }
  326. // A TooManyRequests struct holds information received from Discord
  327. // when receiving a HTTP 429 response.
  328. type TooManyRequests struct {
  329. Bucket string `json:"bucket"`
  330. Message string `json:"message"`
  331. RetryAfter time.Duration `json:"retry_after"`
  332. }
  333. // A ReadState stores data on the read state of channels.
  334. type ReadState struct {
  335. MentionCount int `json:"mention_count"`
  336. LastMessageID string `json:"last_message_id"`
  337. ID string `json:"id"`
  338. }
  339. // A TypingStart stores data for the typing start websocket event.
  340. type TypingStart struct {
  341. UserID string `json:"user_id"`
  342. ChannelID string `json:"channel_id"`
  343. Timestamp int `json:"timestamp"`
  344. }
  345. // A PresenceUpdate stores data for the presence update websocket event.
  346. type PresenceUpdate struct {
  347. Presence
  348. GuildID string `json:"guild_id"`
  349. Roles []string `json:"roles"`
  350. }
  351. // A MessageAck stores data for the message ack websocket event.
  352. type MessageAck struct {
  353. MessageID string `json:"message_id"`
  354. ChannelID string `json:"channel_id"`
  355. }
  356. // An Ack is used to ack messages
  357. type Ack struct {
  358. Token string `json:"token"`
  359. }
  360. // A GuildIntegrationsUpdate stores data for the guild integrations update
  361. // websocket event.
  362. type GuildIntegrationsUpdate struct {
  363. GuildID string `json:"guild_id"`
  364. }
  365. // A GuildRole stores data for guild role websocket events.
  366. type GuildRole struct {
  367. Role *Role `json:"role"`
  368. GuildID string `json:"guild_id"`
  369. }
  370. // A GuildRoleDelete stores data for the guild role delete websocket event.
  371. type GuildRoleDelete struct {
  372. RoleID string `json:"role_id"`
  373. GuildID string `json:"guild_id"`
  374. }
  375. // A GuildBan stores data for a guild ban.
  376. type GuildBan struct {
  377. Reason string `json:"reason"`
  378. User *User `json:"user"`
  379. }
  380. // A GuildEmojisUpdate stores data for a guild emoji update event.
  381. type GuildEmojisUpdate struct {
  382. GuildID string `json:"guild_id"`
  383. Emojis []*Emoji `json:"emojis"`
  384. }
  385. // A GuildMembersChunk stores data for the Guild Members Chunk websocket event.
  386. type GuildMembersChunk struct {
  387. GuildID string `json:"guild_id"`
  388. Members []*Member `json:"members"`
  389. }
  390. // A GuildIntegration stores data for a guild integration.
  391. type GuildIntegration struct {
  392. ID string `json:"id"`
  393. Name string `json:"name"`
  394. Type string `json:"type"`
  395. Enabled bool `json:"enabled"`
  396. Syncing bool `json:"syncing"`
  397. RoleID string `json:"role_id"`
  398. ExpireBehavior int `json:"expire_behavior"`
  399. ExpireGracePeriod int `json:"expire_grace_period"`
  400. User *User `json:"user"`
  401. Account *GuildIntegrationAccount `json:"account"`
  402. SyncedAt int `json:"synced_at"`
  403. }
  404. // A GuildIntegrationAccount stores data for a guild integration account.
  405. type GuildIntegrationAccount struct {
  406. ID string `json:"id"`
  407. Name string `json:"name"`
  408. }
  409. // A GuildEmbed stores data for a guild embed.
  410. type GuildEmbed struct {
  411. Enabled bool `json:"enabled"`
  412. ChannelID string `json:"channel_id"`
  413. }
  414. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  415. type UserGuildSettingsChannelOverride struct {
  416. Muted bool `json:"muted"`
  417. MessageNotifications int `json:"message_notifications"`
  418. ChannelID string `json:"channel_id"`
  419. }
  420. // A UserGuildSettings stores data for a users guild settings.
  421. type UserGuildSettings struct {
  422. SupressEveryone bool `json:"suppress_everyone"`
  423. Muted bool `json:"muted"`
  424. MobilePush bool `json:"mobile_push"`
  425. MessageNotifications int `json:"message_notifications"`
  426. GuildID string `json:"guild_id"`
  427. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  428. }
  429. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  430. type UserGuildSettingsEdit struct {
  431. SupressEveryone bool `json:"suppress_everyone"`
  432. Muted bool `json:"muted"`
  433. MobilePush bool `json:"mobile_push"`
  434. MessageNotifications int `json:"message_notifications"`
  435. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  436. }
  437. // An APIErrorMessage is an api error message returned from discord
  438. type APIErrorMessage struct {
  439. Code int `json:"code"`
  440. Message string `json:"message"`
  441. }
  442. // ChannelPinsUpdate stores data for the channel pins update event
  443. type ChannelPinsUpdate struct {
  444. LastPinTimestamp string `json:"last_pin_timestamp"`
  445. ChannelID string `json:"channel_id"`
  446. }
  447. // Webhook stores the data for a webhook.
  448. type Webhook struct {
  449. ID string `json:"id"`
  450. GuildID string `json:"guild_id"`
  451. ChannelID string `json:"channel_id"`
  452. User *User `json:"user"`
  453. Name string `json:"name"`
  454. Avatar string `json:"avatar"`
  455. Token string `json:"token"`
  456. }
  457. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  458. type WebhookParams struct {
  459. Content string `json:"content,omitempty"`
  460. Username string `json:"username,omitempty"`
  461. AvatarURL string `json:"avatar_url,omitempty"`
  462. TTS bool `json:"tts,omitempty"`
  463. File string `json:"file,omitempty"`
  464. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  465. }
  466. // MessageReaction stores the data for a message reaction.
  467. type MessageReaction struct {
  468. UserID string `json:"user_id"`
  469. MessageID string `json:"message_id"`
  470. Emoji Emoji `json:"emoji"`
  471. ChannelID string `json:"channel_id"`
  472. }
  473. // Constants for the different bit offsets of text channel permissions
  474. const (
  475. PermissionReadMessages = 1 << (iota + 10)
  476. PermissionSendMessages
  477. PermissionSendTTSMessages
  478. PermissionManageMessages
  479. PermissionEmbedLinks
  480. PermissionAttachFiles
  481. PermissionReadMessageHistory
  482. PermissionMentionEveryone
  483. PermissionUseExternalEmojis
  484. )
  485. // Constants for the different bit offsets of voice permissions
  486. const (
  487. PermissionVoiceConnect = 1 << (iota + 20)
  488. PermissionVoiceSpeak
  489. PermissionVoiceMuteMembers
  490. PermissionVoiceDeafenMembers
  491. PermissionVoiceMoveMembers
  492. PermissionVoiceUseVAD
  493. )
  494. // Constants for general management.
  495. const (
  496. PermissionChangeNickname = 1 << (iota + 26)
  497. PermissionManageNicknames
  498. PermissionManageRoles
  499. PermissionManageWebhooks
  500. PermissionManageEmojis
  501. )
  502. // Constants for the different bit offsets of general permissions
  503. const (
  504. PermissionCreateInstantInvite = 1 << iota
  505. PermissionKickMembers
  506. PermissionBanMembers
  507. PermissionAdministrator
  508. PermissionManageChannels
  509. PermissionManageServer
  510. PermissionAllText = PermissionReadMessages |
  511. PermissionSendMessages |
  512. PermissionSendTTSMessages |
  513. PermissionManageMessages |
  514. PermissionEmbedLinks |
  515. PermissionAttachFiles |
  516. PermissionReadMessageHistory |
  517. PermissionMentionEveryone
  518. PermissionAllVoice = PermissionVoiceConnect |
  519. PermissionVoiceSpeak |
  520. PermissionVoiceMuteMembers |
  521. PermissionVoiceDeafenMembers |
  522. PermissionVoiceMoveMembers |
  523. PermissionVoiceUseVAD
  524. PermissionAllChannel = PermissionAllText |
  525. PermissionAllVoice |
  526. PermissionCreateInstantInvite |
  527. PermissionManageRoles |
  528. PermissionManageChannels
  529. PermissionAll = PermissionAllChannel |
  530. PermissionKickMembers |
  531. PermissionBanMembers |
  532. PermissionManageServer
  533. )