structs.go 18 KB

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