Exemplo n.º 1
0
        private static void Connect()
        {
            plugin.Verbose("Attempting Bot Connection...");
            plugin.Verbose("Your Bot IP: " + Config.GetString("bot.ip") + ". Your Bot Port: " + Config.GetInt("bot.port") + ".");

            while (!IsConnected())
            {
                try
                {
                    if (socket != null && socket.IsBound)
                    {
                        //socket.Shutdown(SocketShutdown.Both);
                        messageThread?.Abort();
                        socket.Close();
                    }

                    socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socket.Connect(Config.GetString("bot.ip"), Config.GetInt("bot.port"));
                    messageThread = new Thread(() => new BotListener(plugin));
                    messageThread.Start();

                    networkStream = new NetworkStream(socket);

                    plugin.Info("Connected to Discord bot.");
                    plugin.SendMessage(Config.GetArray("channels.statusmessages"), "botmessages.connectedtobot");
                }
                catch (SocketException e)
                {
                    plugin.VerboseError("Error occured while connecting to discord bot server: " + e.Message.Trim());
                    plugin.DebugError(e.ToString());
                    Thread.Sleep(5000);
                }
                catch (ObjectDisposedException e)
                {
                    plugin.VerboseError("TCP client was unexpectedly closed.");
                    plugin.DebugError(e.ToString());
                    Thread.Sleep(5000);
                }
                catch (ArgumentOutOfRangeException e)
                {
                    plugin.VerboseError("Invalid port.");
                    plugin.DebugError(e.ToString());
                    Thread.Sleep(5000);
                }
                catch (ArgumentNullException e)
                {
                    plugin.VerboseError("IP address is null.");
                    plugin.DebugError(e.ToString());
                    Thread.Sleep(5000);
                }
            }
        }
Exemplo n.º 2
0
 /// <summary>
 /// Gets a string from the primary or backup language file
 /// </summary>
 /// <param name="path">The path to the node</param>
 /// <returns></returns>
 public static string GetString(string path)
 {
     if (primary == null && backup == null)
     {
         plugin.Verbose("Tried to send Discord message before loading languages.");
         return(null);
     }
     try
     {
         return(primary?.SelectToken(path).Value <string>());
     }
     catch (Exception primaryException)
     {
         // This exception means the node does not exist in the language file, the plugin attempts to find it in the backup file
         if (primaryException is NullReferenceException || primaryException is ArgumentNullException || primaryException is InvalidCastException || primaryException is JsonException)
         {
             plugin.Warn("Error reading string '" + path + "' from primary language file, switching to backup...");
             try
             {
                 return(backup.SelectToken(path).Value <string>());
             }
             // The node also does not exist in the backup file
             catch (NullReferenceException e)
             {
                 plugin.Error("Error: Language language string '" + path + "' does not exist. Message can not be sent." + e);
                 return(null);
             }
             catch (ArgumentNullException e)
             {
                 plugin.Error("Error: Language language string '" + path + "' does not exist. Message can not be sent." + e);
                 return(null);
             }
             catch (InvalidCastException e)
             {
                 plugin.Error(e.ToString());
                 throw;
             }
             catch (JsonException e)
             {
                 plugin.Error(e.ToString());
                 throw;
             }
         }
         else
         {
             plugin.Error(primaryException.ToString());
             throw;
         }
     }
 }
