structs.go 18 KB

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