123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- package discordgo
- import (
- "bytes"
- "compress/zlib"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "net/http"
- "reflect"
- "runtime"
- "time"
- "github.com/gorilla/websocket"
- )
- type handshakeProperties struct {
- OS string `json:"$os"`
- Browser string `json:"$browser"`
- Device string `json:"$device"`
- Referer string `json:"$referer"`
- ReferringDomain string `json:"$referring_domain"`
- }
- type handshakeData struct {
- Version int `json:"v"`
- Token string `json:"token"`
- Properties handshakeProperties `json:"properties"`
- LargeThreshold int `json:"large_threshold"`
- Compress bool `json:"compress"`
- }
- type handshakeOp struct {
- Op int `json:"op"`
- Data handshakeData `json:"d"`
- }
- func (s *Session) Open() (err error) {
- s.Lock()
- defer func() {
- if err != nil {
- s.Unlock()
- }
- }()
- if s.wsConn != nil {
- err = errors.New("Web socket already opened.")
- return
- }
-
- g, err := s.Gateway()
- if err != nil {
- return
- }
- header := http.Header{}
- header.Add("accept-encoding", "zlib")
-
-
- s.wsConn, _, err = websocket.DefaultDialer.Dial(g, header)
- if err != nil {
- return
- }
- err = s.wsConn.WriteJSON(handshakeOp{2, handshakeData{3, s.Token, handshakeProperties{runtime.GOOS, "Discordgo v" + VERSION, "", "", ""}, 250, s.Compress}})
- if err != nil {
- return
- }
-
-
- s.listening = make(chan interface{})
- go s.listen(s.wsConn, s.listening)
- s.Unlock()
- s.initialize()
- s.handle(&Connect{})
- return
- }
- func (s *Session) Close() (err error) {
- s.Lock()
- s.DataReady = false
- if s.listening != nil {
- close(s.listening)
- s.listening = nil
- }
- if s.wsConn != nil {
- err = s.wsConn.Close()
- s.wsConn = nil
- }
- s.Unlock()
- s.handle(&Disconnect{})
- return
- }
- func (s *Session) listen(wsConn *websocket.Conn, listening <-chan interface{}) {
- for {
- messageType, message, err := wsConn.ReadMessage()
- if err != nil {
-
-
-
- s.RLock()
- sameConnection := s.wsConn == wsConn
- s.RUnlock()
- if sameConnection {
-
-
- err := s.Close()
- if err != nil {
- fmt.Println("error closing session connection: ", err)
- }
-
- if s.ShouldReconnectOnError {
- wait := time.Duration(1)
- for {
- if s.Open() == nil {
- return
- }
- <-time.After(wait * time.Second)
- wait *= 2
- if wait > 600 {
- wait = 600
- }
- }
- }
- }
- return
- }
- select {
- case <-listening:
- return
- default:
- go s.event(messageType, message)
- }
- }
- }
- type heartbeatOp struct {
- Op int `json:"op"`
- Data int `json:"d"`
- }
- func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {
- if listening == nil || wsConn == nil {
- return
- }
- s.Lock()
- s.DataReady = true
- s.Unlock()
- var err error
- ticker := time.NewTicker(i * time.Millisecond)
- for {
- err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
- if err != nil {
- fmt.Println("Error sending heartbeat:", err)
- return
- }
- select {
- case <-ticker.C:
-
- case <-listening:
- return
- }
- }
- }
- type updateStatusGame struct {
- Name string `json:"name"`
- }
- type updateStatusData struct {
- IdleSince *int `json:"idle_since"`
- Game *updateStatusGame `json:"game"`
- }
- type updateStatusOp struct {
- Op int `json:"op"`
- Data updateStatusData `json:"d"`
- }
- func (s *Session) UpdateStatus(idle int, game string) (err error) {
- s.RLock()
- defer s.RUnlock()
- if s.wsConn == nil {
- return errors.New("No websocket connection exists.")
- }
- var usd updateStatusData
- if idle > 0 {
- usd.IdleSince = &idle
- }
- if game != "" {
- usd.Game = &updateStatusGame{game}
- }
- err = s.wsConn.WriteJSON(updateStatusOp{3, usd})
- return
- }
- func (s *Session) event(messageType int, message []byte) {
- var err error
- var reader io.Reader
- reader = bytes.NewBuffer(message)
- if messageType == 2 {
- z, err1 := zlib.NewReader(reader)
- if err1 != nil {
- fmt.Println(err1)
- return
- }
- defer func() {
- err := z.Close()
- if err != nil {
- fmt.Println("error closing zlib:", err)
- }
- }()
- reader = z
- }
- var e *Event
- decoder := json.NewDecoder(reader)
- if err = decoder.Decode(&e); err != nil {
- fmt.Println(err)
- return
- }
- if s.Debug {
- printEvent(e)
- }
- i := eventToInterface[e.Type]
- if i != nil {
-
- i = reflect.New(reflect.TypeOf(i)).Interface()
-
-
- if err = unmarshal(e.RawData, i); err != nil {
- fmt.Println("Unable to unmarshal event data.")
- i = e
- }
- } else {
- fmt.Println("Unknown event.")
- i = e
- }
- s.handle(i)
- return
- }
- type VoiceServerUpdate struct {
- Token string `json:"token"`
- GuildID string `json:"guild_id"`
- Endpoint string `json:"endpoint"`
- }
- type voiceChannelJoinData struct {
- GuildID *string `json:"guild_id"`
- ChannelID *string `json:"channel_id"`
- SelfMute bool `json:"self_mute"`
- SelfDeaf bool `json:"self_deaf"`
- }
- type voiceChannelJoinOp struct {
- Op int `json:"op"`
- Data voiceChannelJoinData `json:"d"`
- }
- func (s *Session) ChannelVoiceJoin(gID, cID string, mute, deaf bool) (err error) {
-
-
-
- if s.Voice == nil {
- s.Voice = &Voice{}
- }
-
- data := voiceChannelJoinOp{4, voiceChannelJoinData{&gID, &cID, mute, deaf}}
- err = s.wsConn.WriteJSON(data)
- if err != nil {
- return
- }
-
- s.Voice.guildID = gID
- s.Voice.channelID = cID
- return
- }
- func (s *Session) ChannelVoiceLeave() (err error) {
- if s.Voice == nil {
- return
- }
-
- data := voiceChannelJoinOp{4, voiceChannelJoinData{nil, nil, true, true}}
- err = s.wsConn.WriteJSON(data)
- if err != nil {
- return
- }
-
- s.Voice.Close()
- s.Voice = nil
- return
- }
- func (s *Session) onVoiceStateUpdate(se *Session, st *VoiceStateUpdate) {
-
- if s.Voice == nil {
- return
- }
-
-
-
- self, err := s.User("@me")
- if err != nil {
- fmt.Println(err)
- return
- }
-
-
-
- if st.UserID != self.ID {
- return
- }
-
- s.Voice.userID = self.ID
- s.Voice.sessionID = st.SessionID
- }
- func (s *Session) onVoiceServerUpdate(se *Session, st *VoiceServerUpdate) {
-
- s.Voice.token = st.Token
- s.Voice.endpoint = st.Endpoint
- s.Voice.guildID = st.GuildID
-
-
- s.Voice.Close()
-
-
- err := s.Voice.Open()
- if err != nil {
- fmt.Println("onVoiceServerUpdate Voice.Open error: ", err)
-
- }
- }
|