structs.go 18 KB

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