wsapi.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. // Discordgo - Discord bindings for Go
  2. // Available at https://github.com/bwmarrin/discordgo
  3. // Copyright 2015 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 low level functions for interacting with the Discord
  7. // data websocket interface.
  8. package discordgo
  9. import (
  10. "encoding/json"
  11. "fmt"
  12. "runtime"
  13. "time"
  14. "github.com/gorilla/websocket"
  15. )
  16. // Open opens a websocket connection to Discord.
  17. func (s *Session) Open() (err error) {
  18. // Get the gateway to use for the Websocket connection
  19. g, err := s.Gateway()
  20. // TODO: See if there's a use for the http response.
  21. // conn, response, err := websocket.DefaultDialer.Dial(session.Gateway, nil)
  22. s.wsConn, _, err = websocket.DefaultDialer.Dial(g, nil)
  23. return
  24. }
  25. type handshakeProperties struct {
  26. OS string `json:"$os"`
  27. Browser string `json:"$browser"`
  28. Device string `json:"$device"`
  29. Referer string `json:"$referer"`
  30. ReferringDomain string `json:"$referring_domain"`
  31. }
  32. type handshakeData struct {
  33. Version int `json:"v"`
  34. Token string `json:"token"`
  35. Properties handshakeProperties `json:"properties"`
  36. }
  37. type handshakeOp struct {
  38. Op int `json:"op"`
  39. Data handshakeData `json:"d"`
  40. }
  41. // Handshake sends the client data to Discord during websocket initial connection.
  42. func (s *Session) Handshake() (err error) {
  43. // maybe this is SendOrigin? not sure the right name here
  44. data := handshakeOp{2, handshakeData{3, s.Token, handshakeProperties{runtime.GOOS, "DiscordGo v" + VERSION, "", "", ""}}}
  45. err = s.wsConn.WriteJSON(data)
  46. return
  47. }
  48. type updateStatusGame struct {
  49. Name string `json:"name"`
  50. }
  51. type updateStatusData struct {
  52. IdleSince *int `json:"idle_since"`
  53. Game *updateStatusGame `json:"game"`
  54. }
  55. type updateStatusOp struct {
  56. Op int `json:"op"`
  57. Data updateStatusData `json:"d"`
  58. }
  59. // UpdateStatus is used to update the authenticated user's status.
  60. // If idle>0 then set status to idle. If game>0 then set game.
  61. // if otherwise, set status to active, and no game.
  62. func (s *Session) UpdateStatus(idle int, game string) (err error) {
  63. var usd updateStatusData
  64. if idle > 0 {
  65. usd.IdleSince = &idle
  66. }
  67. if game != "" {
  68. usd.Game = &updateStatusGame{game}
  69. }
  70. data := updateStatusOp{3, usd}
  71. err = s.wsConn.WriteJSON(data)
  72. return
  73. }
  74. // Listen starts listening to the websocket connection for events.
  75. func (s *Session) Listen() (err error) {
  76. // TODO: need a channel or something to communicate
  77. // to this so I can tell it to stop listening
  78. if s.wsConn == nil {
  79. fmt.Println("No websocket connection exists.")
  80. return // TODO need to return an error.
  81. }
  82. for {
  83. messageType, message, err := s.wsConn.ReadMessage()
  84. if err != nil {
  85. fmt.Println("Websocket Listen Error", err)
  86. // TODO Log error
  87. break
  88. }
  89. go s.event(messageType, message)
  90. }
  91. return
  92. }
  93. // Not sure how needed this is and where it would be best to call it.
  94. // somewhere.
  95. // Close closes the connection to the websocket.
  96. func (s *Session) Close() {
  97. s.wsConn.Close()
  98. }
  99. func unmarshalEvent(event Event, i interface{}) (err error) {
  100. if err = json.Unmarshal(event.RawData, i); err != nil {
  101. fmt.Println(event.Type, err)
  102. printJSON(event.RawData) // TODO: Better error loggingEvent.
  103. }
  104. return
  105. }
  106. // Front line handler for all Websocket Events. Determines the
  107. // event type and passes the message along to the next handler.
  108. // event is the front line handler for all events. This needs to be
  109. // broken up into smaller functions to be more idiomatic Go.
  110. func (s *Session) event(messageType int, message []byte) (err error) {
  111. if s.Debug {
  112. printJSON(message)
  113. }
  114. var e Event
  115. if err = json.Unmarshal(message, &e); err != nil {
  116. fmt.Println(err)
  117. return
  118. }
  119. switch e.Type {
  120. case "READY":
  121. var st Ready
  122. if err = unmarshalEvent(e, &st); err == nil {
  123. s.State.OnReady(&st)
  124. if s.OnReady != nil {
  125. s.OnReady(s, st)
  126. }
  127. go s.Heartbeat(st.HeartbeatInterval)
  128. }
  129. return
  130. case "VOICE_SERVER_UPDATE":
  131. // TEMP CODE FOR TESTING VOICE
  132. var st VoiceServerUpdate
  133. if err = unmarshalEvent(e, &st); err == nil {
  134. s.onVoiceServerUpdate(st)
  135. }
  136. return
  137. case "VOICE_STATE_UPDATE":
  138. // TEMP CODE FOR TESTING VOICE
  139. var st VoiceState
  140. if err = unmarshalEvent(e, &st); err == nil {
  141. s.onVoiceStateUpdate(st)
  142. }
  143. return
  144. case "USER_UPDATE":
  145. if s.OnUserUpdate != nil {
  146. var st User
  147. if err = unmarshalEvent(e, &st); err == nil {
  148. s.OnUserUpdate(s, st)
  149. }
  150. return
  151. }
  152. case "PRESENCE_UPDATE":
  153. if s.OnPresenceUpdate != nil {
  154. var st PresenceUpdate
  155. if err = unmarshalEvent(e, &st); err == nil {
  156. s.OnPresenceUpdate(s, st)
  157. }
  158. return
  159. }
  160. case "TYPING_START":
  161. if s.OnTypingStart != nil {
  162. var st TypingStart
  163. if err = unmarshalEvent(e, &st); err == nil {
  164. s.OnTypingStart(s, st)
  165. }
  166. return
  167. }
  168. /* Never seen this come in but saw it in another Library.
  169. case "MESSAGE_ACK":
  170. if s.OnMessageAck != nil {
  171. }
  172. */
  173. case "MESSAGE_CREATE":
  174. if s.OnMessageCreate != nil {
  175. var st Message
  176. if err = unmarshalEvent(e, &st); err == nil {
  177. s.OnMessageCreate(s, st)
  178. }
  179. return
  180. }
  181. case "MESSAGE_UPDATE":
  182. if s.OnMessageUpdate != nil {
  183. var st Message
  184. if err = unmarshalEvent(e, &st); err == nil {
  185. s.OnMessageUpdate(s, st)
  186. }
  187. return
  188. }
  189. case "MESSAGE_DELETE":
  190. if s.OnMessageDelete != nil {
  191. var st MessageDelete
  192. if err = unmarshalEvent(e, &st); err == nil {
  193. s.OnMessageDelete(s, st)
  194. }
  195. return
  196. }
  197. case "MESSAGE_ACK":
  198. if s.OnMessageAck != nil {
  199. var st MessageAck
  200. if err = unmarshalEvent(e, &st); err == nil {
  201. s.OnMessageAck(s, st)
  202. }
  203. return
  204. }
  205. case "CHANNEL_CREATE":
  206. var st Channel
  207. if err = unmarshalEvent(e, &st); err == nil {
  208. s.State.AddChannel(&st)
  209. if s.OnChannelCreate != nil {
  210. s.OnChannelCreate(s, st)
  211. }
  212. }
  213. return
  214. case "CHANNEL_UPDATE":
  215. var st Channel
  216. if err = unmarshalEvent(e, &st); err == nil {
  217. s.State.AddChannel(&st)
  218. if s.OnChannelUpdate != nil {
  219. s.OnChannelUpdate(s, st)
  220. }
  221. }
  222. return
  223. case "CHANNEL_DELETE":
  224. var st Channel
  225. if err = unmarshalEvent(e, &st); err == nil {
  226. s.State.RemoveChannel(&st)
  227. if s.OnChannelDelete != nil {
  228. s.OnChannelDelete(s, st)
  229. }
  230. }
  231. return
  232. case "GUILD_CREATE":
  233. var st Guild
  234. if err = unmarshalEvent(e, &st); err == nil {
  235. s.State.AddGuild(&st)
  236. if s.OnGuildCreate != nil {
  237. s.OnGuildCreate(s, st)
  238. }
  239. }
  240. return
  241. case "GUILD_UPDATE":
  242. var st Guild
  243. if err = unmarshalEvent(e, &st); err == nil {
  244. s.State.AddGuild(&st)
  245. if s.OnGuildCreate != nil {
  246. s.OnGuildUpdate(s, st)
  247. }
  248. }
  249. return
  250. case "GUILD_DELETE":
  251. var st Guild
  252. if err = unmarshalEvent(e, &st); err == nil {
  253. s.State.RemoveGuild(&st)
  254. if s.OnGuildDelete != nil {
  255. s.OnGuildDelete(s, st)
  256. }
  257. }
  258. return
  259. case "GUILD_MEMBER_ADD":
  260. var st Member
  261. if err = unmarshalEvent(e, &st); err == nil {
  262. s.State.AddMember(&st)
  263. if s.OnGuildMemberAdd != nil {
  264. s.OnGuildMemberAdd(s, st)
  265. }
  266. }
  267. return
  268. case "GUILD_MEMBER_REMOVE":
  269. var st Member
  270. if err = unmarshalEvent(e, &st); err == nil {
  271. s.State.RemoveMember(&st)
  272. if s.OnGuildMemberRemove != nil {
  273. s.OnGuildMemberRemove(s, st)
  274. }
  275. }
  276. return
  277. case "GUILD_MEMBER_UPDATE":
  278. var st Member
  279. if err = unmarshalEvent(e, &st); err == nil {
  280. s.State.AddMember(&st)
  281. if s.OnGuildMemberUpdate != nil {
  282. s.OnGuildMemberUpdate(s, st)
  283. }
  284. }
  285. return
  286. case "GUILD_ROLE_CREATE":
  287. if s.OnGuildRoleCreate != nil {
  288. var st GuildRole
  289. if err = unmarshalEvent(e, &st); err == nil {
  290. s.OnGuildRoleCreate(s, st)
  291. }
  292. return
  293. }
  294. case "GUILD_ROLE_UPDATE":
  295. if s.OnGuildRoleUpdate != nil {
  296. var st GuildRole
  297. if err = unmarshalEvent(e, &st); err == nil {
  298. s.OnGuildRoleUpdate(s, st)
  299. }
  300. return
  301. }
  302. case "GUILD_ROLE_DELETE":
  303. if s.OnGuildRoleDelete != nil {
  304. var st GuildRoleDelete
  305. if err = unmarshalEvent(e, &st); err == nil {
  306. s.OnGuildRoleDelete(s, st)
  307. }
  308. return
  309. }
  310. case "GUILD_INTEGRATIONS_UPDATE":
  311. if s.OnGuildIntegrationsUpdate != nil {
  312. var st GuildIntegrationsUpdate
  313. if err = unmarshalEvent(e, &st); err == nil {
  314. s.OnGuildIntegrationsUpdate(s, st)
  315. }
  316. return
  317. }
  318. case "GUILD_BAN_ADD":
  319. if s.OnGuildBanAdd != nil {
  320. var st GuildBan
  321. if err = unmarshalEvent(e, &st); err == nil {
  322. s.OnGuildBanAdd(s, st)
  323. }
  324. return
  325. }
  326. case "GUILD_BAN_REMOVE":
  327. if s.OnGuildBanRemove != nil {
  328. var st GuildBan
  329. if err = unmarshalEvent(e, &st); err == nil {
  330. s.OnGuildBanRemove(s, st)
  331. }
  332. return
  333. }
  334. case "USER_SETTINGS_UPDATE":
  335. if s.OnUserSettingsUpdate != nil {
  336. var st map[string]interface{}
  337. if err = unmarshalEvent(e, &st); err == nil {
  338. s.OnUserSettingsUpdate(s, st)
  339. }
  340. return
  341. }
  342. default:
  343. fmt.Println("UNKNOWN EVENT: ", e.Type)
  344. // TODO learn the log package
  345. // log.print type and JSON data
  346. }
  347. // if still here, send to generic OnEvent
  348. if s.OnEvent != nil {
  349. s.OnEvent(s, e)
  350. return
  351. }
  352. return
  353. }
  354. // This heartbeat is sent to keep the Websocket conenction
  355. // to Discord alive. If not sent, Discord will close the
  356. // connection.
  357. // Heartbeat sends regular heartbeats to Discord so it knows the client
  358. // is still connected. If you do not send these heartbeats Discord will
  359. // disconnect the websocket connection after a few seconds.
  360. func (s *Session) Heartbeat(i time.Duration) {
  361. if s.wsConn == nil {
  362. fmt.Println("No websocket connection exists.")
  363. return // TODO need to return an error.
  364. }
  365. // send first heartbeat immediately because lag could put the
  366. // first heartbeat outside the required heartbeat interval window
  367. ticker := time.NewTicker(i * time.Millisecond)
  368. for {
  369. timestamp := int(time.Now().Unix())
  370. err := s.wsConn.WriteJSON(map[string]int{
  371. "op": 1,
  372. "d": timestamp,
  373. })
  374. if err != nil {
  375. fmt.Println("error sending data heartbeat:", err)
  376. s.DataReady = false
  377. return // TODO log error?
  378. }
  379. s.DataReady = true
  380. <-ticker.C
  381. }
  382. }
  383. // Everything below is experimental Voice support code
  384. // all of it will get changed and moved around.
  385. // A VoiceServerUpdate stores the data received during the Voice Server Update
  386. // data websocket event. This data is used during the initial Voice Channel
  387. // join handshaking.
  388. type VoiceServerUpdate struct {
  389. Token string `json:"token"`
  390. GuildID string `json:"guild_id"`
  391. Endpoint string `json:"endpoint"`
  392. }
  393. type voiceChannelJoinData struct {
  394. GuildID string `json:"guild_id"`
  395. ChannelID string `json:"channel_id"`
  396. SelfMute bool `json:"self_mute"`
  397. SelfDeaf bool `json:"self_deaf"`
  398. }
  399. type voiceChannelJoinOp struct {
  400. Op int `json:"op"`
  401. Data voiceChannelJoinData `json:"d"`
  402. }
  403. // VoiceChannelJoin joins the authenticated session user to
  404. // a voice channel. All the voice magic starts with this.
  405. func (s *Session) VoiceChannelJoin(guildID, channelID string) (err error) {
  406. if s.wsConn == nil {
  407. fmt.Println("error: no websocket connection exists.")
  408. return // TODO return error
  409. }
  410. data := voiceChannelJoinOp{4, voiceChannelJoinData{guildID, channelID, false, false}}
  411. err = s.wsConn.WriteJSON(data)
  412. if err != nil {
  413. return
  414. }
  415. // Probably will be removed later.
  416. s.VGuildID = guildID
  417. s.VChannelID = channelID
  418. return
  419. }
  420. // onVoiceStateUpdate handles Voice State Update events on the data
  421. // websocket. This comes immediately after the call to VoiceChannelJoin
  422. // for the authenticated session user. This block is experimental
  423. // code and will be chaned in the future.
  424. func (s *Session) onVoiceStateUpdate(st VoiceState) {
  425. // Need to have this happen at login and store it in the Session
  426. self, err := s.User("@me") // TODO: move to Login/New
  427. if err != nil {
  428. fmt.Println(err)
  429. return
  430. }
  431. // This event comes for all users, if it's not for the session
  432. // user just ignore it.
  433. if st.UserID != self.ID {
  434. return
  435. }
  436. // Store the SessionID. Used later.
  437. s.VSessionID = st.SessionID
  438. }
  439. // onVoiceServerUpdate handles the Voice Server Update data websocket event.
  440. // This will later be exposed but is only for experimental use now.
  441. func (s *Session) onVoiceServerUpdate(st VoiceServerUpdate) {
  442. // Store all the values. They are used later.
  443. // GuildID is probably not needed and may be dropped.
  444. s.VToken = st.Token
  445. s.VEndpoint = st.Endpoint
  446. s.VGuildID = st.GuildID
  447. // We now have enough information to open a voice websocket conenction
  448. // so, that's what the next call does.
  449. s.VoiceOpenWS()
  450. }