示例#1
0
        /// ///////////////////////////////////////////////

        /// Message functions /////////////////////////////
        private static bool SendMessage(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                plugin.Error("Tried to send message but it was null or empty.");
                return(true);
            }

            // Abort if client is dead
            if (socket == null || !socket.Connected)
            {
                plugin.VerboseWarn("Error sending message '" + message + "' to bot: Not connected.");
                return(false);
            }

            // Try to send the message to the bot
            try
            {
                byte[] data = System.Text.Encoding.UTF8.GetBytes(message + '\0');
                socket.Send(data);

                plugin.Debug("Sent message '" + message + "' to bot.");
                return(true);
            }
            catch (Exception e)
            {
                plugin.Error("Error sending message '" + message + "' to bot.");
                plugin.Error(e.ToString());
                if (!(e is InvalidOperationException || e is ArgumentNullException || e is SocketException))
                {
                    throw;
                }
            }
            return(false);
        }
示例#2
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;
                    }
                }
            }
        }
        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.");
            }
        }
示例#4
0
        /// ///////////////////////////////////////////////

        /// Message functions /////////////////////////////
        private static bool SendMessage(MessageWrapper message)
        {
            if (message == null)
            {
                plugin.Error("Tried to send message but it was null.");
                return(true);
            }

            // Abort if client is dead
            if (socket == null || networkStream == null || !socket.Connected)
            {
                plugin.VerboseWarn("Error sending message '" + message.MessageCase.ToString() + "' to bot: Not connected.");
                return(false);
            }

            // Try to send the message to the bot
            try
            {
                message.WriteDelimitedTo(networkStream);
                plugin.Debug("Sent message '" + message.MessageCase.ToString() + "' to bot.");
                return(true);
            }
            catch (Exception e)
            {
                plugin.Error("Error sending message '" + message.MessageCase.ToString() + "' to bot.");
                plugin.Error(e.ToString());
                if (!(e is InvalidOperationException || e is ArgumentNullException || e is SocketException))
                {
                    throw;
                }
            }
            return(false);
        }
示例#5
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.");
            }
        }
        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);
            }
        }
示例#7
0
        public BotListener(SCPDiscord plugin)
        {
            this.plugin = plugin;
            while (true)
            {
                try
                {
                    //Listen for connections
                    if (NetworkSystem.IsConnected())
                    {
                        MessageWrapper data;
                        try
                        {
                            data = MessageWrapper.Parser.ParseDelimitedFrom(NetworkSystem.networkStream);
                        }
                        catch (Exception e)
                        {
                            if (e is IOException)
                            {
                                plugin.Error("Connection to bot lost.");
                            }

                            else
                            {
                                plugin.Error("Couldnt parse incoming packet!\n" + e.ToString());
                            }

                            return;
                        }

                        plugin.Debug("Incoming packet: " + Google.Protobuf.JsonFormatter.Default.Format(data));

                        switch (data.MessageCase)
                        {
                        case MessageWrapper.MessageOneofCase.SyncRoleCommand:
                            plugin.SendStringByID(data.SyncRoleCommand.ChannelID, plugin.roleSync.AddPlayer(data.SyncRoleCommand.SteamID.ToString(), data.SyncRoleCommand.DiscordID));
                            break;

                        case MessageWrapper.MessageOneofCase.UnsyncRoleCommand:
                            plugin.SendStringByID(data.UnsyncRoleCommand.ChannelID, plugin.roleSync.RemovePlayer(data.UnsyncRoleCommand.DiscordID));
                            break;

                        case MessageWrapper.MessageOneofCase.ConsoleCommand:
                            string[] words    = data.ConsoleCommand.Command.Split(' ');
                            string   response = plugin.ConsoleCommand(plugin.PluginManager.Server, words[0], words.Skip(1).ToArray());
                            Dictionary <string, string> variables = new Dictionary <string, string>
                            {
                                { "feedback", response }
                            };
                            plugin.SendMessageByID(data.ConsoleCommand.ChannelID, "botresponses.consolecommandfeedback", variables);
                            break;

                        case MessageWrapper.MessageOneofCase.RoleResponse:
                            plugin.roleSync.ReceiveQueryResponse(data.RoleResponse.SteamID, data.RoleResponse.RoleIDs.ToList());
                            break;

                        case MessageWrapper.MessageOneofCase.BanCommand:
                            BanCommand(data.BanCommand.ChannelID, data.BanCommand.SteamID.ToString(), data.BanCommand.Duration, data.BanCommand.Reason, data.BanCommand.AdminTag);
                            break;

                        case MessageWrapper.MessageOneofCase.UnbanCommand:
                            UnbanCommand(data.UnbanCommand.ChannelID, data.UnbanCommand.SteamIDOrIP);
                            break;

                        case MessageWrapper.MessageOneofCase.KickCommand:
                            KickCommand(data.KickCommand.ChannelID, data.KickCommand.SteamID.ToString(), data.KickCommand.Reason, data.KickCommand.AdminTag);
                            break;

                        case MessageWrapper.MessageOneofCase.KickallCommand:
                            KickallCommand(data.KickallCommand.ChannelID, data.KickallCommand.Reason, data.KickallCommand.AdminTag);
                            break;

                        case MessageWrapper.MessageOneofCase.ListCommand:
                            var reply = "```md\n# Players online (" + (plugin.Server.NumPlayers - 1) + "):\n";
                            foreach (Player player in plugin.Server.GetPlayers())
                            {
                                reply += player.Name.PadRight(35) + "<" + player.UserID + ">" + "\n";
                            }
                            reply += "```";
                            plugin.SendStringByID(data.ListCommand.ChannelID, reply);
                            break;

                        case MessageWrapper.MessageOneofCase.BotActivity:
                        case MessageWrapper.MessageOneofCase.ChatMessage:
                        case MessageWrapper.MessageOneofCase.RoleQuery:
                            plugin.Warn("Recieved packet meant for bot: " + Google.Protobuf.JsonFormatter.Default.Format(data));
                            break;

                        default:
                            plugin.Warn("Unknown packet received: " + Google.Protobuf.JsonFormatter.Default.Format(data));
                            break;
                        }
                    }
                    Thread.Sleep(1000);
                }
                catch (Exception ex)
                {
                    plugin.Error("BotListener Error: " + ex);
                }
            }
        }
