public void Connect()
        {
            CurrentGatewayURL = GetGatewayUrl();
            DebugLogger.Log("Gateway retrieved: " + CurrentGatewayURL);
            ws = new WebSocket(CurrentGatewayURL);
            ws.EnableRedirection = true;
            ws.Log.File = "websocketlog.txt";
                ws.OnMessage += (sender, e) =>
                {
                    var message = JObject.Parse(e.Data);
                    switch(message["t"].ToString())
                    {
                        case ("READY"):
                            if(WriteLatestReady)
                                using (var sw = new StreamWriter("READY_LATEST.txt"))
                                    sw.Write(message);
                            //Me = new DiscordMember(this)
                            //{
                            //    user = new DiscordUser(this)
                            //    {
                            //        username = message["d"]["user"]["username"].ToString(),
                            //        id = message["d"]["user"]["id"].ToString(),
                            //        verified = message["d"]["user"]["verified"].ToObject<bool>(),
                            //        avatar = message["d"]["user"]["avatar"].ToString(),
                            //        discriminator = message["d"]["user"]["discriminator"].ToString(),
                            //        email = message["d"]["user"]["email"].ToString()
                            //    }
                            //};
                            Me = JsonConvert.DeserializeObject<DiscordMember>(message["d"]["user"].ToString());


                            ClientPrivateInformation.avatar = Me.Avatar;
                            ClientPrivateInformation.username = Me.Username;
                            HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                            GetChannelsList(message);
                            if (Connected != null)
                                Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it.
                            break;
                        case ("GUILD_MEMBER_REMOVE"):
                            GuildMemberRemoveEvents(message);
                            break;
                        case ("GUILD_MEMBER_ADD"):
                            GuildMemberAddEvents(message);
                            break;
                        case ("GUILD_DELETE"):
                            GuildDeleteEvents(message);
                            break;
                        case ("GUILD_CREATE"):
                            GuildCreateEvents(message);
                            break;
                        case ("GUILD_MEMBER_UPDATE"):
                            GuildMemberUpdateEvents(message);
                            break;
                        case ("GUILD_UPDATE"):
                            GuildUpdateEvents(message);
                            break;
                        case ("GUILD_ROLE_DELETE"):
                            GuildRoleDeleteEvents(message);
                            break;
                        case ("GUILD_ROLE_UPDATE"):
                            GuildRoleUpdateEvents(message);
                            break;
                        case ("PRESENCE_UPDATE"):
                            PresenceUpdateEvents(message);
                            break;
                        case ("MESSAGE_UPDATE"):
                            MessageUpdateEvents(message);
                            break;
                        case ("TYPING_START"):
                            DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                            if (server != null)
                            {
                                DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                                DiscordMember uuser = server.members.Find(x => x.ID == message["d"]["user_id"].ToString());
                                if (UserTypingStart != null)
                                    UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) });
                            }
                            break;
                        case ("MESSAGE_CREATE"):
                            MessageCreateEvents(message);
                            break;
                        case ("CHANNEL_CREATE"):
                            ChannelCreateEvents(message);
                            break;
                        case ("VOICE_STATE_UPDATE"):
                            VoiceStateUpdateEvents(message);
                            break;
                        case ("VOICE_SERVER_UPDATE"):
                            VoiceServerUpdateEvents(message);
                            break;
                        case ("MESSAGE_DELETE"):
                            MessageDeletedEvents(message);
                            break;
                        case ("USER_UPDATE"):
                            UserUpdateEvents(message);
                            break;
                        case ("CHANNEL_UPDATE"):
                            ChannelUpdateEvents(message);
                            break;
                        case ("CHANNEL_DELETE"):
                            ChannelDeleteEvents(message);
                            break;
                        case("MESSAGE_ACK"): //ignore this message, it's irrelevant
                            break;
                        default:
                            if (UnknownMessageTypeReceived != null)
                                UnknownMessageTypeReceived(this, new UnknownMessageEventArgs { RawJson = message });
                            break;
                    }
                };
                ws.OnOpen += (sender, e) => 
                {
                    DiscordInitObj initObj = new DiscordInitObj();
                    initObj.op = 2;
                    initObj.d.token = token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);

                    KeepAliveTaskToken = KeepAliveTaskTokenSource.Token;
                    KeepAliveTask = new Task(() => 
                    {
                        while (true)
                        {
                            DebugLogger.Log("Hello from inside KeepAliveTask! Sending..");
                            KeepAlive();
                            Thread.Sleep(HeartbeatInterval);
                            if (KeepAliveTaskToken.IsCancellationRequested)
                                KeepAliveTaskToken.ThrowIfCancellationRequested();
                        }
                    }, KeepAliveTaskToken, TaskCreationOptions.LongRunning);
                    KeepAliveTask.Start();
                    DebugLogger.Log("Began keepalive task..");
                };
                ws.OnClose += (sender, e) =>
                {
                    DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                    scev.Code = e.Code;
                    scev.Reason = e.Reason;
                    scev.WasClean = e.WasClean;
                    if (SocketClosed != null)
                        SocketClosed(this, scev);

                };
                ws.Connect();
            DebugLogger.Log("Connecting..");
        }
