public static void ReceiveData()
 {
     try
     {
         if (!tcpClient.Connected)
         {
             throw new InvalidOperationException("Tcp Client not connected!");
         }
         BinaryFormatter formatter = new BinaryFormatter();
         for (;;)
         {
             SerializedData.SerializedData deserialize =
                 formatter.Deserialize(tcpClient.GetStream()) as SerializedData.SerializedData;
             if (deserialize == null)
             {
                 continue;
             }
             dataQueue.Enqueue(deserialize);
         }
     }
     catch (SerializationException)
     {
         _init = new Thread(Init);
         _init.Start();
     }
     catch (IOException)
     {
         _init = new Thread(Init);
         _init.Start();
     }
     catch (Exception e)
     {
         Plugin.Error(e.ToString());
     }
 }
        public static void SendData(string data, ulong channel)
        {
            try
            {
                if (tcpClient == null || !tcpClient.Connected)
                {
                    return;
                }

                SerializedData.SerializedData serializedData = new SerializedData.SerializedData
                {
                    Data = data, Port = ServerConsole.Port, Channel = channel
                };
                if (Plugin.Egg)
                {
                    serializedData = new SerializedData.SerializedData
                    {
                        Data = data, Port = ServerConsole.Port + 4130, Channel = channel
                    }
                }
                ;
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(tcpClient.GetStream(), serializedData);
                Plugin.Debug($"Sent {data}");
            }
            catch (IOException)
            {
                _init = new Thread(Init);
                _init.Start();
            }
            catch (Exception e)
            {
                Plugin.Error(e.ToString());
            }
        }
        public static void SendData(string data, int port, string name, ulong channel = 0)
        {
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                SerializedData.SerializedData serializedData =
                    new SerializedData.SerializedData {
                    Data = data, Port = port, Channel = channel, Name = name
                };
                //Console.WriteLine($"Sending {serializedData.Data}");
                if (!bag.ContainsKey(port))
                {
                    Console.WriteLine($"STT: Bag does not contain {port}");
                    return;
                }

                if (bag[port] != null && bag[port].Connected)
                {
                    formatter.Serialize(bag[port].GetStream(), serializedData);
                }
                else
                {
                    Console.WriteLine($"Error - Bag {port} is null or not connected.");
                    if (bag.TryRemove(port, out TcpClient client))
                    {
                        client.Dispose();
                    }
                }
            }
            catch (IOException s)
            {
                Console.WriteLine($"STT: Socket exception, removing..");
                KeyValuePair <int, TcpClient> thingything = default;
                foreach (var thing in bag)
                {
                    if (thing.Key == port)
                    {
                        thingything = thing;
                    }
                }

                if (bag.TryRemove(thingything.Key, out TcpClient _client))
                {
                    _client.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
        public static async Task ReceiveData(SerializedData.SerializedData data, TcpClient client)
        {
            try
            {
                if (data == null)
                {
                    Console.WriteLine("STT: Received data null");
                    return;
                }

                Program.Log($"Receiving data: {data.Data} Channel: {data.Channel} for {data.Port}", true);
                if (data.Data.Contains("REQUEST_DATA PLAYER_LIST SILENT"))
                {
                    return;
                }
                SocketGuild guild = Bot.Client.Guilds.FirstOrDefault();

                if (data.Data.StartsWith("checksync"))
                {
                    string[] args = data.Data.Split(' ');
                    Program.Log($"Checking rolesync for {args[1]}", true);
                    SyncedUser user = Program.Users.FirstOrDefault(u => u.UserId == args[1]);
                    if (user == null)
                    {
                        Program.Log($"Role sync for {args[1]} not found.", true);
                        return;
                    }

                    foreach (SocketRole role in guild.GetUser(user.DiscordId).Roles)
                    {
                        if (Program.SyncedGroups.ContainsKey(role.Id))
                        {
                            SendData($"setgroup {user.UserId} {Program.SyncedGroups[role.Id]}", Program.Config.Port, "RoleSync");
                        }
                    }
                }
                if (data.Data == "ping")
                {
                    if (!bag.ContainsKey(data.Port))
                    {
                        Console.WriteLine($"STT: Adding {data.Port}");
                        bag.TryAdd(data.Port, client);
                    }

                    if (!bag[data.Port].Connected || bag[data.Port] == null)
                    {
                        Console.WriteLine($"STT: Bag {data.Port} not connected or null, removing.");
                        if (bag.TryRemove(data.Port, out TcpClient cli))
                        {
                            cli?.Close();
                        }
                    }
                    Console.WriteLine($"STT: Received heartbeat for: {data.Port}");
                    if (!heartbeats.ContainsKey(data.Port))
                    {
                        Heartbeat(data.Port);
                        heartbeats.TryAdd(data.Port, 0);
                    }
                    else
                    {
                        heartbeats[data.Port]--;
                    }

                    Program.Log($"Updating channelID's for plugin..{data.Port}", true);
                    try
                    {
                        Program.Log($"GameChannelID: {GameChannelId}", true);
                        SendData("set gameid", data.Port, "bot", GameChannelId);
                        Program.Log($"CommandChannelID: {CmdChannelId}", true);
                        SendData("set cmdid", data.Port, "bot", CmdChannelId);
                    }
                    catch (Exception e)
                    {
                        Program.Log(e.ToString());
                    }

                    return;
                }

                if (data.Data.StartsWith("channelstatus"))
                {
                    /*  -- Disabled due to Discord.NET bug.
                     * Program.Log($"updating channel topic", true);
                     * string status = data.Data.Replace("channelstatus", "");
                     * SocketTextChannel chan1 = guild.GetTextChannel(GameChannelId);
                     * await chan1.ModifyAsync(x => x.Topic = status);
                     * SocketTextChannel chan2 = guild.GetTextChannel(CmdChannelId);
                     * await chan2.ModifyAsync(x => x.Topic = status);
                     */

                    return;
                }

                if (data.Data.StartsWith("updateStatus"))
                {
                    Program.Log($"updating status for bot", true);
                    string status = data.Data.Replace("updateStatus ", "");
                    if (status.StartsWith("0"))
                    {
                        await Bot.Client.SetStatusAsync(UserStatus.Idle);
                    }
                    else
                    {
                        await Bot.Client.SetStatusAsync(UserStatus.Online);
                    }
                    await Bot.Client.SetActivityAsync(new Game(status));

                    return;
                }
                data.Data = data.Data.Substring(data.Data.IndexOf('#') + 1);



                Console.WriteLine("Getting guild.");
                Console.WriteLine("Getting channel");
                if (guild == null)
                {
                    Console.WriteLine("Guild not found.");
                    return;
                }

                SocketTextChannel chan = null;
                if (data.Channel == 1)
                {
                    chan = guild.GetTextChannel(GameChannelId);
                }
                else if (data.Channel == 2)
                {
                    chan = guild.GetTextChannel(CmdChannelId);
                }
                else
                {
                    chan = guild.GetTextChannel(data.Channel);
                }

                if (chan == null)
                {
                    await Program.Log(new LogMessage(LogSeverity.Critical, "recievedData", "Channel not found."));

                    return;
                }

                if (chan.Id == Program.Config.GameLogChannelId || chan.Id == Program.Config.CommandLogChannelId)
                {
                    Program.Log("Storing message.", true);
                    lock (_messages)
                    {
                        if (!_messages.ContainsKey(chan.Id))
                        {
                            _messages.Add(chan.Id, string.Empty);
                        }
                        _messages[chan.Id] += $"[{DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}] {data.Data} {Environment.NewLine}".Replace("<", "<​").Replace("@everyone", "@​everyone").Replace("@here", "@​here");
                    }
                    return;
                }
                Console.WriteLine("Sending message.");
                await chan.SendMessageAsync($"[{DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}] {data.Data}".Replace("<", "<​").Replace("@everyone", "@​everyone").Replace("@here", "@​here"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
示例#5
0
        public static async Task ReceiveData(SerializedData.SerializedData data, TcpClient client)
        {
            try
            {
                if (data == null)
                {
                    Console.WriteLine("Network: Received data null");
                    return;
                }

                if (data.Data.Contains("REQUEST_DATA PLAYER_LIST SILENT"))
                {
                    return;
                }
                SocketGuild guild = Bot.Client.Guilds.FirstOrDefault();

                if (data.Data.StartsWith("checksync"))
                {
                    string[]   args = data.Data.Split(' ');
                    SyncedUser user = Program.Users.FirstOrDefault(u => u.UserId == args[1]);
                    if (user == null)
                    {
                        return;
                    }

                    foreach (SocketRole role in guild.GetUser(user.DiscordId).Roles)
                    {
                        if (Program.SyncedGroups.ContainsKey(role.Id))
                        {
                            SendData($"setgroup {user.UserId} {Program.SyncedGroups[role.Id]}", Config.Port, "RoleSync");
                        }
                    }
                }
                if (data.Data == "ping")
                {
                    if (!bag.ContainsKey(data.Port))
                    {
                        Console.WriteLine($"Network: Adding {data.Port}");
                        bag.TryAdd(data.Port, client);
                    }

                    if (!bag[data.Port].Connected || bag[data.Port] == null)
                    {
                        Console.WriteLine($"Network: Bag {data.Port} not connected or null, removing.");
                        if (bag.TryRemove(data.Port, out TcpClient cli))
                        {
                            cli?.Close();
                        }
                    }
                    Console.WriteLine($"Network: Received heartbeat for: {data.Port}");
                    if (!heartbeats.ContainsKey(data.Port))
                    {
                        Heartbeat(data.Port);
                        heartbeats.TryAdd(data.Port, 0);
                    }
                    else
                    {
                        heartbeats[data.Port]--;
                    }
                    return;
                }

                if (data.Data.StartsWith("updateStatus"))
                {
                    string status = data.Data.Replace("updateStatus ", "");
                    if (status.StartsWith("0"))
                    {
                        await Bot.Client.SetStatusAsync(UserStatus.Idle);
                    }
                    else
                    {
                        await Bot.Client.SetStatusAsync(UserStatus.Online);
                    }
                    await Bot.Client.SetActivityAsync(new Game(status));

                    return;
                }

                if (data.Data.StartsWith("embed"))
                {
                    try
                    {
                        Console.WriteLine($"Received embed: \"{data.Data.Replace("embed ", "")}\"");
                        Console.WriteLine("Splitting");
                        string[] embedData = data.Data.Replace("embed ", "").Split('+');
                        Console.WriteLine("Initializing EmbedBuilder");
                        EmbedBuilder embedBuilder = new EmbedBuilder();
                        Embed        embed;
                        Console.WriteLine("Setting color");
                        embedBuilder.WithColor(Color.Red);

                        if (!string.IsNullOrEmpty(embedData[0]) && embedData[0] != "none")
                        {
                            Console.WriteLine($"Setting title: {embedData[0]}");
                            embedBuilder.WithTitle(embedData[0]);
                        }

                        if (!string.IsNullOrEmpty(embedData[1]))
                        {
                            Console.WriteLine($"Setting description: {embedData[1]}");
                            embedBuilder.WithDescription(embedData[1]);
                        }

                        if (!string.IsNullOrEmpty(embedData[2]))
                        {
                            Console.WriteLine($"Setting footer: {embedData[2]}");
                            EmbedFooterBuilder embedFooterBuilder = new EmbedFooterBuilder();
                            embedFooterBuilder.WithText(embedData[2]);
                            embedBuilder.WithFooter(embedFooterBuilder);
                        }

                        Console.WriteLine("Building embed");
                        embed = embedBuilder.Build();
                        Console.WriteLine($"Sending embed to {data.Channel}");
                        await API.API.SendEmbed(embed, data.Channel);

                        return;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        return;
                    }
                }

                if (data.Data.StartsWith("cmdresp"))
                {
                    try
                    {
                        Console.WriteLine($"Received command embed response: \"{data.Data.Replace("embed ", "")}\"");
                        Console.WriteLine("Getting description");
                        string description = data.Data.Replace("cmdresp ", "");
                        description = $"```{description.Substring(description.IndexOf("#") + 1)}```";
                        Console.WriteLine("Initializing EmbedBuilder");
                        EmbedBuilder embedBuilder = new EmbedBuilder();
                        Embed        embed;
                        Console.WriteLine("Setting properties");
                        embedBuilder.WithColor(Color.Blue);
                        embedBuilder.WithDescription(description);
                        embedBuilder.WithCurrentTimestamp();
                        Console.WriteLine("Building embed");
                        embed = embedBuilder.Build();
                        Console.WriteLine($"Sending embed to {data.Channel}");
                        await API.API.SendEmbed(embed, data.Channel);

                        return;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        return;
                    }
                }

                data.Data = data.Data.Substring(data.Data.IndexOf('#') + 1);
                if (guild == null)
                {
                    return;
                }
                SocketTextChannel chan = null;
                chan = data.Channel.GetChannel();

                if (chan == null)
                {
                    return;
                }

                await chan.SendMessageAsync($"[{DateTime.Now.ToString("HH:mm:ss")}] {data.Data}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }