structs.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. type Roles []*Role
  211. func (r Roles) Len() int {
  212. return len(r)
  213. }
  214. func (r Roles) Less(i, j int) bool {
  215. return r[i].Position > r[j].Position
  216. }
  217. func (r Roles) Swap(i, j int) {
  218. r[i], r[j] = r[j], r[i]
  219. }
  220. // A VoiceState stores the voice states of Guilds
  221. type VoiceState struct {
  222. UserID string `json:"user_id"`
  223. SessionID string `json:"session_id"`
  224. ChannelID string `json:"channel_id"`
  225. GuildID string `json:"guild_id"`
  226. Suppress bool `json:"suppress"`
  227. SelfMute bool `json:"self_mute"`
  228. SelfDeaf bool `json:"self_deaf"`
  229. Mute bool `json:"mute"`
  230. Deaf bool `json:"deaf"`
  231. }
  232. // A Presence stores the online, offline, or idle and game status of Guild members.
  233. type Presence struct {
  234. User *User `json:"user"`
  235. Status Status `json:"status"`
  236. Game *Game `json:"game"`
  237. Nick string `json:"nick"`
  238. Roles []string `json:"roles"`
  239. }
  240. // A Game struct holds the name of the "playing .." game for a user
  241. type Game struct {
  242. Name string `json:"name"`
  243. Type int `json:"type"`
  244. URL string `json:"url"`
  245. }
  246. // UnmarshalJSON unmarshals json to Game struct
  247. func (g *Game) UnmarshalJSON(bytes []byte) error {
  248. temp := &struct {
  249. Name string `json:"name"`
  250. Type json.RawMessage `json:"type"`
  251. URL string `json:"url"`
  252. }{}
  253. err := json.Unmarshal(bytes, temp)
  254. if err != nil {
  255. return err
  256. }
  257. g.Name = temp.Name
  258. g.URL = temp.URL
  259. if temp.Type != nil {
  260. err = json.Unmarshal(temp.Type, &g.Type)
  261. if err == nil {
  262. return nil
  263. }
  264. s := ""
  265. err = json.Unmarshal(temp.Type, &s)
  266. if err == nil {
  267. g.Type, err = strconv.Atoi(s)
  268. }
  269. return err
  270. }
  271. return nil
  272. }
  273. // A Member stores user information for Guild members.
  274. type Member struct {
  275. GuildID string `json:"guild_id"`
  276. JoinedAt string `json:"joined_at"`
  277. Nick string `json:"nick"`
  278. Deaf bool `json:"deaf"`
  279. Mute bool `json:"mute"`
  280. User *User `json:"user"`
  281. Roles []string `json:"roles"`
  282. }
  283. // A User stores all data for an individual Discord user.
  284. type User struct {
  285. ID string `json:"id"`
  286. Email string `json:"email"`
  287. Username string `json:"username"`
  288. Avatar string `json:"Avatar"`
  289. Discriminator string `json:"discriminator"`
  290. Token string `json:"token"`
  291. Verified bool `json:"verified"`
  292. MFAEnabled bool `json:"mfa_enabled"`
  293. Bot bool `json:"bot"`
  294. }
  295. // A Settings stores data for a specific users Discord client settings.
  296. type Settings struct {
  297. RenderEmbeds bool `json:"render_embeds"`
  298. InlineEmbedMedia bool `json:"inline_embed_media"`
  299. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  300. EnableTtsCommand bool `json:"enable_tts_command"`
  301. MessageDisplayCompact bool `json:"message_display_compact"`
  302. ShowCurrentGame bool `json:"show_current_game"`
  303. ConvertEmoticons bool `json:"convert_emoticons"`
  304. Locale string `json:"locale"`
  305. Theme string `json:"theme"`
  306. GuildPositions []string `json:"guild_positions"`
  307. RestrictedGuilds []string `json:"restricted_guilds"`
  308. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  309. Status Status `json:"status"`
  310. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  311. DeveloperMode bool `json:"developer_mode"`
  312. }
  313. // Status type defination
  314. type Status string
  315. // Constants for Status with the different current available status
  316. const (
  317. StatusOnline Status = "online"
  318. StatusIdle Status = "idle"
  319. StatusDoNotDisturb Status = "dnd"
  320. StatusInvisible Status = "invisible"
  321. StatusOffline Status = "offline"
  322. )
  323. // FriendSourceFlags stores ... TODO :)
  324. type FriendSourceFlags struct {
  325. All bool `json:"all"`
  326. MutualGuilds bool `json:"mutual_guilds"`
  327. MutualFriends bool `json:"mutual_friends"`
  328. }
  329. // A Relationship between the logged in user and Relationship.User
  330. type Relationship struct {
  331. User *User `json:"user"`
  332. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  333. ID string `json:"id"`
  334. }
  335. // A TooManyRequests struct holds information received from Discord
  336. // when receiving a HTTP 429 response.
  337. type TooManyRequests struct {
  338. Bucket string `json:"bucket"`
  339. Message string `json:"message"`
  340. RetryAfter time.Duration `json:"retry_after"`
  341. }
  342. // A ReadState stores data on the read state of channels.
  343. type ReadState struct {
  344. MentionCount int `json:"mention_count"`
  345. LastMessageID string `json:"last_message_id"`
  346. ID string `json:"id"`
  347. }
  348. // An Ack is used to ack messages
  349. type Ack struct {
  350. Token string `json:"token"`
  351. }
  352. // A GuildRole stores data for guild roles.
  353. type GuildRole struct {
  354. Role *Role `json:"role"`
  355. GuildID string `json:"guild_id"`
  356. }
  357. // A GuildBan stores data for a guild ban.
  358. type GuildBan struct {
  359. Reason string `json:"reason"`
  360. User *User `json:"user"`
  361. }
  362. // A GuildIntegration stores data for a guild integration.
  363. type GuildIntegration struct {
  364. ID string `json:"id"`
  365. Name string `json:"name"`
  366. Type string `json:"type"`
  367. Enabled bool `json:"enabled"`
  368. Syncing bool `json:"syncing"`
  369. RoleID string `json:"role_id"`
  370. ExpireBehavior int `json:"expire_behavior"`
  371. ExpireGracePeriod int `json:"expire_grace_period"`
  372. User *User `json:"user"`
  373. Account *GuildIntegrationAccount `json:"account"`
  374. SyncedAt int `json:"synced_at"`
  375. }
  376. // A GuildIntegrationAccount stores data for a guild integration account.
  377. type GuildIntegrationAccount struct {
  378. ID string `json:"id"`
  379. Name string `json:"name"`
  380. }
  381. // A GuildEmbed stores data for a guild embed.
  382. type GuildEmbed struct {
  383. Enabled bool `json:"enabled"`
  384. ChannelID string `json:"channel_id"`
  385. }
  386. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  387. type UserGuildSettingsChannelOverride struct {
  388. Muted bool `json:"muted"`
  389. MessageNotifications int `json:"message_notifications"`
  390. ChannelID string `json:"channel_id"`
  391. }
  392. // A UserGuildSettings stores data for a users guild settings.
  393. type UserGuildSettings struct {
  394. SupressEveryone bool `json:"suppress_everyone"`
  395. Muted bool `json:"muted"`
  396. MobilePush bool `json:"mobile_push"`
  397. MessageNotifications int `json:"message_notifications"`
  398. GuildID string `json:"guild_id"`
  399. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  400. }
  401. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  402. type UserGuildSettingsEdit struct {
  403. SupressEveryone bool `json:"suppress_everyone"`
  404. Muted bool `json:"muted"`
  405. MobilePush bool `json:"mobile_push"`
  406. MessageNotifications int `json:"message_notifications"`
  407. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  408. }
  409. // An APIErrorMessage is an api error message returned from discord
  410. type APIErrorMessage struct {
  411. Code int `json:"code"`
  412. Message string `json:"message"`
  413. }
  414. // Webhook stores the data for a webhook.
  415. type Webhook struct {
  416. ID string `json:"id"`
  417. GuildID string `json:"guild_id"`
  418. ChannelID string `json:"channel_id"`
  419. User *User `json:"user"`
  420. Name string `json:"name"`
  421. Avatar string `json:"avatar"`
  422. Token string `json:"token"`
  423. }
  424. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  425. type WebhookParams struct {
  426. Content string `json:"content,omitempty"`
  427. Username string `json:"username,omitempty"`
  428. AvatarURL string `json:"avatar_url,omitempty"`
  429. TTS bool `json:"tts,omitempty"`
  430. File string `json:"file,omitempty"`
  431. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  432. }
  433. // MessageReaction stores the data for a message reaction.
  434. type MessageReaction struct {
  435. UserID string `json:"user_id"`
  436. MessageID string `json:"message_id"`
  437. Emoji Emoji `json:"emoji"`
  438. ChannelID string `json:"channel_id"`
  439. }
  440. // Constants for the different bit offsets of text channel permissions
  441. const (
  442. PermissionReadMessages = 1 << (iota + 10)
  443. PermissionSendMessages
  444. PermissionSendTTSMessages
  445. PermissionManageMessages
  446. PermissionEmbedLinks
  447. PermissionAttachFiles
  448. PermissionReadMessageHistory
  449. PermissionMentionEveryone
  450. PermissionUseExternalEmojis
  451. )
  452. // Constants for the different bit offsets of voice permissions
  453. const (
  454. PermissionVoiceConnect = 1 << (iota + 20)
  455. PermissionVoiceSpeak
  456. PermissionVoiceMuteMembers
  457. PermissionVoiceDeafenMembers
  458. PermissionVoiceMoveMembers
  459. PermissionVoiceUseVAD
  460. )
  461. // Constants for general management.
  462. const (
  463. PermissionChangeNickname = 1 << (iota + 26)
  464. PermissionManageNicknames
  465. PermissionManageRoles
  466. PermissionManageWebhooks
  467. PermissionManageEmojis
  468. )
  469. // Constants for the different bit offsets of general permissions
  470. const (
  471. PermissionCreateInstantInvite = 1 << iota
  472. PermissionKickMembers
  473. PermissionBanMembers
  474. PermissionAdministrator
  475. PermissionManageChannels
  476. PermissionManageServer
  477. PermissionAllText = PermissionReadMessages |
  478. PermissionSendMessages |
  479. PermissionSendTTSMessages |
  480. PermissionManageMessages |
  481. PermissionEmbedLinks |
  482. PermissionAttachFiles |
  483. PermissionReadMessageHistory |
  484. PermissionMentionEveryone
  485. PermissionAllVoice = PermissionVoiceConnect |
  486. PermissionVoiceSpeak |
  487. PermissionVoiceMuteMembers |
  488. PermissionVoiceDeafenMembers |
  489. PermissionVoiceMoveMembers |
  490. PermissionVoiceUseVAD
  491. PermissionAllChannel = PermissionAllText |
  492. PermissionAllVoice |
  493. PermissionCreateInstantInvite |
  494. PermissionManageRoles |
  495. PermissionManageChannels
  496. PermissionAll = PermissionAllChannel |
  497. PermissionKickMembers |
  498. PermissionBanMembers |
  499. PermissionManageServer
  500. )