structs.go 19 KB

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