示例#8
0
        public static void Reload()
        {
            ready  = false;
            plugin = SCPDiscord.plugin;

            // Save default language files
            SaveDefaultLanguages();

            // Read primary language file
            plugin.Info("Loading primary language file...");
            try
            {
                LoadLanguageFile(Config.GetString("settings.language"), false);
            }
            catch (Exception e)
            {
                if (e is DirectoryNotFoundException)
                {
                    plugin.Error("Language directory not found.");
                }
                else if (e is UnauthorizedAccessException)
                {
                    plugin.Error("Primary language file access denied.");
                }
                else if (e is FileNotFoundException)
                {
                    plugin.Error("'" + Config.GetString("settings.language") + ".yml' was not found.");
                }
                else if (e is JsonReaderException || e is YamlException)
                {
                    plugin.Error("'" + Config.GetString("settings.language") + ".yml' formatting error.");
                }
                plugin.Error("Error reading language file '" + Config.GetString("settings.language") + ".yml'. Attempting to initialize backup system...");
                plugin.Debug(e.ToString());
            }

            // Read backup language file if not the same as the primary
            if (Config.GetString("settings.language") != "english")
            {
                plugin.Info("Loading backup language file...");
                try
                {
                    LoadLanguageFile("english", true);
                }
                catch (Exception e)
                {
                    if (e is DirectoryNotFoundException)
                    {
                        plugin.Error("Language directory not found.");
                    }
                    else if (e is UnauthorizedAccessException)
                    {
                        plugin.Error("Backup language file access denied.");
                    }
                    else if (e is FileNotFoundException)
                    {
                        plugin.Error("'" + Config.GetString("settings.language") + ".yml' was not found.");
                    }
                    else if (e is JsonReaderException || e is YamlException)
                    {
                        plugin.Error("'" + Config.GetString("settings.language") + ".yml' formatting error.");
                    }
                    plugin.Error("Error reading backup language file 'english.yml'.");
                    plugin.Debug(e.ToString());
                }
            }
            if (primary == null && backup == null)
            {
                plugin.Error("NO LANGUAGE FILE LOADED! DEACTIVATING SCPDISCORD.");
                plugin.Disable();
            }

            ValidateLanguageStrings();

            ready = true;
        }
        public static void Reload()
        {
            ready         = false;
            plugin        = SCPDiscord.plugin;
            languagesPath = FileManager.GetAppFolder(true, !plugin.GetConfigBool("scpdiscord_languages_global")) + "SCPDiscord/Languages/";

            // Save default language files
            SaveDefaultLanguages();

            // Read primary language file
            plugin.Info("Loading primary language file...");
            try
            {
                LoadLanguageFile(Config.GetString("settings.language"), false);
            }
            catch (Exception e)
            {
                switch (e)
                {
                case DirectoryNotFoundException _:
                    plugin.Error("Language directory not found.");
                    break;

                case UnauthorizedAccessException _:
                    plugin.Error("Primary language file access denied.");
                    break;

                case FileNotFoundException _:
                    plugin.Error("'" + languagesPath + Config.GetString("settings.language") + ".yml' was not found.");
                    break;

                case JsonReaderException _:
                case YamlException _:
                    plugin.Error("'" + languagesPath + Config.GetString("settings.language") + ".yml' formatting error.");
                    break;
                }
                plugin.Error("Error reading primary language file '" + languagesPath + Config.GetString("settings.language") + ".yml'. Attempting to initialize backup system...");
                plugin.Debug(e.ToString());
            }

            // Read backup language file if not the same as the primary
            if (Config.GetString("settings.language") != "english")
            {
                plugin.Info("Loading backup language file...");
                try
                {
                    LoadLanguageFile("english", true);
                }
                catch (Exception e)
                {
                    switch (e)
                    {
                    case DirectoryNotFoundException _:
                        plugin.Error("Language directory not found.");
                        break;

                    case UnauthorizedAccessException _:
                        plugin.Error("Backup language file access denied.");
                        break;

                    case FileNotFoundException _:
                        plugin.Error("'" + languagesPath + Config.GetString("settings.language") + ".yml' was not found.");
                        break;

                    case JsonReaderException _:
                    case YamlException _:
                        plugin.Error("'" + languagesPath + Config.GetString("settings.language") + ".yml' formatting error.");
                        break;
                    }
                    plugin.Error("Error reading backup language file '" + languagesPath + "english.yml'.");
                    plugin.Debug(e.ToString());
                }
            }
            if (primary == null && backup == null)
            {
                plugin.Error("NO LANGUAGE FILE LOADED! DEACTIVATING SCPDISCORD.");
                plugin.Disable();
            }

            if (Config.GetBool("settings.verbose"))
            {
                ValidateLanguageStrings();
            }

            ready = true;
        }