structs.go 19 KB

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