structs.go 19 KB

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