Example #2
0
        public void ConnectAndReadMessages()
        {
            CurrentGatewayURL = GetGatewayUrl();
            ws = new WebSocket(CurrentGatewayURL);
            ws.EnableRedirection = true;
            ws.Log.File = "websocketlog.txt";
                ws.OnMessage += (sender, e) =>
                {
                    var message = JObject.Parse(e.Data);
                    switch(message["t"].ToString())
                    {
                        case ("READY"):
                            using (var sw = new StreamWriter("READY_LATEST.txt"))
                                sw.Write(message);
                            Me = new DiscordMember
                            {
                                user = new DiscordUser
                                {
                                    username = message["d"]["user"]["username"].ToString(),
                                    id = message["d"]["user"]["id"].ToString(),
                                    verified = message["d"]["user"]["verified"].ToObject<bool>(),
                                    avatar = message["d"]["user"]["avatar"].ToString(),
                                    discriminator = message["d"]["user"]["discriminator"].ToString(),
                                    email = message["d"]["user"]["email"].ToString()
                                }
                            };
                            ClientPrivateInformation.avatar = Me.user.avatar;
                            ClientPrivateInformation.username = Me.user.username;
                            HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                            GetChannelsList(message);
                            if (Connected != null)
                                Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it.
                            break;
                        case ("GUILD_MEMBER_REMOVE"):
                            GuildMemberRemoveEvents(message);
                            break;
                        case ("GUILD_MEMBER_ADD"):
                            GuildMemberAddEvents(message);
                            break;
                        case ("GUILD_DELETE"):
                            GuildDeleteEvents(message);
                            break;
                        case ("GUILD_CREATE"):
                            GuildCreateEvents(message);
                            break;
                        case ("PRESENCE_UPDATE"):
                            PresenceUpdateEvents(message);
                            break;
                        case ("MESSAGE_UPDATE"):
                            MessageUpdateEvents(message);
                            break;
                        case ("TYPING_START"):
                            DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                            if (server != null)
                            {
                                DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                                DiscordMember uuser = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString());
                                if (UserTypingStart != null)
                                    UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) });
                            }
                            break;
                        case ("MESSAGE_CREATE"):
                            MessageCreateEvents(message);
                            break;
                        case ("CHANNEL_CREATE"):
                            ChannelCreateEvents(message);
                            break;
                        case ("VOICE_STATE_UPDATE"):
                            VoiceStateUpdateEvents(message);
                            break;
                        case ("MESSAGE_DELETE"):
                            MessageDeletedEvents(message);
                            break;
                        case ("USER_UPDATE"):
                            UserUpdateEvents(message);
                            break;
                        case ("CHANNEL_UPDATE"):
                            ChannelUpdateEvents(message);
                            break;
                        default:
                            if (UnknownMessageTypeReceived != null)
                                UnknownMessageTypeReceived(this, new UnknownMessageEventArgs { RawJson = message });
                            break;
                    }
                };
                ws.OnOpen += (sender, e) => 
                {
                    DiscordInitObj initObj = new DiscordInitObj();
                    initObj.op = 2;
                    initObj.d.token = this.token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);
                    Thread keepAlivetimer = new Thread(KeepAlive);
                    keepAlivetimer.Start();
                };
                ws.OnClose += (sender, e) =>
                {
                    DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                    scev.Code = e.Code;
                    scev.Reason = e.Reason;
                    scev.WasClean = e.WasClean;
                    if (SocketClosed != null)
                        SocketClosed(this, scev);

                };
                ws.Connect();
        }