Exemplo n.º 3
0
        public void ReceiveQueryResponse(string steamID, string jsonString)
        {
            Player player = plugin.Server.GetPlayers(steamID)[0];

            if (player != null)
            {
                List <string> roles = JArray.Parse(jsonString).Values <string>().ToList();
                foreach (KeyValuePair <string, string[]> keyValuePair in this.roleDictionary)
                {
                    if (roles.Contains(keyValuePair.Key))
                    {
                        Dictionary <string, string> variables = new Dictionary <string, string>
                        {
                            { "ipaddress", player.IpAddress },
                            { "name", player.Name },
                            { "playerid", player.PlayerId.ToString() },
                            { "steamid", player.SteamId }
                        };
                        foreach (string unparsedCommand in keyValuePair.Value)
                        {
                            string command = unparsedCommand;
                            // Variable insertion
                            foreach (KeyValuePair <string, string> variable in variables)
                            {
                                command = command.Replace("<var:" + variable.Key + ">", variable.Value);
                            }
                            plugin.Debug(this.plugin.ConsoleCommand(null, command.Split(' ')[0], command.Split(' ').Skip(1).ToArray()));
                        }

                        plugin.Verbose("Synced " + player.Name);
                        return;
                    }
                }
            }
        }
Exemplo n.º 4
0
        public void ReceiveQueryResponse(string userID, List <ulong> roleIDs)
        {
            try
            {
                Player player;
                try {
                    plugin.Debug("Syncing User: "******"Player found on server: " + plugin.Server.GetPlayers(userID).Any());
                    player = plugin.Server.GetPlayers(userID)?.FirstOrDefault();
                }
                catch (NullReferenceException e)
                {
                    plugin.Error("Error getting player for RoleSync: " + e);
                    return;
                }

                if (player == null)
                {
                    plugin.Error("Could not get player for rolesync, did they disconnect immediately?");
                    return;
                }

                foreach (KeyValuePair <ulong, string[]> keyValuePair in roleDictionary)
                {
                    plugin.Debug("User has discord role " + keyValuePair.Key + ": " + roleIDs.Contains(keyValuePair.Key));
                    if (roleIDs.Contains(keyValuePair.Key))
                    {
                        Dictionary <string, string> variables = new Dictionary <string, string>
                        {
                            { "ipaddress", player.IPAddress },
                            { "name", player.Name },
                            { "playerid", player.PlayerID.ToString() },
                            { "userid", player.UserID },
                            { "steamid", player.GetParsedUserID() }
                        };
                        foreach (string unparsedCommand in keyValuePair.Value)
                        {
                            string command = unparsedCommand;
                            // Variable insertion
                            foreach (KeyValuePair <string, string> variable in variables)
                            {
                                command = command.Replace("<var:" + variable.Key + ">", variable.Value);
                            }
                            plugin.Debug("Running rolesync command: " + command);
                            plugin.Debug("Command response: " + plugin.ConsoleCommand(null, command.Split(' ')[0], command.Split(' ').Skip(1).ToArray()));
                        }

                        plugin.Verbose("Synced " + player.Name + " (" + player.UserID + ") with Discord role id " + keyValuePair.Key);
                        return;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                plugin.Warn("Tried to run commands on a player who is not on the server anymore.");
            }
        }
Exemplo n.º 5
0
        public void ReceiveQueryResponse(string userID, string jsonString)
        {
            try
            {
                Player player;
                try
                {
                    player = plugin.Server.GetPlayers(userID)?.First();
                }
                catch (NullReferenceException e)
                {
                    plugin.Error("Error getting player for RoleSync: " + e);
                    return;
                }

                if (player == null)
                {
                    plugin.Error("Could not get player for rolesync, did they disconnect immediately?");
                    return;
                }

                List <string> roles = JArray.Parse(jsonString).Values <string>().ToList();
                foreach (KeyValuePair <string, string[]> keyValuePair in this.roleDictionary)
                {
                    if (roles.Contains(keyValuePair.Key))
                    {
                        Dictionary <string, string> variables = new Dictionary <string, string>
                        {
                            { "ipaddress", player.IpAddress },
                            { "name", player.Name },
                            { "playerid", player.PlayerId.ToString() },
                            { "userid", player.UserId },
                            { "steamid", player.GetParsedUserID() }
                        };
                        foreach (string unparsedCommand in keyValuePair.Value)
                        {
                            string command = unparsedCommand;
                            // Variable insertion
                            foreach (KeyValuePair <string, string> variable in variables)
                            {
                                command = command.Replace("<var:" + variable.Key + ">", variable.Value);
                            }
                            plugin.Debug(this.plugin.ConsoleCommand(null, command.Split(' ')[0], command.Split(' ').Skip(1).ToArray()));
                        }

                        plugin.Verbose("Synced " + player.Name);
                        return;
                    }
                }
            }
            catch (InvalidOperationException)
            {
                this.plugin.Warn("Tried to run commands on a player who is not on the server anymore.");
            }
        }
        public BotListener(SCPDiscord plugin)
        {
            this.plugin = plugin;
            while (!plugin.shutdown)
            {
                //Listen for connections
                if (NetworkSystem.IsConnected())
                {
                    try
                    {
                        //Discord messages can be up to 2000 chars long, UTF8 chars can be up to 4 bytes long.
                        byte[] data       = new byte[1000];
                        int    dataLength = NetworkSystem.Receive(data);

                        string incomingData = Encoding.UTF8.GetString(data, 0, dataLength);

                        List <string> messages = new List <string>(incomingData.Split('\n'));

                        //If several messages come in at the same time, process all of them
                        while (messages.Count > 0)
                        {
                            if (messages[0].Length == 0)
                            {
                                messages.RemoveAt(0);
                                continue;
                            }

                            plugin.Debug("Incoming command from discord: " + messages[0]);

                            string[] words = messages[0].Split(' ');
                            if (words[0] == "command")
                            {
                                string   channel    = words[1];
                                string   discordTag = words[2].Replace('_', ' ');
                                string   command    = words[3];
                                string[] arguments  = new string[0];
                                if (words.Length >= 5)
                                {
                                    arguments = words.Skip(4).ToArray();
                                }

                                string response;
                                Dictionary <string, string> variables;

                                switch (command)
                                {
                                case "ban":
                                    //Check if the command has enough arguments
                                    if (arguments.Length >= 2)
                                    {
                                        BanCommand(channel, arguments[0], arguments[1], MergeString(arguments.Skip(2).ToArray()), discordTag);
                                    }
                                    else
                                    {
                                        variables = new Dictionary <string, string>
                                        {
                                            { "command", messages[0] }
                                        };
                                        plugin.SendMessageByID(channel, "botresponses.missingarguments", variables);
                                    }
                                    break;

                                case "kick":
                                    //Check if the command has enough arguments
                                    if (arguments.Length >= 1)
                                    {
                                        KickCommand(channel, arguments[0], MergeString(arguments.Skip(1).ToArray()), discordTag);
                                    }
                                    else
                                    {
                                        variables = new Dictionary <string, string>
                                        {
                                            { "command", messages[0] }
                                        };
                                        plugin.SendMessageByID(channel, "botresponses.missingarguments", variables);
                                    }
                                    break;

                                case "kickall":
                                    KickallCommand(channel, MergeString(arguments), discordTag);
                                    break;

                                case "unban":
                                    //Check if the command has enough arguments
                                    if (arguments.Length >= 1)
                                    {
                                        UnbanCommand(channel, arguments[0]);
                                    }
                                    else
                                    {
                                        variables = new Dictionary <string, string>
                                        {
                                            { "command", messages[0] }
                                        };
                                        plugin.SendMessageByID(channel, "botresponses.missingarguments", variables);
                                    }
                                    break;

                                case "list":
                                    var message = "```md\n# Players online (" + (plugin.Server.NumPlayers - 1) + "):\n";
                                    foreach (Player player in plugin.Server.GetPlayers())
                                    {
                                        message += player.Name.PadRight(35) + "<" + player.UserId + ">" + "\n";
                                    }
                                    message += "```";
                                    NetworkSystem.QueueMessage(channel + message);
                                    break;

                                case "exit":
                                    plugin.SendMessageByID(channel, "botresponses.exit");
                                    break;

                                case "help":
                                    plugin.SendMessageByID(channel, "botresponses.help");
                                    break;

                                case "hidetag":
                                case "showtag":
                                    if (plugin.PluginManager.GetEnabledPlugin("karlofduty.toggletag") != null)
                                    {
                                        if (arguments.Length > 0)
                                        {
                                            command  = "console_" + command;
                                            response = plugin.ConsoleCommand(plugin.PluginManager.Server, command, arguments);

                                            variables = new Dictionary <string, string>
                                            {
                                                { "feedback", response }
                                            };
                                            plugin.SendMessageByID(channel, "botresponses.consolecommandfeedback", variables);
                                        }
                                        else
                                        {
                                            variables = new Dictionary <string, string>
                                            {
                                                { "command", command }
                                            };
                                            plugin.SendMessageByID(channel, "botresponses.missingarguments", variables);
                                        }
                                    }
                                    else
                                    {
                                        plugin.SendMessageByID(channel, "botresponses.toggletag.notinstalled");
                                    }
                                    break;

                                case "vs_enable":
                                case "vs_disable":
                                case "vs_whitelist":
                                case "vs_reload":
                                    if (plugin.PluginManager.GetEnabledPlugin("karlofduty.vpnshield") != null)
                                    {
                                        response = plugin.ConsoleCommand(plugin.PluginManager.Server, command, arguments);

                                        variables = new Dictionary <string, string>
                                        {
                                            { "feedback", response }
                                        };
                                        plugin.SendMessageByID(channel, "botresponses.consolecommandfeedback", variables);
                                    }
                                    else
                                    {
                                        plugin.SendMessageByID(channel, "botresponses.vpnshield.notinstalled");
                                    }
                                    break;

                                case "scperms_reload":
                                case "scperms_giverank":
                                case "scperms_removerank":
                                case "scperms_verbose":
                                case "scperms_debug":
                                case "scpermissions_reload":
                                case "scpermissions_giverank":
                                case "scpermissions_removerank":
                                case "scpermissions_verbose":
                                case "scpermissions_debug":
                                    if (plugin.PluginManager.GetEnabledPlugin("karlofduty.scpermissions") != null)
                                    {
                                        response = plugin.ConsoleCommand(plugin.PluginManager.Server, command, arguments);

                                        variables = new Dictionary <string, string>
                                        {
                                            { "feedback", response }
                                        };
                                        plugin.SendMessageByID(channel, "botresponses.consolecommandfeedback", variables);
                                    }
                                    else
                                    {
                                        plugin.SendMessageByID(channel, "botresponses.scpermissions.notinstalled");
                                    }
                                    break;

                                case "syncrole":
                                    NetworkSystem.QueueMessage(channel + plugin.roleSync.AddPlayer(arguments[0], arguments[1]));
                                    break;

                                case "unsyncrole":
                                    NetworkSystem.QueueMessage(channel + plugin.roleSync.RemovePlayer(arguments[0]));
                                    break;

                                default:
                                    response  = plugin.ConsoleCommand(plugin.PluginManager.Server, command, arguments);
                                    variables = new Dictionary <string, string>
                                    {
                                        { "feedback", response }
                                    };
                                    plugin.SendMessageByID(channel, "botresponses.consolecommandfeedback", variables);
                                    break;
                                }
                            }
                            else if (words[0] == "roleresponse")
                            {
                                plugin.roleSync.ReceiveQueryResponse(words[1] + "@steam", MergeString(words.Skip(2).ToArray()));
                            }
                            plugin.Verbose("From discord: " + messages[0]);

                            messages.RemoveAt(0);
                        }
                    }
                    catch (Exception ex)
                    {
                        plugin.Error("BotListener Error: " + ex);
                    }
                }
                Thread.Sleep(1000);
            }
        }
Exemplo n.º 7
0
        internal static void Reload(SCPDiscord plugin)
        {
            ready = false;
            plugin.SetUpFileSystem();

            // Reads file contents into FileStream
            FileStream stream = File.OpenRead(FileManager.GetAppFolder(true, !plugin.GetConfigBool("scpdiscord_config_global")) + "SCPDiscord/config.yml");

            // Converts the FileStream into a YAML Dictionary object
            IDeserializer deserializer = new DeserializerBuilder().Build();
            object        yamlObject   = deserializer.Deserialize(new StreamReader(stream));

            // Converts the YAML Dictionary into JSON String
            ISerializer serializer = new SerializerBuilder()
                                     .JsonCompatible()
                                     .Build();
            string jsonString = serializer.Serialize(yamlObject);

            JObject json = JObject.Parse(jsonString);

            plugin.Verbose("Reading config validation");

            // Reads the configvalidation node first as it is used for reading the others
            try
            {
                configBools["settings.configvalidation"] = json.SelectToken("settings.configvalidation").Value <bool>();
            }
            catch (ArgumentNullException)
            {
                plugin.Warn("Config bool 'settings.configvalidation' not found, using default value: true");
            }

            // Read config strings
            foreach (KeyValuePair <string, string> node in configStrings.ToList())
            {
                try
                {
                    configStrings[node.Key] = json.SelectToken(node.Key).Value <string>();
                }
                catch (ArgumentNullException)
                {
                    plugin.Warn("Config string '" + node.Key + "' not found, using default value: \"" + node.Value + "\"");
                }
            }

            // Read config ints
            foreach (KeyValuePair <string, int> node in configInts.ToList())
            {
                try
                {
                    configInts[node.Key] = json.SelectToken(node.Key).Value <int>();
                }
                catch (ArgumentNullException)
                {
                    plugin.Warn("Config int '" + node.Key + "' not found, using default value: \"" + node.Value + "\"");
                }
            }

            // Read config bools
            foreach (KeyValuePair <string, bool> node in configBools.ToList().Where(kvm => kvm.Key != "settings.configvalidation"))
            {
                try
                {
                    configBools[node.Key] = json.SelectToken(node.Key).Value <bool>();
                }
                catch (ArgumentNullException)
                {
                    plugin.Warn("Config bool '" + node.Key + "' not found, using default value: " + node.Value);
                }
            }

            // Read config arrays
            foreach (KeyValuePair <string, string[]> node in configArrays.ToList())
            {
                try
                {
                    configArrays[node.Key] = json.SelectToken(node.Key).Value <JArray>().Values <string>().ToArray();
                }
                catch (ArgumentNullException)
                {
                    plugin.Warn("Config array '" + node.Key + "' not found, using default value: []");
                }
            }

            // Read config dictionaries
            foreach (KeyValuePair <string, Dictionary <string, ulong> > node in configDicts.ToList())
            {
                try
                {
                    configDicts[node.Key] = json.SelectToken(node.Key).Value <JArray>().ToDictionary(k => ((JObject)k).Properties().First().Name, v => v.Values().First().Value <ulong>());
                }
                catch (ArgumentNullException)
                {
                    plugin.Warn("Config dictionary '" + node.Key + "' not found, using default value: []");
                }
            }

            // Read rolesync system
            if (GetBool("settings.rolesync"))
            {
                try
                {
                    plugin.roleSync.roleDictionary = json.SelectToken("rolesync").Value <JArray>().ToDictionary(k => ulong.Parse(((JObject)k).Properties().First().Name), v => v.Values().First().Value <JArray>().Values <string>().ToArray());
                }
                catch (Exception)
                {
                    plugin.Warn("The rolesync config list is invalid, rolesync disabled.");
                    SetBool("settings.rolesync", false);
                }
            }

            if (GetBool("settings.configvalidation") && GetBool("settings.verbose"))
            {
                ValidateConfig(plugin);
            }

            ready = true;
        }