structs.go 20 KB

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