structs.go 18 KB

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