structs.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. "net/http"
  12. "sync"
  13. "time"
  14. "github.com/gorilla/websocket"
  15. )
  16. // A Session represents a connection to the Discord API.
  17. type Session struct {
  18. sync.RWMutex
  19. // General configurable settings.
  20. // Authentication token for this session
  21. Token string
  22. MFA bool
  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. // Whether or not to call event handlers synchronously.
  38. // e.g false = launch event handlers in their own goroutines.
  39. SyncEvents bool
  40. // Exposed but should not be modified by User.
  41. // Whether the Data Websocket is ready
  42. DataReady bool // NOTE: Maye be deprecated soon
  43. // Max number of REST API retries
  44. MaxRestRetries int
  45. // Status stores the currect status of the websocket connection
  46. // this is being tested, may stay, may go away.
  47. status int32
  48. // Whether the Voice Websocket is ready
  49. VoiceReady bool // NOTE: Deprecated.
  50. // Whether the UDP Connection is ready
  51. UDPReady bool // NOTE: Deprecated
  52. // Stores a mapping of guild id's to VoiceConnections
  53. VoiceConnections map[string]*VoiceConnection
  54. // Managed state object, updated internally with events when
  55. // StateEnabled is true.
  56. State *State
  57. // The http client used for REST requests
  58. Client *http.Client
  59. // Stores the last HeartbeatAck that was recieved (in UTC)
  60. LastHeartbeatAck time.Time
  61. // used to deal with rate limits
  62. Ratelimiter *RateLimiter
  63. // Event handlers
  64. handlersMu sync.RWMutex
  65. handlers map[string][]*eventHandlerInstance
  66. onceHandlers map[string][]*eventHandlerInstance
  67. // The websocket connection.
  68. wsConn *websocket.Conn
  69. // When nil, the session is not listening.
  70. listening chan interface{}
  71. // sequence tracks the current gateway api websocket sequence number
  72. sequence *int64
  73. // stores sessions current Discord Gateway
  74. gateway string
  75. // stores session ID of current Gateway connection
  76. sessionID string
  77. // used to make sure gateway websocket writes do not happen concurrently
  78. wsMutex sync.Mutex
  79. }
  80. // A VoiceRegion stores data for a specific voice region server.
  81. type VoiceRegion struct {
  82. ID string `json:"id"`
  83. Name string `json:"name"`
  84. Hostname string `json:"sample_hostname"`
  85. Port int `json:"sample_port"`
  86. }
  87. // A VoiceICE stores data for voice ICE servers.
  88. type VoiceICE struct {
  89. TTL string `json:"ttl"`
  90. Servers []*ICEServer `json:"servers"`
  91. }
  92. // A ICEServer stores data for a specific voice ICE server.
  93. type ICEServer struct {
  94. URL string `json:"url"`
  95. Username string `json:"username"`
  96. Credential string `json:"credential"`
  97. }
  98. // A Invite stores all data related to a specific Discord Guild or Channel invite.
  99. type Invite struct {
  100. Guild *Guild `json:"guild"`
  101. Channel *Channel `json:"channel"`
  102. Inviter *User `json:"inviter"`
  103. Code string `json:"code"`
  104. CreatedAt Timestamp `json:"created_at"`
  105. MaxAge int `json:"max_age"`
  106. Uses int `json:"uses"`
  107. MaxUses int `json:"max_uses"`
  108. XkcdPass string `json:"xkcdpass"`
  109. Revoked bool `json:"revoked"`
  110. Temporary bool `json:"temporary"`
  111. }
  112. // ChannelType is the type of a Channel
  113. type ChannelType int
  114. // Block contains known ChannelType values
  115. const (
  116. ChannelTypeGuildText ChannelType = iota
  117. ChannelTypeDM
  118. ChannelTypeGuildVoice
  119. ChannelTypeGroupDM
  120. ChannelTypeGuildCategory
  121. )
  122. // A Channel holds all data related to an individual Discord channel.
  123. type Channel struct {
  124. ID string `json:"id"`
  125. GuildID string `json:"guild_id"`
  126. Name string `json:"name"`
  127. Topic string `json:"topic"`
  128. Type ChannelType `json:"type"`
  129. LastMessageID string `json:"last_message_id"`
  130. NSFW bool `json:"nsfw"`
  131. Position int `json:"position"`
  132. Bitrate int `json:"bitrate"`
  133. Recipients []*User `json:"recipients"`
  134. Messages []*Message `json:"-"`
  135. PermissionOverwrites []*PermissionOverwrite `json:"permission_overwrites"`
  136. ParentID string `json:"parent_id"`
  137. }
  138. // A PermissionOverwrite holds permission overwrite data for a Channel
  139. type PermissionOverwrite struct {
  140. ID string `json:"id"`
  141. Type string `json:"type"`
  142. Deny int `json:"deny"`
  143. Allow int `json:"allow"`
  144. }
  145. // Emoji struct holds data related to Emoji's
  146. type Emoji struct {
  147. ID string `json:"id"`
  148. Name string `json:"name"`
  149. Roles []string `json:"roles"`
  150. Managed bool `json:"managed"`
  151. RequireColons bool `json:"require_colons"`
  152. }
  153. // APIName returns an correctly formatted API name for use in the MessageReactions endpoints.
  154. func (e *Emoji) APIName() string {
  155. if e.ID != "" && e.Name != "" {
  156. return e.Name + ":" + e.ID
  157. }
  158. if e.Name != "" {
  159. return e.Name
  160. }
  161. return e.ID
  162. }
  163. // VerificationLevel type defination
  164. type VerificationLevel int
  165. // Constants for VerificationLevel levels from 0 to 3 inclusive
  166. const (
  167. VerificationLevelNone VerificationLevel = iota
  168. VerificationLevelLow
  169. VerificationLevelMedium
  170. VerificationLevelHigh
  171. )
  172. // A Guild holds all data related to a specific Discord Guild. Guilds are also
  173. // sometimes referred to as Servers in the Discord client.
  174. type Guild struct {
  175. ID string `json:"id"`
  176. Name string `json:"name"`
  177. Icon string `json:"icon"`
  178. Region string `json:"region"`
  179. AfkChannelID string `json:"afk_channel_id"`
  180. EmbedChannelID string `json:"embed_channel_id"`
  181. OwnerID string `json:"owner_id"`
  182. JoinedAt Timestamp `json:"joined_at"`
  183. Splash string `json:"splash"`
  184. AfkTimeout int `json:"afk_timeout"`
  185. MemberCount int `json:"member_count"`
  186. VerificationLevel VerificationLevel `json:"verification_level"`
  187. EmbedEnabled bool `json:"embed_enabled"`
  188. Large bool `json:"large"` // ??
  189. DefaultMessageNotifications int `json:"default_message_notifications"`
  190. Roles []*Role `json:"roles"`
  191. Emojis []*Emoji `json:"emojis"`
  192. Members []*Member `json:"members"`
  193. Presences []*Presence `json:"presences"`
  194. Channels []*Channel `json:"channels"`
  195. VoiceStates []*VoiceState `json:"voice_states"`
  196. Unavailable bool `json:"unavailable"`
  197. }
  198. // A UserGuild holds a brief version of a Guild
  199. type UserGuild struct {
  200. ID string `json:"id"`
  201. Name string `json:"name"`
  202. Icon string `json:"icon"`
  203. Owner bool `json:"owner"`
  204. Permissions int `json:"permissions"`
  205. }
  206. // A GuildParams stores all the data needed to update discord guild settings
  207. type GuildParams struct {
  208. Name string `json:"name,omitempty"`
  209. Region string `json:"region,omitempty"`
  210. VerificationLevel *VerificationLevel `json:"verification_level,omitempty"`
  211. DefaultMessageNotifications int `json:"default_message_notifications,omitempty"` // TODO: Separate type?
  212. AfkChannelID string `json:"afk_channel_id,omitempty"`
  213. AfkTimeout int `json:"afk_timeout,omitempty"`
  214. Icon string `json:"icon,omitempty"`
  215. OwnerID string `json:"owner_id,omitempty"`
  216. Splash string `json:"splash,omitempty"`
  217. }
  218. // A Role stores information about Discord guild member roles.
  219. type Role struct {
  220. ID string `json:"id"`
  221. Name string `json:"name"`
  222. Managed bool `json:"managed"`
  223. Mentionable bool `json:"mentionable"`
  224. Hoist bool `json:"hoist"`
  225. Color int `json:"color"`
  226. Position int `json:"position"`
  227. Permissions int `json:"permissions"`
  228. }
  229. // Roles are a collection of Role
  230. type Roles []*Role
  231. func (r Roles) Len() int {
  232. return len(r)
  233. }
  234. func (r Roles) Less(i, j int) bool {
  235. return r[i].Position > r[j].Position
  236. }
  237. func (r Roles) Swap(i, j int) {
  238. r[i], r[j] = r[j], r[i]
  239. }
  240. // A VoiceState stores the voice states of Guilds
  241. type VoiceState struct {
  242. UserID string `json:"user_id"`
  243. SessionID string `json:"session_id"`
  244. ChannelID string `json:"channel_id"`
  245. GuildID string `json:"guild_id"`
  246. Suppress bool `json:"suppress"`
  247. SelfMute bool `json:"self_mute"`
  248. SelfDeaf bool `json:"self_deaf"`
  249. Mute bool `json:"mute"`
  250. Deaf bool `json:"deaf"`
  251. }
  252. // A Presence stores the online, offline, or idle and game status of Guild members.
  253. type Presence struct {
  254. User *User `json:"user"`
  255. Status Status `json:"status"`
  256. Game *Game `json:"game"`
  257. Nick string `json:"nick"`
  258. Roles []string `json:"roles"`
  259. Since *int `json:"since"`
  260. }
  261. // A game type
  262. type GameType int
  263. const (
  264. GameTypeGame GameType = iota
  265. GameTypeStreaming
  266. )
  267. // A Game struct holds the name of the "playing .." game for a user
  268. type Game struct {
  269. Name string `json:"name"`
  270. Type GameType `json:"type"`
  271. URL string `json:"url,omitempty"`
  272. }
  273. // A Member stores user information for Guild members.
  274. type Member struct {
  275. GuildID string `json:"guild_id"`
  276. JoinedAt string `json:"joined_at"`
  277. Nick string `json:"nick"`
  278. Deaf bool `json:"deaf"`
  279. Mute bool `json:"mute"`
  280. User *User `json:"user"`
  281. Roles []string `json:"roles"`
  282. }
  283. // A Settings stores data for a specific users Discord client settings.
  284. type Settings struct {
  285. RenderEmbeds bool `json:"render_embeds"`
  286. InlineEmbedMedia bool `json:"inline_embed_media"`
  287. InlineAttachmentMedia bool `json:"inline_attachment_media"`
  288. EnableTtsCommand bool `json:"enable_tts_command"`
  289. MessageDisplayCompact bool `json:"message_display_compact"`
  290. ShowCurrentGame bool `json:"show_current_game"`
  291. ConvertEmoticons bool `json:"convert_emoticons"`
  292. Locale string `json:"locale"`
  293. Theme string `json:"theme"`
  294. GuildPositions []string `json:"guild_positions"`
  295. RestrictedGuilds []string `json:"restricted_guilds"`
  296. FriendSourceFlags *FriendSourceFlags `json:"friend_source_flags"`
  297. Status Status `json:"status"`
  298. DetectPlatformAccounts bool `json:"detect_platform_accounts"`
  299. DeveloperMode bool `json:"developer_mode"`
  300. }
  301. // Status type defination
  302. type Status string
  303. // Constants for Status with the different current available status
  304. const (
  305. StatusOnline Status = "online"
  306. StatusIdle Status = "idle"
  307. StatusDoNotDisturb Status = "dnd"
  308. StatusInvisible Status = "invisible"
  309. StatusOffline Status = "offline"
  310. )
  311. // FriendSourceFlags stores ... TODO :)
  312. type FriendSourceFlags struct {
  313. All bool `json:"all"`
  314. MutualGuilds bool `json:"mutual_guilds"`
  315. MutualFriends bool `json:"mutual_friends"`
  316. }
  317. // A Relationship between the logged in user and Relationship.User
  318. type Relationship struct {
  319. User *User `json:"user"`
  320. Type int `json:"type"` // 1 = friend, 2 = blocked, 3 = incoming friend req, 4 = sent friend req
  321. ID string `json:"id"`
  322. }
  323. // A TooManyRequests struct holds information received from Discord
  324. // when receiving a HTTP 429 response.
  325. type TooManyRequests struct {
  326. Bucket string `json:"bucket"`
  327. Message string `json:"message"`
  328. RetryAfter time.Duration `json:"retry_after"`
  329. }
  330. // A ReadState stores data on the read state of channels.
  331. type ReadState struct {
  332. MentionCount int `json:"mention_count"`
  333. LastMessageID string `json:"last_message_id"`
  334. ID string `json:"id"`
  335. }
  336. // An Ack is used to ack messages
  337. type Ack struct {
  338. Token string `json:"token"`
  339. }
  340. // A GuildRole stores data for guild roles.
  341. type GuildRole struct {
  342. Role *Role `json:"role"`
  343. GuildID string `json:"guild_id"`
  344. }
  345. // A GuildBan stores data for a guild ban.
  346. type GuildBan struct {
  347. Reason string `json:"reason"`
  348. User *User `json:"user"`
  349. }
  350. // A GuildIntegration stores data for a guild integration.
  351. type GuildIntegration struct {
  352. ID string `json:"id"`
  353. Name string `json:"name"`
  354. Type string `json:"type"`
  355. Enabled bool `json:"enabled"`
  356. Syncing bool `json:"syncing"`
  357. RoleID string `json:"role_id"`
  358. ExpireBehavior int `json:"expire_behavior"`
  359. ExpireGracePeriod int `json:"expire_grace_period"`
  360. User *User `json:"user"`
  361. Account *GuildIntegrationAccount `json:"account"`
  362. SyncedAt int `json:"synced_at"`
  363. }
  364. // A GuildIntegrationAccount stores data for a guild integration account.
  365. type GuildIntegrationAccount struct {
  366. ID string `json:"id"`
  367. Name string `json:"name"`
  368. }
  369. // A GuildEmbed stores data for a guild embed.
  370. type GuildEmbed struct {
  371. Enabled bool `json:"enabled"`
  372. ChannelID string `json:"channel_id"`
  373. }
  374. // A UserGuildSettingsChannelOverride stores data for a channel override for a users guild settings.
  375. type UserGuildSettingsChannelOverride struct {
  376. Muted bool `json:"muted"`
  377. MessageNotifications int `json:"message_notifications"`
  378. ChannelID string `json:"channel_id"`
  379. }
  380. // A UserGuildSettings stores data for a users guild settings.
  381. type UserGuildSettings struct {
  382. SupressEveryone bool `json:"suppress_everyone"`
  383. Muted bool `json:"muted"`
  384. MobilePush bool `json:"mobile_push"`
  385. MessageNotifications int `json:"message_notifications"`
  386. GuildID string `json:"guild_id"`
  387. ChannelOverrides []*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  388. }
  389. // A UserGuildSettingsEdit stores data for editing UserGuildSettings
  390. type UserGuildSettingsEdit struct {
  391. SupressEveryone bool `json:"suppress_everyone"`
  392. Muted bool `json:"muted"`
  393. MobilePush bool `json:"mobile_push"`
  394. MessageNotifications int `json:"message_notifications"`
  395. ChannelOverrides map[string]*UserGuildSettingsChannelOverride `json:"channel_overrides"`
  396. }
  397. // An APIErrorMessage is an api error message returned from discord
  398. type APIErrorMessage struct {
  399. Code int `json:"code"`
  400. Message string `json:"message"`
  401. }
  402. // Webhook stores the data for a webhook.
  403. type Webhook struct {
  404. ID string `json:"id"`
  405. GuildID string `json:"guild_id"`
  406. ChannelID string `json:"channel_id"`
  407. User *User `json:"user"`
  408. Name string `json:"name"`
  409. Avatar string `json:"avatar"`
  410. Token string `json:"token"`
  411. }
  412. // WebhookParams is a struct for webhook params, used in the WebhookExecute command.
  413. type WebhookParams struct {
  414. Content string `json:"content,omitempty"`
  415. Username string `json:"username,omitempty"`
  416. AvatarURL string `json:"avatar_url,omitempty"`
  417. TTS bool `json:"tts,omitempty"`
  418. File string `json:"file,omitempty"`
  419. Embeds []*MessageEmbed `json:"embeds,omitempty"`
  420. }
  421. // MessageReaction stores the data for a message reaction.
  422. type MessageReaction struct {
  423. UserID string `json:"user_id"`
  424. MessageID string `json:"message_id"`
  425. Emoji Emoji `json:"emoji"`
  426. ChannelID string `json:"channel_id"`
  427. }
  428. // GatewayBotResponse stores the data for the gateway/bot response
  429. type GatewayBotResponse struct {
  430. URL string `json:"url"`
  431. Shards int `json:"shards"`
  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. PermissionAddReactions
  471. PermissionViewAuditLogs
  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. PermissionAddReactions |
  492. PermissionViewAuditLogs
  493. PermissionAll = PermissionAllChannel |
  494. PermissionKickMembers |
  495. PermissionBanMembers |
  496. PermissionManageServer |
  497. PermissionAdministrator
  498. )
  499. // Block contains Discord JSON Error Response codes
  500. const (
  501. ErrCodeUnknownAccount = 10001
  502. ErrCodeUnknownApplication = 10002
  503. ErrCodeUnknownChannel = 10003
  504. ErrCodeUnknownGuild = 10004
  505. ErrCodeUnknownIntegration = 10005
  506. ErrCodeUnknownInvite = 10006
  507. ErrCodeUnknownMember = 10007
  508. ErrCodeUnknownMessage = 10008
  509. ErrCodeUnknownOverwrite = 10009
  510. ErrCodeUnknownProvider = 10010
  511. ErrCodeUnknownRole = 10011
  512. ErrCodeUnknownToken = 10012
  513. ErrCodeUnknownUser = 10013
  514. ErrCodeUnknownEmoji = 10014
  515. ErrCodeBotsCannotUseEndpoint = 20001
  516. ErrCodeOnlyBotsCanUseEndpoint = 20002
  517. ErrCodeMaximumGuildsReached = 30001
  518. ErrCodeMaximumFriendsReached = 30002
  519. ErrCodeMaximumPinsReached = 30003
  520. ErrCodeMaximumGuildRolesReached = 30005
  521. ErrCodeTooManyReactions = 30010
  522. ErrCodeUnauthorized = 40001
  523. ErrCodeMissingAccess = 50001
  524. ErrCodeInvalidAccountType = 50002
  525. ErrCodeCannotExecuteActionOnDMChannel = 50003
  526. ErrCodeEmbedCisabled = 50004
  527. ErrCodeCannotEditFromAnotherUser = 50005
  528. ErrCodeCannotSendEmptyMessage = 50006
  529. ErrCodeCannotSendMessagesToThisUser = 50007
  530. ErrCodeCannotSendMessagesInVoiceChannel = 50008
  531. ErrCodeChannelVerificationLevelTooHigh = 50009
  532. ErrCodeOAuth2ApplicationDoesNotHaveBot = 50010
  533. ErrCodeOAuth2ApplicationLimitReached = 50011
  534. ErrCodeInvalidOAuthState = 50012
  535. ErrCodeMissingPermissions = 50013
  536. ErrCodeInvalidAuthenticationToken = 50014
  537. ErrCodeNoteTooLong = 50015
  538. ErrCodeTooFewOrTooManyMessagesToDelete = 50016
  539. ErrCodeCanOnlyPinMessageToOriginatingChannel = 50019
  540. ErrCodeCannotExecuteActionOnSystemMessage = 50021
  541. ErrCodeMessageProvidedTooOldForBulkDelete = 50034
  542. ErrCodeInvalidFormBody = 50035
  543. ErrCodeInviteAcceptedToGuildApplicationsBotNotIn = 50036
  544. ErrCodeReactionBlocked = 90001
  545. )