Example #3
0
        /// <summary>
        /// Runs the websocket connection for the client hooking up the appropriate events.
        /// </summary>
        /// <param name="useDotNetWebsocket">If true, DiscordSharp will connect using the .Net Framework's built-in WebSocketClasses.
        /// Please do not use this on Mono or versions of Windows below 8/8.1</param>
        public void Connect(bool useDotNetWebsocket = false)
        {
            CurrentGatewayURL = GetGatewayUrl();
            if (string.IsNullOrEmpty(CurrentGatewayURL))
            {
                DebugLogger.Log("Gateway URL was null or empty?!", MessageLevel.Critical);
                return;
            }
            DebugLogger.Log("Gateway retrieved: " + CurrentGatewayURL);

            if (useDotNetWebsocket)
            {
                ws = new NetWebSocket(CurrentGatewayURL);
                DebugLogger.Log("Using the built-in .Net websocket..");
            }
            else
            {
                ws = new WebSocketSharpSocket(CurrentGatewayURL);
                DebugLogger.Log("Using WebSocketSharp websocket..");
            }

            ws.MessageReceived += (sender, e) =>
            {
                var message = new JObject();
                try
                {
                    message = JObject.Parse(e.Message);
                }
                catch(Exception ex)
                {
                    DebugLogger.Log($"MessageReceived Error: {ex.Message}\n\n```{e.Message}\n```\n", MessageLevel.Error);
                }

                if (EnableVerboseLogging)
                    if (message["t"].ToString() != "READY")
                        DebugLogger.Log(message.ToString(), MessageLevel.Unecessary);

                if (!message["t"].IsNullOrEmpty()) //contains a t parameter used for client events.
                    ClientPacketReceived(message);
                else
                    MiscellaneousOpcodes(message);

                if (!message["s"].IsNullOrEmpty())
                    Sequence = message["s"].ToObject<int>();

            };
            ws.SocketOpened += (sender, e) =>
            {
                SendIdentifyPacket();
                SocketOpened?.Invoke(this, null);
            };
            ws.SocketClosed += (sender, e) =>
            {
                DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                scev.Code = e.Code;
                scev.Reason = e.Reason;
                scev.WasClean = e.WasClean;
                SocketClosed?.Invoke(this, scev);

                if (Autoconnect && !e.WasClean)
                {
                    PerformReconnection();
                }
            };
            ws.Connect();
            DebugLogger.Log("Connecting..");
        }
Example #4
0
        public void ConnectAndReadMessages()
        {
            ws            = new WebSocket("wss://discordapp.com/hub");
            ws.OnMessage += (sender, e) =>
            {
                var message = JObject.Parse(e.Data);
                switch (message["t"].ToString())
                {
                case ("READY"):
                    using (var sw = new StreamWriter("READY"))
                        sw.Write(message);
                    Me = new DiscordMember {
                        user = new DiscordUser {
                            username = message["d"]["user"]["username"].ToString(),
                            id       = message["d"]["user"]["id"].ToString(), verified = message["d"]["user"]["verified"].ToObject <bool>(), avatar = message["d"]["user"]["avatar"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString()
                        }
                    };
                    HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                    GetChannelsList(message);
                    if (Connected != null)
                    {
                        Connected(this, new DiscordConnectEventArgs {
                            user = Me
                        });                                                                 //Since I already know someone will ask for it.
                    }
                    break;

                case ("PRESENCE_UPDATE"):
                    PresenceUpdateEvents(message);
                    break;

                case ("MESSAGE_UPDATE"):
                    MessageUpdateEvents(message);
                    break;

                case ("TYPING_START"):
                    DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                    if (server != null)
                    {
                        DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                        DiscordMember  uuser   = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString());
                        if (UserTypingStart != null)
                        {
                            UserTypingStart(this, new DiscordTypingStartEventArgs {
                                user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString())
                            });
                        }
                    }
                    break;

                case ("MESSAGE_CREATE"):
                    MessageCreateEvents(message);
                    break;

                case ("CHANNEL_CREATE"):
                    ChannelCreateEvents(message);
                    break;

#if DEBUG
                default:
                    ni.BalloonTipText = "Check console! New message type!";
                    ni.ShowBalloonTip(10 * 1000);
                    Console.WriteLine(message);
                    break;
#endif
                }
            };
            ws.OnOpen += (sender, e) =>
            {
                DiscordInitObj initObj = new DiscordInitObj();
                initObj.op      = 2;
                initObj.d.token = this.token;
                string json = initObj.AsJson();
                ws.Send(json);
                if (SocketOpened != null)
                {
                    SocketOpened(this, null);
                }
                Thread keepAlivetimer = new Thread(KeepAlive);
                keepAlivetimer.Start();
            };
            ws.OnClose += (sender, e) =>
            {
                DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                scev.Code     = e.Code;
                scev.Reason   = e.Reason;
                scev.WasClean = e.WasClean;
                if (SocketClosed != null)
                {
                    SocketClosed(this, scev);
                }
            };
            ws.Connect();
        }
