structs.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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 Settings stores data for a specific users Discord client settings.
  283. type Settings struct {
  284. RenderEmbeds bool `json:"render_embeds"`
  285. InlineEmbedMedia bool `json:"inline_embed_media"`
  286. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  287. EnableTtsCommand bool `json:"enable_tts_command"`
  288. MessageDisplayCompact bool `json:"message_display_compact"`
  289. ShowCurrentGame bool `json:"show_current_game"`
  290. ConvertEmoticons bool `json:"convert_emoticons"`
  291. Locale string `json:"locale"`
  292. Theme string `json:"theme"`
  293. GuildPositions []string `json:"guild_positions"`
  294. RestrictedGuilds []string `json:"restricted_guilds"`
  295. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  296. Status Status `json:"status"`
  297. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  298. DeveloperMode bool `json:"developer_mode"`
  299. }
  300. // Status type defination
  301. type Status string
  302. // Constants for Status with the different current available status
  303. const (
  304. StatusOnline Status = "online"
  305. StatusIdle Status = "idle"
  306. StatusDoNotDisturb Status = "dnd"
  307. StatusInvisible Status = "invisible"
  308. StatusOffline Status = "offline"
  309. )
  310. // FriendSourceFlags stores ... TODO :)
  311. type FriendSourceFlags struct {
  312. All bool `json:"all"`
  313. MutualGuilds bool `json:"mutual_guilds"`
  314. MutualFriends bool `json:"mutual_friends"`
  315. }
  316. // A Relationship between the logged in user and Relationship.User
  317. type Relationship struct {
  318. User *User `json:"user"`
  319. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  320. ID string `json:"id"`
  321. }
  322. // A TooManyRequests struct holds information received from Discord
  323. // when receiving a HTTP 429 response.
  324. type TooManyRequests struct {
  325. Bucket string `json:"bucket"`
  326. Message string `json:"message"`
  327. RetryAfter time.Duration `json:"retry_after"`
  328. }
  329. // A ReadState stores data on the read state of channels.
  330. type ReadState struct {
  331. MentionCount int `json:"mention_count"`
  332. LastMessageID string `json:"last_message_id"`
  333. ID string `json:"id"`
  334. }
  335. // An Ack is used to ack messages
  336. type Ack struct {
  337. Token string `json:"token"`
  338. }
  339. // A GuildRole stores data for guild roles.
  340. type GuildRole struct {
  341. Role *Role `json:"role"`
  342. GuildID string `json:"guild_id"`
  343. }
  344. // A GuildBan stores data for a guild ban.
  345. type GuildBan struct {
  346. Reason string `json:"reason"`
  347. User *User `json:"user"`
  348. }
  349. // A GuildIntegration stores data for a guild integration.
  350. type GuildIntegration struct {
  351. ID string `json:"id"`
  352. Name string `json:"name"`
  353. Type string `json:"type"`
  354. Enabled bool `json:"enabled"`
  355. Syncing bool `json:"syncing"`
  356. RoleID string `json:"role_id"`
  357. ExpireBehavior int `json:"expire_behavior"`
  358. ExpireGracePeriod int `json:"expire_grace_period"`
  359. User *User `json:"user"`
  360. Account *GuildIntegrationAccount `json:"account"`
  361. SyncedAt int `json:"synced_at"`
  362. }
  363. // A GuildIntegrationAccount stores data for a guild integration account.
  364. type GuildIntegrationAccount struct {
  365. ID string `json:"id"`
  366. Name string `json:"name"`
  367. }
  368. // A GuildEmbed stores data for a guild embed.
  369. type GuildEmbed struct {
  370. Enabled bool `json:"enabled"`
  371. ChannelID string `json:"channel_id"`
  372. }
  373. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  374. type UserGuildSettingsChannelOverride struct {
  375. Muted bool `json:"muted"`
  376. MessageNotifications int `json:"message_notifications"`
  377. ChannelID string `json:"channel_id"`
  378. }
  379. // A UserGuildSettings stores data for a users guild settings.
  380. type UserGuildSettings struct {
  381. SupressEveryone bool `json:"suppress_everyone"`
  382. Muted bool `json:"muted"`
  383. MobilePush bool `json:"mobile_push"`
  384. MessageNotifications int `json:"message_notifications"`
  385. GuildID string `json:"guild_id"`
  386. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  387. }
  388. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  389. type UserGuildSettingsEdit 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. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  395. }
  396. // An APIErrorMessage is an api error message returned from discord
  397. type APIErrorMessage struct {
  398. Code int `json:"code"`
  399. Message string `json:"message"`
  400. }
  401. // Webhook stores the data for a webhook.
  402. type Webhook struct {
  403. ID string `json:"id"`
  404. GuildID string `json:"guild_id"`
  405. ChannelID string `json:"channel_id"`
  406. User *User `json:"user"`
  407. Name string `json:"name"`
  408. Avatar string `json:"avatar"`
  409. Token string `json:"token"`
  410. }
  411. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  412. type WebhookParams struct {
  413. Content string `json:"content,omitempty"`
  414. Username string `json:"username,omitempty"`
  415. AvatarURL string `json:"avatar_url,omitempty"`
  416. TTS bool `json:"tts,omitempty"`
  417. File string `json:"file,omitempty"`
  418. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  419. }
  420. // MessageReaction stores the data for a message reaction.
  421. type MessageReaction struct {
  422. UserID string `json:"user_id"`
  423. MessageID string `json:"message_id"`
  424. Emoji Emoji `json:"emoji"`
  425. ChannelID string `json:"channel_id"`
  426. }
  427. // Constants for the different bit offsets of text channel permissions
  428. const (
  429. PermissionReadMessages = 1 << (iota + 10)
  430. PermissionSendMessages
  431. PermissionSendTTSMessages
  432. PermissionManageMessages
  433. PermissionEmbedLinks
  434. PermissionAttachFiles
  435. PermissionReadMessageHistory
  436. PermissionMentionEveryone
  437. PermissionUseExternalEmojis
  438. )
  439. // Constants for the different bit offsets of voice permissions
  440. const (
  441. PermissionVoiceConnect = 1 << (iota + 20)
  442. PermissionVoiceSpeak
  443. PermissionVoiceMuteMembers
  444. PermissionVoiceDeafenMembers
  445. PermissionVoiceMoveMembers
  446. PermissionVoiceUseVAD
  447. )
  448. // Constants for general management.
  449. const (
  450. PermissionChangeNickname = 1 << (iota + 26)
  451. PermissionManageNicknames
  452. PermissionManageRoles
  453. PermissionManageWebhooks
  454. PermissionManageEmojis
  455. )
  456. // Constants for the different bit offsets of general permissions
  457. const (
  458. PermissionCreateInstantInvite = 1 << iota
  459. PermissionKickMembers
  460. PermissionBanMembers
  461. PermissionAdministrator
  462. PermissionManageChannels
  463. PermissionManageServer
  464. PermissionAllText = PermissionReadMessages |
  465. PermissionSendMessages |
  466. PermissionSendTTSMessages |
  467. PermissionManageMessages |
  468. PermissionEmbedLinks |
  469. PermissionAttachFiles |
  470. PermissionReadMessageHistory |
  471. PermissionMentionEveryone
  472. PermissionAllVoice = PermissionVoiceConnect |
  473. PermissionVoiceSpeak |
  474. PermissionVoiceMuteMembers |
  475. PermissionVoiceDeafenMembers |
  476. PermissionVoiceMoveMembers |
  477. PermissionVoiceUseVAD
  478. PermissionAllChannel = PermissionAllText |
  479. PermissionAllVoice |
  480. PermissionCreateInstantInvite |
  481. PermissionManageRoles |
  482. PermissionManageChannels
  483. PermissionAll = PermissionAllChannel |
  484. PermissionKickMembers |
  485. PermissionBanMembers |
  486. PermissionManageServer |
  487. PermissionAdministrator
  488. )