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