Example #5
0
        public void ConnectAndReadMessages()
        {
            ws = new WebSocket("wss://discordapp.com/hub");
                ws.OnMessage += (sender, e) =>
                {
                    var message = JObject.Parse(e.Data);
                    switch(message["t"].ToString())
                    {
                        case ("READY"):
                            using (var sw = new StreamWriter("READY"))
                                sw.Write(message);
                            Me = new DiscordMember { user = new DiscordUser { username = message["d"]["user"]["username"].ToString(),
                                id = message["d"]["user"]["id"].ToString(), verified = message["d"]["user"]["verified"].ToObject<bool>(), avatar = message["d"]["user"]["avatar"].ToString(), discriminator = message["d"]["user"]["discriminator"].ToString()} };
                            HeartbeatInterval = int.Parse(message["d"]["heartbeat_interval"].ToString());
                            GetChannelsList(message);
                            if (Connected != null)
                                Connected(this, new DiscordConnectEventArgs { user = Me }); //Since I already know someone will ask for it.
                            break;
                        case ("PRESENCE_UPDATE"):
                            PresenceUpdateEvents(message);
                            break;
                        case ("MESSAGE_UPDATE"):
                            MessageUpdateEvents(message);
                            break;
                        case ("TYPING_START"):
                            DiscordServer server = ServersList.Find(x => x.channels.Find(y => y.id == message["d"]["channel_id"].ToString()) != null);
                            if (server != null)
                            {
                                DiscordChannel channel = server.channels.Find(x => x.id == message["d"]["channel_id"].ToString());
                                DiscordMember uuser = server.members.Find(x => x.user.id == message["d"]["user_id"].ToString());
                                if (UserTypingStart != null)
                                    UserTypingStart(this, new DiscordTypingStartEventArgs { user = uuser, channel = channel, timestamp = int.Parse(message["d"]["timestamp"].ToString()) });
                            }
                            break;
                        case ("MESSAGE_CREATE"):
                            MessageCreateEvents(message);
                            break;
                        case ("CHANNEL_CREATE"):
                            ChannelCreateEvents(message);
                            break;
#if DEBUG
                            default:
                            ni.BalloonTipText = "Check console! New message type!";
                            ni.ShowBalloonTip(10 * 1000);
                            Console.WriteLine(message);
                            break;
#endif
                    }
                };
                ws.OnOpen += (sender, e) => 
                {
                    DiscordInitObj initObj = new DiscordInitObj();
                    initObj.op = 2;
                    initObj.d.token = this.token;
                    string json = initObj.AsJson();
                    ws.Send(json);
                    if (SocketOpened != null)
                        SocketOpened(this, null);
                    Thread keepAlivetimer = new Thread(KeepAlive);
                    keepAlivetimer.Start();
                };
                ws.OnClose += (sender, e) =>
                {
                    DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                    scev.Code = e.Code;
                    scev.Reason = e.Reason;
                    scev.WasClean = e.WasClean;
                    if (SocketClosed != null)
                        SocketClosed(this, scev);
                };
                ws.Connect();
        }
        /// <summary>
        /// Runs the websocket connection for the client hooking up the appropriate events.
        /// </summary>
        public void Connect()
        {
            CurrentGatewayURL = GetGatewayUrl();
            if (string.IsNullOrEmpty(CurrentGatewayURL))
            {
                DebugLogger.Log("Gateway URL was null or empty?!", MessageLevel.Critical);
                return;
            }
            DebugLogger.Log("Gateway retrieved: " + CurrentGatewayURL);
            
            ws = new WebSocketSharpSocket(CurrentGatewayURL);
            DebugLogger.Log("Using WebSocketSharp websocket..");
            //catch (PlatformNotSupportedException) //Win7 doesn't support this.
            //{
            //    ws = new NetWebSocket(CurrentGatewayURL);
            //    DebugLogger.Log("Using .Net's built in WebSocket..");
            //}
            ws.MessageReceived += (sender, e) =>
            {
                var message = JObject.Parse(e.Message);

                if (EnableVerboseLogging)
                    if (message["t"].ToString() != "READY")
                        DebugLogger.Log(message.ToString(), MessageLevel.Unecessary);

                if (!message["t"].IsNullOrEmpty()) //contains a t parameter used for client events.
                    ClientPacketReceived(message);
                else
                    MiscellaneousOpcodes(message);

                if (!message["s"].IsNullOrEmpty())
                    Sequence = message["s"].ToObject<int>();

            };
            ws.SocketOpened += (sender, e) =>
            {
                SendIdentifyPacket();
                SocketOpened?.Invoke(this, null);
            };
            ws.SocketClosed += (sender, e) =>
            {
                DiscordSocketClosedEventArgs scev = new DiscordSocketClosedEventArgs();
                scev.Code = e.Code;
                scev.Reason = e.Reason;
                scev.WasClean = e.WasClean;
                SocketClosed?.Invoke(this, scev);

                if (Autoconnect && !e.WasClean)
                {
                    PerformReconnection();
                }
            };
            ws.Connect();
            DebugLogger.Log("Connecting..");
        }