/// <summary> /// Makes sure all plugin files exist. /// </summary> public void SetUpFileSystem() { if (!Directory.Exists(FileManager.GetAppFolder(GetConfigBool("scpdiscord_config_global")) + "SCPDiscord")) { Directory.CreateDirectory(FileManager.GetAppFolder(GetConfigBool("scpdiscord_config_global")) + "SCPDiscord"); } if (!Directory.Exists(FileManager.GetAppFolder(GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord")) { Directory.CreateDirectory(FileManager.GetAppFolder(GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord"); } if (!Directory.Exists(FileManager.GetAppFolder(GetConfigBool("scpdiscord_languages_global")) + "SCPDiscord")) { Directory.CreateDirectory(FileManager.GetAppFolder(GetConfigBool("scpdiscord_languages_global")) + "SCPDiscord"); } if (!File.Exists(FileManager.GetAppFolder(GetConfigBool("scpdiscord_config_global")) + "SCPDiscord/config.yml")) { this.Info("Config file '" + FileManager.GetAppFolder(GetConfigBool("scpdiscord_config_global")) + "SCPDiscord/config.yml' does not exist, creating..."); File.WriteAllText(FileManager.GetAppFolder(GetConfigBool("scpdiscord_config_global")) + "SCPDiscord/config.yml", Encoding.UTF8.GetString(Resources.config)); } // ReSharper disable once InvertIf if (!File.Exists(FileManager.GetAppFolder(GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord/rolesync.json")) { plugin.Info("Config file rolesync.json does not exist, creating..."); File.WriteAllText(FileManager.GetAppFolder(GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord/rolesync.json", "[]"); } }
public string[] OnCall(ICommandSender sender, string[] args) { plugin.Info("Reloading plugin..."); Config.Reload(plugin); plugin.Info("Successfully loaded config '" + plugin.GetConfigString("scpdiscord_config") + "'."); Language.Reload(); plugin.roleSync.Reload(); if (NetworkSystem.IsConnected()) { NetworkSystem.Disconnect(); } return(new string[] { "Reload complete." }); }
public void ReceiveQueryResponse(string steamID, string gameRole) { Player player = plugin.Server.GetPlayers(steamID)[0]; if (player != null) { player.SetRank("", "", gameRole); plugin.Info(player.GetUserGroup().Name); if (Config.GetBool("settings.verbose")) { plugin.Info("Set " + player.Name + "'s rank to " + gameRole + "."); } } }
public static void ValidateConfig(SCPDiscord plugin) { StringBuilder sb = new StringBuilder(); sb.Append("||||||||||||| SCPDiscord config validator ||||||||||||||\n"); sb.Append("------------ Config strings ------------\n"); foreach (KeyValuePair <string, string> node in configStrings) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config ints ------------\n"); foreach (KeyValuePair <string, bool> node in configBools) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config bools ------------\n"); foreach (KeyValuePair <string, bool> node in configBools) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config arrays ------------\n"); foreach (KeyValuePair <string, string[]> node in configArrays) { sb.Append(node.Key + ": [ " + string.Join(", ", node.Value) + " ]\n"); if (node.Key.StartsWith("channels.")) { foreach (string s in node.Value) { if (!GetDict("aliases").ContainsKey(s)) { sb.Append("WARNING: Channel alias '" + s + "' does not exist!\n"); } } } } sb.Append("------------ Config dictionaries ------------\n"); foreach (KeyValuePair <string, Dictionary <string, string> > node in configDicts) { sb.Append(node.Key + ":\n"); foreach (KeyValuePair <string, string> subNode in node.Value) { if (!Regex.IsMatch(subNode.Value, @"^\d+$")) { sb.Append("WARNING: Invalid channel ID: " + subNode.Value + "!\n"); } sb.Append(" " + subNode.Key + ": " + subNode.Value + "\n"); } } sb.Append("|||||||||||||||||||||||||||||||||||||||||||||||||||||||"); plugin.Info(sb.ToString()); }
/// <summary> /// Saves all default language files included in the .dll /// </summary> public static void SaveDefaultLanguages() { foreach (KeyValuePair <string, string> language in defaultLanguages) { if (!File.Exists(languagesPath + language.Key + ".yml")) { plugin.Info("Creating language file " + language.Key + ".yml..."); try { File.WriteAllText((languagesPath + language.Key + ".yml"), language.Value); } catch (DirectoryNotFoundException) { plugin.Warn("Could not create language file: Language directory does not exist, attempting to create it... "); Directory.CreateDirectory(languagesPath); plugin.Info("Creating language file " + language.Key + ".yml..."); File.WriteAllText((languagesPath + language.Key + ".yml"), language.Value); } } } }
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); } } }
public void SetUpFileSystem() { if (!Directory.Exists(FileManager.GetAppFolder() + "SCPDiscord")) { Directory.CreateDirectory(FileManager.GetAppFolder() + "SCPDiscord"); } if (!File.Exists(FileManager.GetAppFolder() + "SCPDiscord/" + GetConfigString("scpdiscord_config"))) { this.Info("Config file " + GetConfigString("scpdiscord_config") + " does not exist, creating..."); File.WriteAllText(FileManager.GetAppFolder() + "SCPDiscord/" + GetConfigString("scpdiscord_config"), Encoding.UTF8.GetString(Resources.config)); } if (!File.Exists(FileManager.GetAppFolder() + "SCPDiscord/rolesync.json")) { plugin.Info("Config file rolesync.json does not exist, creating..."); File.WriteAllText(FileManager.GetAppFolder() + "SCPDiscord/rolesync.json", "[]"); } }
/// /////////////////////////////////////////////// /// Channel topic refreshing ////////////////////// private static void RefreshChannelTopic(SCPDiscord plugin, string channelID, float tps) { Dictionary <string, string> variables = new Dictionary <string, string>(); try { Server server = plugin.pluginManager.Server; Dictionary <string, string> serverVariables; if (server != null) { serverVariables = new Dictionary <string, string> { { "players", (server.NumPlayers - 1) + "" }, { "maxplayers", plugin.GetConfigString("max_players") }, { "ip", server.IpAddress }, { "port", server.Port + "" }, { "isvisible", server.Visible + "" }, { "isverified", server.Verified + "" }, { "uptime", (plugin.serverStartTime.ElapsedMilliseconds / 1000 / 60) + "" }, { "tps", tps.ToString("0.00") } }; } else { serverVariables = new Dictionary <string, string> { { "players", "0" }, { "maxplayers", "0" }, { "ip", "---.---.---.---" }, { "port", "----" }, { "isvisible", "False" }, { "isverified", "False" }, { "uptime", "0" }, { "tps", tps.ToString("0.00") } }; } Dictionary <string, string> mapVariables; if (server != null && server.Map != null) { mapVariables = new Dictionary <string, string> { //{ "warheaddetonated", server.Map.WarheadDetonated + "" }, { "decontaminated", server.Map.LCZDecontaminated + "" } }; } else { mapVariables = new Dictionary <string, string> { //{ "warheaddetonated", "False" }, { "decontaminated", "False" } }; } Dictionary <string, string> roundVariables; if (server != null && server.Round != null) { roundVariables = new Dictionary <string, string> { { "roundduration", (server.Round.Duration / 60) + "" }, { "dclassalive", server.Round.Stats.ClassDAlive + "" }, { "dclassdead", server.Round.Stats.ClassDDead + "" }, { "dclassescaped", server.Round.Stats.ClassDEscaped + "" }, { "dclassstart", server.Round.Stats.ClassDStart + "" }, { "mtfalive", server.Round.Stats.NTFAlive + "" }, { "scientistsalive", server.Round.Stats.ScientistsAlive + "" }, { "scientistsdead", server.Round.Stats.ScientistsDead + "" }, { "scientistsescaped", server.Round.Stats.ScientistsEscaped + "" }, { "scientistsstart", server.Round.Stats.ScientistsStart + "" }, { "scpalive", server.Round.Stats.SCPAlive + "" }, { "scpdead", server.Round.Stats.SCPDead + "" }, { "scpkills", server.Round.Stats.SCPKills + "" }, { "scpstart", server.Round.Stats.SCPStart + "" }, { "warheaddetonated", server.Round.Stats.WarheadDetonated + "" }, { "zombies", server.Round.Stats.Zombies + "" } }; } else { roundVariables = new Dictionary <string, string> { { "roundduration", "0" }, { "dclassalive", "0" }, { "dclassdead", "0" }, { "dclassescaped", "0" }, { "dclassstart", "0" }, { "mtfalive", "0" }, { "scientistsalive", "0" }, { "scientistsdead", "0" }, { "scientistsescaped", "0" }, { "scientistsstart", "0" }, { "scpalive", "0" }, { "scpdead", "0" }, { "scpkills", "0" }, { "scpstart", "0" }, { "warheaddetonated", "0" }, { "zombies", "0" } }; } foreach (var entry in serverVariables) { variables.Add(entry.Key, entry.Value); } foreach (var entry in mapVariables) { variables.Add(entry.Key, entry.Value); } foreach (var entry in roundVariables) { variables.Add(entry.Key, entry.Value); } var topic = Language.GetString("topic.message"); topic = topic.Replace("\n", ""); // Variable insertion foreach (KeyValuePair <string, string> variable in variables) { topic = topic.Replace("<var:" + variable.Key + ">", variable.Value); } // Regex replacements Dictionary <string, string> regex = Language.GetRegexDictionary("topic.regex"); // Run the regex replacements foreach (KeyValuePair <string, string> entry in regex) { topic = topic.Replace(entry.Key, entry.Value); } // Try to send the message to the bot try { QueueMessage("channeltopic" + channelID + topic); if (Config.GetBool("settings.debug")) { plugin.Info("Sent channel topic '" + topic + "' to bot."); } } catch (InvalidOperationException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("Error sending channel topic '" + topic + "' to bot."); plugin.Error(e.ToString()); } } catch (ArgumentNullException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("Error sending channel topic '" + topic + "' to bot."); plugin.Error(e.ToString()); } } } catch (Exception e) { if (Config.GetBool("settings.verbose")) { plugin.Error(e.ToString()); } } }
private static void Connect(string address, int port) { if (Config.GetBool("settings.verbose")) { plugin.Info("Attempting Bot Connection..."); } while (!IsConnected()) { try { if (socket != null && socket.IsBound) { socket.Shutdown(SocketShutdown.Both); socket.Close(); } if (Config.GetBool("settings.verbose")) { plugin.Info("Your Bot IP: " + Config.GetString("bot.ip") + ". Your Bot Port: " + Config.GetInt("bot.port") + "."); } socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(Config.GetString("bot.ip"), Config.GetInt("bot.port")); plugin.Info("Connected to Discord bot."); plugin.SendMessage(Config.GetArray("channels.statusmessages"), "botmessages.connectedtobot"); } catch (SocketException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("Error occured while connecting to discord bot server: " + e.Message); if (Config.GetBool("settings.verbose")) { plugin.Error(e.ToString()); } } Thread.Sleep(5000); } catch (ObjectDisposedException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("TCP client was unexpectedly closed."); plugin.Error(e.ToString()); } Thread.Sleep(5000); } catch (ArgumentOutOfRangeException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("Invalid port."); plugin.Error(e.ToString()); } Thread.Sleep(5000); } catch (ArgumentNullException e) { if (Config.GetBool("settings.verbose")) { plugin.Error("IP address is null."); plugin.Error(e.ToString()); } Thread.Sleep(5000); } } }
public static void ValidateConfig(SCPDiscord plugin) { StringBuilder sb = new StringBuilder(); sb.Append("\n||||||||||||| SCPDiscord config validator ||||||||||||||\n"); sb.Append("------------ Config strings ------------\n"); foreach (KeyValuePair <string, string> node in configStrings) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config ints ------------\n"); foreach (KeyValuePair <string, int> node in configInts) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config bools ------------\n"); foreach (KeyValuePair <string, bool> node in configBools) { sb.Append(node.Key + ": " + node.Value + "\n"); } sb.Append("------------ Config arrays ------------\n"); foreach (KeyValuePair <string, string[]> node in configArrays) { sb.Append(node.Key + ": [ " + string.Join(", ", node.Value) + " ]\n"); if (node.Key.StartsWith("channels.")) { foreach (string s in node.Value) { if (!GetDict("aliases").ContainsKey(s)) { sb.Append("WARNING: Channel alias '" + s + "' does not exist!\n"); } } } } sb.Append("------------ Config dictionaries ------------\n"); foreach (KeyValuePair <string, Dictionary <string, ulong> > node in configDicts) { sb.Append(node.Key + ":\n"); foreach (KeyValuePair <string, ulong> subNode in node.Value) { sb.Append(" " + subNode.Key + ": " + subNode.Value + "\n"); } } sb.Append("------------ Rolesync system ------------\n"); foreach (KeyValuePair <ulong, string[]> node in plugin.roleSync.roleDictionary) { sb.Append(node.Key + ":\n"); foreach (string command in node.Value) { sb.Append(" " + command + "\n"); } } sb.Append("|||||||||||| End of config validation ||||||||||||"); plugin.Info(sb.ToString()); }
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; }
public RoleSync(SCPDiscord plugin) { this.plugin = plugin; Reload(); plugin.Info("RoleSync system loaded."); }
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 = ""; 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; } if (Config.GetBool("settings.debug")) { plugin.Info("COMMAND: " + messages[0]); } string[] words = messages[0].Split(' '); if (words[0] == "command") { string channel = words[1]; string command = words[2]; string[] arguments = new string[0]; if (words.Length >= 4) { arguments = words.Skip(3).ToArray(); } string response = ""; Dictionary <string, string> variables = new Dictionary <string, string>(); switch (command) { case "ban": //Check if the command has enough arguments if (arguments.Length >= 2) { BanCommand(arguments[0], arguments[1], MergeString(arguments.Skip(2).ToArray())); } else { variables = new Dictionary <string, string> { { "command", messages[0] } }; plugin.SendMessage(channel, "botresponses.missingarguments", variables); } break; case "kick": //Check if the command has enough arguments if (arguments.Length >= 1) { KickCommand(arguments[0], MergeString(arguments.Skip(1).ToArray())); } else { variables = new Dictionary <string, string> { { "command", messages[0] } }; plugin.SendMessage(channel, "botresponses.missingarguments", variables); } break; case "kickall": KickallCommand(MergeString(arguments)); break; case "unban": //Check if the command has enough arguments if (arguments.Length >= 1) { UnbanCommand(arguments[0]); } else { variables = new Dictionary <string, string> { { "command", messages[0] } }; plugin.SendMessage(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.SteamId + ">" + "\n"; } message += "```"; NetworkSystem.QueueMessage(channel + message); break; case "exit": plugin.SendMessage(channel, "botresponses.exit"); break; case "help": plugin.SendMessage(channel, "botresponses.help"); break; case "hidetag": case "showtag": if (plugin.pluginManager.GetEnabledPlugin("karlofduty.toggletag") != null) { if (arguments.Length > 0) { command = "console_" + command; response = ConsoleCommand(plugin.pluginManager.Server, command, arguments); variables = new Dictionary <string, string> { { "feedback", response } }; plugin.SendMessage(channel, "botresponses.consolecommandfeedback", variables); } else { variables = new Dictionary <string, string> { { "command", command } }; plugin.SendMessage(channel, "botresponses.missingarguments", variables); } } else { plugin.SendMessage(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 = ConsoleCommand(plugin.pluginManager.Server, command, arguments); variables = new Dictionary <string, string> { { "feedback", response } }; plugin.SendMessage(channel, "botresponses.consolecommandfeedback", variables); } else { plugin.SendMessage(channel, "botresponses.vpnshield.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 = ConsoleCommand(plugin.pluginManager.Server, command, arguments); variables = new Dictionary <string, string> { { "feedback", response } }; plugin.SendMessage(channel, "botresponses.consolecommandfeedback", variables); break; } } else if (words[0] == "roleresponse") { plugin.roleSync.ReceiveQueryResponse(words[1], MergeString(words.Skip(2).ToArray())); } if (Config.GetBool("settings.verbose")) { plugin.Info("From discord: " + messages[0]); } messages.RemoveAt(0); } } catch (Exception ex) { if (ex is IOException) { plugin.Error("BotListener Error: " + ex); } plugin.Error("BotListener Error: " + ex); } } Thread.Sleep(1000); } }
public void Reload() { plugin.SetUpFileSystem(); syncedPlayers = JArray.Parse(File.ReadAllText(FileManager.GetAppFolder(plugin.GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord/rolesync.json")).ToDictionary(k => ((JObject)k).Properties().First().Name, v => v.Values().First().Value <string>()); plugin.Info("Successfully loaded config '" + FileManager.GetAppFolder(plugin.GetConfigBool("scpdiscord_rolesync_global")) + "SCPDiscord/rolesync.json'."); }