Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Text.RegularExpressions;
- using Oxide_kIRC;
- using Oxide;
- using Oxide.Core;
- using Oxide.Game.Rust;
- using UnityEngine;
- using Newtonsoft.Json;
- using Oxide.Plugins;
- namespace Oxide.Plugins
- {
- [Info("kirc", "Kirollos", 1.0)]
- public class Kirc : RustPlugin
- {
- public kIRCCore irc = null;
- public Thread ircthread;
- public static Kirc dis = null;
- public void _NextTick(Action ac)
- {
- this.NextTick(ac);
- }
- public Oxide.Core.Libraries.Lang _lang
- {
- get { return this.lang; }
- set { this.lang = _lang; }
- }
- public Oxide.Core.Libraries.Permission _permission
- {
- get { return this.permission; }
- set { this.permission = _permission; }
- }
- public Oxide.Game.Rust.Libraries.Rust _rust
- {
- get { return this.rust; }
- set { this.rust = _rust; }
- }
- void Init()
- {
- dis = this;
- Puts("plugin loaded");
- irc = new kIRCCore((string)Config["server"], (int)Config["port"], (string)Config["nick"], (string)Config["ident"], (string)Config["real"], (string)Config["channel"], (string)Config["password"], (string)Config["spassword"]);
- irc.SetAllowAdminOwner(true);
- irc.SetCommandPrefix(Convert.ToChar(Config["command_prefix"]));
- irc.SetParameterDelimiter(Convert.ToChar(Config["parameter_delimiter"]));
- ircthread = new Thread(() => irc.loopparsing(this));
- ircthread.Start();
- DeathNotes._Loaded();
- }
- void Loaded()
- {
- //DedNotes._Loaded();
- }
- void Unload()
- {
- Puts("plugin unloaded");
- irc.Destruct();
- /*if (ircthread.IsAlive)
- ircthread.Abort();*/
- }
- protected override void LoadDefaultConfig()
- {
- PrintWarning("Creating a new config file");
- Config.Clear();
- Config["server"] = "irc.cncirc.net";
- Config["port"] = 6667;
- Config["spassword"] = "";
- Config["nick"] = "rustirc";
- Config["ident"] = "rustirc";
- Config["real"] = "rustirc";
- Config["password"] = "";
- Config["channel"] = "#rustirc";
- Config["command_prefix"] = "!";
- Config["parameter_delimiter"] = "/";
- Config["allow_adminowner"] = true;
- }
- protected override void LoadConfig()
- {
- //DedNotes._LoadConfig();
- }
- void OnEntityDeath(BaseCombatEntity victim, HitInfo info)
- {
- DeathNotes._OnEntityDeath(victim, info);
- }
- void OnEntityTakeDamage(BaseCombatEntity victim, HitInfo info)
- {
- DeathNotes._OnEntityTakeDamage(victim, info);
- }
- public void Log(string message)
- {
- Puts(message);
- }
- public void SendToChat(string message)
- {
- PrintToChat(message);
- }
- public void SendToChat(BasePlayer p, string message)
- {
- PrintToChat(p, message);
- }
- void OnPlayerChat(ConsoleSystem.Arg arg)
- {
- //BasePlayer p = arg.connection.player;
- irc.Say((string)Config["channel"], arg.Player().displayName + ": " + arg.ArgsStr);
- }
- void OnPlayerInit(BasePlayer player)
- {
- DeathNotes._OnPlayerInit(player);
- irc.Say((string)Config["channel"], "[CONNECT] " + player.displayName + " has connected!");
- }
- void OnPlayerDisconnected(BasePlayer player, string reason)
- {
- irc.Say((string)Config["channel"], "[DISCONNECT] " + player.displayName + " has disconnected (" + reason + ")!");
- }
- public void _SaveConfig()
- {
- this.SaveConfig();
- }
- }
- }
- namespace Oxide_kIRC
- {
- public class kIRCCore
- {
- public string _host;
- public int _port;
- public string _nick;
- public string _user;
- public string _realname;
- public string _password;
- public string _channel;
- public char _command_prefix;
- public char _parameter_delimiter;
- public string _spassword;
- public bool Registered = false;
- private TcpClient ircsock;
- private Stream mystream;
- private UTF8Encoding _encoding;
- public List<string[]> userlist = new List<string[]>();
- public bool allow_adminowner;
- private bool __NAMES = false;
- public bool isConnected = false;
- //public List<CPerform> cperform;
- //public List<kIRC_Commands> custom_commands;
- public kIRCCore(string host, int port, string nick, string user, string realname, string channel, string password, string spassword)
- {
- ircsock = new TcpClient();
- ircsock.Connect(host, port);
- mystream = ircsock.GetStream();
- ircsock.NoDelay = true;
- _encoding = new UTF8Encoding();
- isConnected = true;
- _nick = nick;
- _host = host;
- _port = port;
- _user = user;
- _spassword = spassword;
- _realname = realname;
- _password = password;
- _channel = channel;
- this.Send("NICK " + this._nick);
- if (!String.IsNullOrEmpty(_spassword))
- this.Send("PASS " + _spassword);
- this.Send("USER " + this._user + " - - :" + this._realname);
- }
- public bool Disconnect(string reason = "Bye!")
- {
- try
- {
- this.Send("QUIT :" + reason);
- ircsock.Close();
- return true;
- }
- catch
- {
- return false;
- }
- }
- public void Destruct(bool disconnect = true)
- {
- if (!isConnected) return;
- if (disconnect)
- this.Disconnect();
- else
- ircsock.Close();
- isConnected = false;
- }
- public void Send(string data)
- {
- if (!this.isConnected) return;
- if (!data.Contains("\n"))
- data += "\r\n";
- byte[] _data = _encoding.GetBytes(data);
- try
- {
- mystream.Write(_data, 0, _data.Length);
- //if (kIRC.dis.Configuration.Instance.Debug)
- {
- Kirc.dis.Log("[kIRC DEBUG]: {" + DateTime.Now + "} << " + data);
- }
- }
- catch(Exception e)
- {
- Kirc.dis.Log("kIRC Error: Send() has failed, therefore destructing. cause: " + e.ToString());
- Kirc.dis.Log("kIRC Error: You can reload the plugin using `rocket reload kIRC`");
- this.Destruct(false);
- }
- }
- public String Read()
- {
- if (!this.isConnected) return "";
- string data = "";
- byte[] _data = new byte[1];
- while (true)
- {
- try
- {
- int k = mystream.Read(_data, 0, 1);
- if (k == 0)
- {
- this.Destruct();
- return "";
- }
- char kk = Convert.ToChar(_data[0]);
- data += kk;
- if (kk == '\n')
- break;
- }
- catch
- {
- Kirc.dis.Log("kIRC Error: Read() has failed, therefore destructing.");
- Kirc.dis.Log("kIRC Error: You can reload the plugin using `rocket reload kIRC`");
- this.Destruct(false);
- return "";
- }
- }
- return data;
- }
- public void Say(string target, string text)
- {
- string[] splitted_text = text.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < splitted_text.Length; i++)
- this.Send("PRIVMSG " + target + " :" + /*text*/splitted_text[i]);
- return;
- }
- public void Notice(string target, string text)
- {
- string[] splitted_text = text.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < splitted_text.Length; i++)
- this.Send("NOTICE " + target + " :" + /*text*/splitted_text[i]);
- return;
- }
- public void parse(string data, Kirc unturnedclass)
- {
- if (data == "") return;
- //if (kIRC.dis.Configuration.Instance.Debug)
- {
- Kirc.dis.Log("[kIRC DEBUG]: {" + DateTime.Now + "} >> " + data);
- }
- if (data.Substring(0, 6) == "ERROR ")
- {
- Kirc.dis.Log("Error: IRC socket has closed. Reload the plugin for reconnection.");
- this.Destruct();
- }
- // Regex taken from (http://calebdelnay.com/blog/2010/11/parsing-the-irc-message-format-as-a-client)
- string
- prefix = "",
- command = "",
- //parameters,
- trailing = ""
- ;
- string[] parameters = new string[] { };
- Regex parsingRegex = new Regex(@"^(:(?<prefix>\S+) )?(?<command>\S+)( (?!:)(?<params>.+?))?( :(?<trail>.+))?$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
- Match messageMatch = parsingRegex.Match(data);
- if (messageMatch.Success)
- {
- prefix = messageMatch.Groups["prefix"].Value;
- command = messageMatch.Groups["command"].Value;
- parameters = messageMatch.Groups["params"].Value.Split(' ');
- trailing = messageMatch.Groups["trail"].Value;
- if (!String.IsNullOrEmpty(trailing))
- parameters = parameters.Concat(new string[] { trailing }).ToArray();
- }
- if (command == "PING")
- {
- this.Send("PONG :" + trailing);
- this.Send("NAMES " + this._channel);
- }
- if (command == "001")
- {
- this.Registered = true;
- //}
- //if (command == "005")
- //{
- if (!String.IsNullOrEmpty(this._password))
- this.Say("NickServ", "IDENTIFY " + this._password);
- this.Send("JOIN " + _channel);
- // Perform
- //for (int i = 0; i < this.cperform.Count; i++)
- //{
- // this.Send(this.cperform[i].pcommand);
- //}
- // -------
- //kIRCVersionChecker.CheckUpdate(this, this._channel); // Update checker
- }
- if (command == "353")
- {
- // Names list
- if (!this.__NAMES)
- {
- this.__NAMES = true;
- this.userlist.Clear();
- }
- string[] _userlist = trailing.Trim().Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
- for (int i = 0; i < _userlist.Length; i++)
- {
- string lerank = Convert.ToString(_userlist[i][0]);
- string lename = _userlist[i].Remove(0, 1);
- if (lerank == "~" || lerank == "&" || lerank == "@" || lerank == "%" || lerank == "+")
- {
- lename = _userlist[i].Remove(0, 1);
- }
- else
- {
- lename = _userlist[i];
- lerank = "";
- }
- this.userlist.Add(new[] { lename, lerank });
- }
- }
- if (command == "433")
- {
- Kirc.dis.Log("Error: Nickname taken. Reload the plugin for reconnection.");
- this.Destruct();
- }
- if (command == "JOIN")
- {
- string user = prefix.Split('!')[0];
- string ident = prefix.Split('!')[1].Split('@')[0];
- string host = prefix.Split('@')[1];
- //RocketChat.Say("[IRC JOIN] "+ user +" has joined IRC channel.", Color.gray);
- /*kIRCTranslate.Rocket_ChatSay("game_ircjoin", Color.gray, new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel}
- });*/
- this.userlist.Add(new[] { user, "" });
- }
- else if (command == "PART")
- {
- string user = prefix.Split('!')[0];
- string ident = prefix.Split('!')[1].Split('@')[0];
- string host = prefix.Split('@')[1];
- //RocketChat.Say("[IRC PART] " + user + " has left IRC channel.", Color.gray);
- /*kIRCTranslate.Rocket_ChatSay("game_ircpart", Color.gray, new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_partreason", trailing.Trim()}
- });*/
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == user)
- {
- this.userlist.Remove(new[] { user, this.userlist[i][1] });
- break;
- }
- }
- }
- if (command == "366")
- { // End of /NAMES
- this.__NAMES = false;
- }
- if (command == "MODE")
- {
- if (String.IsNullOrEmpty(trailing))
- {
- this.Send("NAMES " + this._channel);
- }
- }
- if (command == "NICK")
- {
- if (this.Registered)
- {
- string user = prefix.Split('!')[0];
- if (this._nick == user)
- this._nick = trailing.Trim();
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == user)
- {
- this.userlist[i][0] = trailing.Trim();
- break;
- }
- }
- }
- }
- if (command == "PRIVMSG")
- {
- if (trailing[0] == this._command_prefix)
- {
- string cmd;
- try
- {
- cmd = trailing.Split(' ')[0].ToLower();
- if (String.IsNullOrEmpty(cmd.Trim()))
- cmd = trailing.Trim().ToLower();
- }
- catch
- {
- cmd = trailing.Trim().ToLower();
- }
- string msg = "";
- string user = prefix.Split('!')[0];
- string ident = prefix.Split('!')[1].Split('@')[0];
- string host = prefix.Split('@')[1];
- cmd = cmd.Remove(0, 1); // remove the prefix pls
- msg = trailing.Remove(0, 1 + cmd.Length).Trim();
- cmd = cmd.Trim();
- if(cmd == "say")
- {
- if (String.IsNullOrEmpty(msg))
- {
- string[] ParamSyntax = { "text" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- return;
- }
- Kirc.dis.SendToChat("[IRC] " + user + ": " + msg);
- }
- if(cmd == "players")
- {
- string listStr = "";
- BaseEntity[] uh = BaseEntity.Util.FindTargets("", true);
- BasePlayer[] ps = uh.Select(x => x.ToPlayer()).ToArray();
- int count = uh.Where(x => x.ToPlayer().isConnected == true).Count();
- int i = 0;
- foreach (BasePlayer u in ps)
- {
- if (!u.isConnected) continue;
- listStr += u.displayName;
- if(++i != count)
- listStr += ", ";
- }
- this.Say(this._channel, "Connected Players [" + count + "]: " + listStr);
- }
- if(cmd == "give" && IsOp(user, false))
- {
- // not done
- }
- /*if (cmd == "help")
- {
- if (!IsVoice(user, false))
- {
- this.Say(this._channel, "Error: You need voice to use the commands.");
- return;
- }
- this.Say(this._channel, "====Unturned IRC Commands====");
- this.Say(this._channel, "- " + this._command_prefix + "help => This command");
- this.Say(this._channel, "- " + this._command_prefix + "say <text> => Send a message to ingame users");
- this.Say(this._channel, "- " + this._command_prefix + "players => Shows a list of online players");
- this.Say(this._channel, "- " + this._command_prefix + "pm => Sends a personal message to a specific player");
- // Custom commands
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- if (this.custom_commands[i].FlagNeeded == "v" || this.custom_commands[i].FlagNeeded == "")
- {
- this.Say(this._channel, "+ " + this._command_prefix + this.custom_commands[i].BotCommand + " " + this.custom_commands[i].BotSyntax);
- }
- }
- // ---------------
- if (IsHalfOp(user, false))
- {
- this.Say(this._channel, "- " + this._command_prefix + "info <player name> => Show information about given username");
- this.Say(this._channel, "- " + this._command_prefix + "broadcast <text> => Sends a broadcast to the players");
- // Custom commands
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- if (this.custom_commands[i].FlagNeeded == "h")
- {
- this.Say(this._channel, "+ " + this._command_prefix + this.custom_commands[i].BotCommand + " " + this.custom_commands[i].BotSyntax);
- }
- }
- // ---------------
- }
- if (IsOp(user, false))
- {
- this.Say(this._channel, "- " + this._command_prefix + "kick <player name> <reason> => Kicks a player from the server with a given reason");
- // Custom commands
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- if (this.custom_commands[i].FlagNeeded == "o")
- {
- this.Say(this._channel, "+ " + this._command_prefix + this.custom_commands[i].BotCommand + " " + this.custom_commands[i].BotSyntax);
- }
- }
- // ---------------
- }
- if (IsAdmin(user, false))
- {
- this.Say(this._channel, "- " + this._command_prefix + "ban <player name|SteamID> <duration in seconds> <reason> => Bans a player from the server with a given duration and reason");
- this.Say(this._channel, "- " + this._command_prefix + "unban <SteamID> => Unbans a player from the server with a given SteamID");
- this.Say(this._channel, "- " + this._command_prefix + "bans => Shows ban list");
- this.Say(this._channel, "- " + this._command_prefix + "save => Saves the game data.");
- this.Say(this._channel, "- " + this._command_prefix + "shutdown => shuts down the server.");
- // Custom commands
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- if (this.custom_commands[i].FlagNeeded == "a")
- {
- this.Say(this._channel, "+ " + this._command_prefix + this.custom_commands[i].BotCommand + " " + this.custom_commands[i].BotSyntax);
- }
- }
- // ---------------
- }
- if (IsOwner(user, false))
- {
- // Custom commands
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- if (this.custom_commands[i].FlagNeeded == "q")
- {
- this.Say(this._channel, "+ " + this._command_prefix + this.custom_commands[i].BotCommand + " " + this.custom_commands[i].BotSyntax);
- }
- }
- // ---------------
- }
- this.Say(this._channel, "=============================");
- }
- else if (cmd == "say" && IsVoice(user, false))
- {
- if (String.IsNullOrEmpty(msg))
- {
- string[] ParamSyntax = { "text" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- return;
- }
- //RocketChat.Say("[IRC] " + user + ": " + msg, Color.yellow);
- kIRCTranslate.Rocket_ChatSay("game_ircsay", Color.yellow, new Dictionary<string, string>()
- {
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_message", msg}
- });
- }
- else if (cmd == "players" && IsVoice(user, false))
- {
- string playerlist = "";
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_playerslist", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"players_amount", Provider.Players.Count.ToString()},
- {"players_max", Provider.MaxPlayers.ToString()},
- {"players_list", playerlist}
- });
- }
- else if (cmd == "pm" && IsVoice(user, false))
- {
- if (msg.Split(this._parameter_delimiter).Length < 2)
- {
- string[] ParamSyntax = { "Player Name", "Message" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- return;
- }
- else
- {
- string pname = msg.Split(this._parameter_delimiter)[0];
- string message = msg.Split(this._parameter_delimiter)[1];
- UnturnedPlayer pPointer = UnturnedPlayer.FromName(pname);
- if (pPointer == null || pPointer.CharacterName != pname)
- this.Say(this._channel, "[ERROR] Player " + pname + " not found.");
- else
- {
- //RocketChat.Say(pPointer, "[IRC PM] " + user + ": " + message, Color.magenta);
- kIRCTranslate.Rocket_ChatSay("game_ircpm", Color.magenta, new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_message", message}
- }, pPointer);
- }
- }
- }
- else if (cmd == "info" && IsHalfOp(user, false))
- {
- if (String.IsNullOrEmpty(msg))
- {
- string[] ParamSyntax = { "Player Name" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- }
- else
- {
- string pname = msg.Trim();
- UnturnedPlayer pPointer = UnturnedPlayer.FromName(pname);
- if (pPointer == null || pPointer.CharacterName != pname)
- {
- this.Say(this._channel, "[ERROR] Player " + pname + " not found.");
- return;
- }
- this.Notice(user, "Info about {" + pname + "}");
- this.Notice(user, "Character name: " + pPointer.CharacterName);
- this.Notice(user, "Steam name: " + pPointer.SteamName);
- this.Notice(user, "SteamID: " + pPointer.CSteamID.ToString());
- //this.Notice(user, "Health: " + pPointer.Health + "%"); // pPointer.Health ALWAYS returns zero for some reason..
- // Therefore using another method to update player health
- // on each health update event.
- this.Notice(user, "Health: " + pPointer.Health); // Fixed in Rocket v4.6.0.0
- this.Notice(user, "Hunger: " + pPointer.Hunger + "%");
- this.Notice(user, "Thirst: " + pPointer.Thirst + "%");
- this.Notice(user, "Infection: " + pPointer.Infection + "%");
- this.Notice(user, "Stamina: " + pPointer.Stamina + "%");
- this.Notice(user, "Experience: " + pPointer.Experience);
- this.Notice(user, "Admin: " + (pPointer.IsAdmin == true ? "Yes" : "No"));
- this.Notice(user, "Dead: " + (pPointer.Dead == true ? "Yes" : "No"));
- this.Notice(user, "Godmode: " + (pPointer.Features.GodMode == true ? "Enabled" : "Disabled"));
- this.Notice(user, "Position: X:" + pPointer.Position.x + ", Y:" + pPointer.Position.y + ", Z:" + pPointer.Position.z);
- }
- }
- else if (cmd == "broadcast" && IsHalfOp(user, false))
- {
- if (String.IsNullOrEmpty(msg))
- {
- string[] ParamSyntax = { "text" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- return;
- }
- //RocketChat.Say("[IRC Broadcast]: " + msg, Color.red);
- kIRCTranslate.Rocket_ChatSay("game_ircbroadcast", Color.red, new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_message", msg}
- });
- }
- else if (cmd == "kick" && IsOp(user, false))
- {
- if (msg.Split(this._parameter_delimiter).Length < 2)
- {
- string[] ParamSyntax = { "Player Name", "Reason" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- }
- else
- {
- string pname = msg.Split(this._parameter_delimiter)[0];
- string reason = msg.Split(this._parameter_delimiter)[1];
- UnturnedPlayer pPointer = UnturnedPlayer.FromName(pname);
- if (pPointer == null || pPointer.CharacterName != pname)
- this.Say(this._channel, "[ERROR] Player " + pname + " not found.");
- else
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "__kick";
- pcmd.parameters = new string[] { pname, reason };
- pcmd.extradata.Add("Syntax", "");
- pcmd.onfire(() => { });
- pcmd.onexec((string response) =>
- {
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_kicksuccess", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_targetnick", pname},
- {"irc_kickreason", reason}
- });
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- }
- }
- else if (cmd == "ban" && IsAdmin(user, false))
- {
- if (msg.Split(this._parameter_delimiter).Length < 3)
- {
- string[] ParamSyntax = { "Player Name|SteamID", "Duration in seconds", "Reason" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- }
- else
- {
- string pname = msg.Split(this._parameter_delimiter)[0];
- string durationstr = msg.Split(this._parameter_delimiter)[1];
- int duration = 0;
- if (!int.TryParse(durationstr, out duration))
- {
- this.Say(this._channel, "[ERROR] duration \"" + durationstr + "\" is not valid.");
- return;
- }
- if (!Regex.IsMatch(pname, @"^\d+$")) // If not SteamID
- {
- UnturnedPlayer pPointer = UnturnedPlayer.FromName(pname);
- if (pPointer == null || pPointer.CharacterName != pname)
- {
- this.Say(this._channel, "[ERROR] Player " + pname + " not found.");
- return;
- }
- else
- {
- // pPointer.Ban(reason, (uint) duration); // Doesn't work (https://github.com/RocketFoundation/Rocket/issues/173)
- //this.Say(this._channel, "[SUCCESS] Player " + pname + " is banned!");
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_pbansuccess", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_targetnick", pname},
- {"irc_banreason", reason},
- {"irc_banduration", durationstr}
- });
- }
- }
- else
- {
- //this.Say(this._channel, "[SUCCESS] SteamID "+pname+" is banned.");
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_sbansuccess", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_targetsteamid", pname},
- {"irc_banreason", reason},
- {"irc_banduration", durationstr}
- });
- }
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "ban {0}/{1}/{2}";
- pcmd.parameters = new string[] { pname, reason, durationstr };
- pcmd.onfire(() => { });
- pcmd.onexec((string response) => { });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- }
- else if (cmd == "unban" && IsAdmin(user, false))
- {
- if (String.IsNullOrEmpty(msg))
- {
- string[] ParamSyntax = { "SteamID" };
- this.SendSyntax(this._channel, cmd, ParamSyntax);
- return;
- }
- else
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "unban {0}";
- pcmd.parameters = new string[] { msg };
- pcmd.onfire(() => { });
- pcmd.onexec((string response) => {
- //this.Say(this._channel, "Unban response: " + response);
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_unbanresponse", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_targetsteamid", msg},
- {"irc_response", response}
- });
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- }
- else if (cmd == "bans" && IsAdmin(user, false))
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "bans";
- pcmd.parameters = new string[] { };
- pcmd.onfire(() =>
- {
- this.Say(this._channel, user + ": Response is sent to your query.");
- });
- pcmd.onexec((string response) =>
- {
- this.Say(user, "Response from bans:");
- string[] bans = response.Split('\n');
- for (int i = 0; i < bans.Length; i++)
- {
- this.Say(user, bans[i]);
- }
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- else if (cmd == "save" && IsAdmin(user, false))
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "save";
- pcmd.parameters = new string[] { };
- pcmd.onfire(() => {
- //this.Say(this._channel, "Saving server settings...");
- //RocketChat.Say("[IRC] Saving server settings...");
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_onsave", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel}
- });
- kIRCTranslate.Rocket_ChatSay("game_onsave", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel}
- });
- });
- pcmd.onexec((string response) => {
- //this.Say(this._channel, "Save response: " + response);
- //RocketChat.Say("[IRC] Server settings, Player items saved!");
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_saveexec", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_response", response}
- });
- kIRCTranslate.Rocket_ChatSay("game_saveexec", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_response", response}
- });
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- else if (cmd == "shutdown" && IsAdmin(user, false))
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = "save";
- pcmd.parameters = new string[] { };
- pcmd.onfire(() =>
- {
- //RocketChat.Say("[IRC WARNING]: SERVER IS SHUTTING DOWN IN 5 SECONDS!", Color.red);
- //this.Say(this._channel, "Shutting down in 5 seconds");
- kIRCTranslate.Rocket_ChatSay("game_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "5"}
- });
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "5"}
- });
- Thread.Sleep(1000);
- });
- pcmd.onexec((string response) =>
- {
- //RocketChat.Say("[IRC] Server settings, Player items saved!");
- kIRCTranslate.Rocket_ChatSay("game_saveexec", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"irc_response", response}
- });
- kIRC_PushCommand pcmd2 = new kIRC_PushCommand();
- pcmd2.command = "shutdown";
- pcmd2.parameters = new string[] { };
- pcmd2.onfire(() =>
- {
- kIRCTranslate.Rocket_ChatSay("game_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "4"}
- });
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "4"}
- });
- Thread.Sleep(1000);
- kIRCTranslate.Rocket_ChatSay("game_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "3"}
- });
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "3"}
- });
- Thread.Sleep(1000);
- kIRCTranslate.Rocket_ChatSay("game_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "2"}
- });
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "2"}
- });
- Thread.Sleep(1000);
- kIRCTranslate.Rocket_ChatSay("game_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "1"}
- });
- kIRCTranslate.IRC_SayTranslation(this, this._channel, "irc_shutdownwarning", new Dictionary<string, string>()
- {
- {"time", DateTime.Now.ToString()},
- {"irc_usernick", user},
- {"irc_userident", ident},
- {"irc_userhost", host},
- {"irc_channel", this._channel},
- {"shutdown_secs", "1"}
- });
- Thread.Sleep(1000);
- });
- pcmd2.onexec((string response2) => { });
- pcmd2.execute = true;
- pcmd2.push(unturnedclass);
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- else
- {
- for (int i = 0; i < this.custom_commands.Count; i++)
- {
- kIRC_Commands refer = this.custom_commands[i];
- if (refer.BotCommand.ToLower().Trim() == cmd)
- {
- bool hasperms = false;
- if (refer.FlagNeeded == "q")
- hasperms = IsOwner(user);
- else if (refer.FlagNeeded == "a")
- hasperms = IsAdmin(user);
- else if (refer.FlagNeeded == "o")
- hasperms = IsOp(user);
- else if (refer.FlagNeeded == "h")
- hasperms = IsHalfOp(user);
- else if (refer.FlagNeeded == "v")
- hasperms = IsVoice(user);
- else
- hasperms = false;
- if (hasperms)
- {
- kIRC_PushCommand pcmd = new kIRC_PushCommand();
- pcmd.command = refer.ConsoleCommand;
- pcmd.parameters = (!String.IsNullOrEmpty(msg) && msg.Split(this._parameter_delimiter).Length > 0) ? msg.Split(this._parameter_delimiter) : new string[] { };
- pcmd.extradata.Add("Syntax", refer.BotSyntax);
- pcmd.onfire(() =>
- {
- if (!String.IsNullOrEmpty(refer.IRCmsg_onfire.Trim()))
- {
- this.Say(this._channel, refer.IRCmsg_onfire);
- }
- if (!String.IsNullOrEmpty(refer.GAMEmsg_onfire.Trim()))
- {
- UnturnedChat.Say(refer.GAMEmsg_onfire);
- }
- });
- pcmd.onexec((string response) =>
- {
- if (!String.IsNullOrEmpty(refer.IRCmsg_onexec.Trim()))
- {
- this.Say(this._channel, refer.IRCmsg_onexec);
- }
- if (!String.IsNullOrEmpty(refer.GAMEmsg_onexec.Trim()))
- {
- UnturnedChat.Say(refer.GAMEmsg_onexec);
- }
- if (refer.printresponse == true)
- this.Say(this._channel, "Response from (" + cmd + "): " + response);
- });
- pcmd.execute = true;
- pcmd.push(unturnedclass); // Sends it to the main unturned thread
- }
- break;
- }
- }
- }*/
- }
- }
- }
- public bool IsOwner(string name, bool actualrank = true)
- {
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == name)
- {
- if (this.allow_adminowner || actualrank)
- return userlist[i][1] == "~";
- else
- return userlist[i][1] == "@";
- }
- }
- return false;
- }
- public bool IsAdmin(string name, bool actualrank = true)
- {
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == name)
- {
- if (this.allow_adminowner || actualrank)
- return userlist[i][1] == "&" || userlist[i][1] == "~";
- else
- return userlist[i][1] == "@";
- }
- }
- return false;
- }
- public bool IsOp(string name, bool actualrank = true)
- {
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == name)
- {
- if (this.allow_adminowner || actualrank)
- return userlist[i][1] == "@" || userlist[i][1] == "&" || userlist[i][1] == "~";
- else
- return userlist[i][1] == "%" || userlist[i][1] == "@";
- }
- }
- return false;
- }
- public bool IsHalfOp(string name, bool actualrank = true)
- {
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == name)
- {
- if (this.allow_adminowner || actualrank)
- return userlist[i][1] == "%" || userlist[i][1] == "@" || userlist[i][1] == "&" || userlist[i][1] == "~";
- else
- return userlist[i][1] == "%" || userlist[i][1] == "@";
- }
- }
- return false;
- }
- public bool IsVoice(string name, bool actualrank = true)
- {
- for (int i = 0; i < this.userlist.Count; i++)
- {
- if (this.userlist[i][0] == name)
- {
- if (this.allow_adminowner || actualrank)
- return userlist[i][1] == "+" || userlist[i][1] == "%" || userlist[i][1] == "@" || userlist[i][1] == "&" || userlist[i][1] == "~";
- else
- return userlist[i][1] == "+" || userlist[i][1] == "%" || userlist[i][1] == "@";
- }
- }
- return false;
- }
- public void SetCommandPrefix(char prefix)
- {
- this._command_prefix = prefix;
- }
- public void SetParameterDelimiter(char delimiter)
- {
- this._parameter_delimiter = delimiter;
- }
- public void SetAllowAdminOwner(bool allow)
- {
- this.allow_adminowner = allow;
- }
- //public void SetCustomCommands(List<kIRC_Commands> cc)
- //{
- // this.custom_commands = cc;
- //}
- public void SendSyntax(string channel, string command, string[] parameters)
- {
- string _parameters = "";
- for (int i = 0; i < parameters.Length; i++)
- {
- _parameters += "<" + parameters[i] + ">";
- if (i != (parameters.Length - 1))
- _parameters += this._parameter_delimiter;
- }
- this.Say(channel, "Syntax: " + this._command_prefix + command + " " + _parameters);
- return;
- }
- public void loopparsing(Kirc uclass)
- {
- while (isConnected)
- {
- try {
- this.parse(this.Read(), uclass);
- }
- catch
- {
- isConnected = false;
- }
- }
- }
- }
- class DeathNotes //: RustPlugin
- {
- static bool debug = false;
- static Dictionary<ulong, bool> canRead = new Dictionary<ulong, bool>();
- static Dictionary<ulong, HitInfo> LastWounded = new Dictionary<ulong, HitInfo>();
- static public Oxide.Core.Configuration.DynamicConfigFile _Config
- {
- get
- {
- return Kirc.dis.Config;
- }
- }
- ////////////////////////////////////////
- /// Classes
- ////////////////////////////////////////
- class Attacker
- {
- public string name = string.Empty;
- [JsonIgnore]
- public BaseCombatEntity entity = new BaseCombatEntity();
- public AttackerType type = AttackerType.Invalid;
- public string TryGetName()
- {
- if (type == AttackerType.Player)
- return entity?.ToPlayer().displayName;
- else if (type == AttackerType.Helicopter)
- return "Patrol Helicopter";
- else if (type == AttackerType.Turret)
- return "Auto Turret";
- else if (type == AttackerType.Self)
- return "himself";
- else if (type == AttackerType.Animal)
- {
- if ((bool)entity?.name?.Contains("boar"))
- return "Boar";
- else if ((bool)entity?.name?.Contains("horse"))
- return "Horse";
- else if ((bool)entity?.name?.Contains("wolf"))
- return "Wolf";
- else if ((bool)entity?.name?.Contains("stag"))
- return "Stag";
- else if ((bool)entity?.name?.Contains("chicken"))
- return "Chicken";
- else if ((bool)entity?.name?.Contains("bear"))
- return "Bear";
- }
- else if (type == AttackerType.Structure)
- {
- if ((bool)entity?.name?.Contains("barricade.wood.prefab"))
- return "Wooden Barricade";
- else if ((bool)entity?.name?.Contains("barricade.woodwire.prefab"))
- return "Barbed Wooden Barricade";
- else if ((bool)entity?.name?.Contains("barricade.metal.prefab"))
- return "Metal Barricade";
- else if ((bool)entity?.name?.Contains("wall.external.high.wood.prefab"))
- return "High External Wooden Wall";
- else if ((bool)entity?.name?.Contains("wall.external.high.stone.prefab"))
- return "High External Stone Wall";
- else if ((bool)entity?.name?.Contains("gate.external.high.wood.prefab"))
- return "High External Wooden Gate";
- else if ((bool)entity?.name?.Contains("gate.external.high.wood.prefab"))
- return "High External Stone Gate";
- }
- else if (type == AttackerType.Trap)
- {
- if ((bool)entity?.name?.Contains("beartrap.prefab"))
- return "Snap Trap";
- else if ((bool)entity?.name?.Contains("landmine.prefab"))
- return "Land Mine";
- else if ((bool)entity?.name?.Contains("spikes.floor.prefab"))
- return "Wooden Floor Spikes";
- }
- return "No Attacker";
- }
- public AttackerType TryGetType()
- {
- if (entity == null)
- return AttackerType.Invalid;
- else if (entity?.ToPlayer() != null)
- return AttackerType.Player;
- else if ((bool)entity?.name?.Contains("patrolhelicopter.prefab"))
- return AttackerType.Helicopter;
- else if ((bool)entity?.name?.Contains("animals/"))
- return AttackerType.Animal;
- else if ((bool)entity?.name?.Contains("barricades/") || (bool)entity?.name?.Contains("wall.external.high"))
- return AttackerType.Structure;
- else if ((bool)entity?.name?.Contains("beartrap.prefab") || (bool)entity?.name?.Contains("landmine.prefab") || (bool)entity?.name?.Contains("spikes.floor.prefab"))
- return AttackerType.Trap;
- else if ((bool)entity?.name?.Contains("autoturret_deployed.prefab"))
- return AttackerType.Turret;
- return AttackerType.Invalid;
- }
- }
- class Victim
- {
- public string name = string.Empty;
- [JsonIgnore]
- public BaseCombatEntity entity = new BaseCombatEntity();
- public VictimType type = VictimType.Invalid;
- public string TryGetName()
- {
- if (type == VictimType.Player)
- return entity?.ToPlayer().displayName;
- else if (type == VictimType.Helicopter)
- return "Patrol Helicopter";
- else if (type == VictimType.Animal)
- {
- if ((bool)entity?.name?.Contains("boar"))
- return "Boar";
- else if ((bool)entity?.name?.Contains("horse"))
- return "Horse";
- else if ((bool)entity?.name?.Contains("wolf"))
- return "Wolf";
- else if ((bool)entity?.name?.Contains("stag"))
- return "Stag";
- else if ((bool)entity?.name?.Contains("chicken"))
- return "Chicken";
- else if ((bool)entity?.name?.Contains("bear"))
- return "Bear";
- }
- return "No Victim";
- }
- public VictimType TryGetType()
- {
- if (entity?.ToPlayer() != null)
- return VictimType.Player;
- else if ((bool)entity?.name?.Contains("patrolhelicopter.prefab"))
- return VictimType.Helicopter;
- else if ((bool)entity?.name?.Contains("animals/"))
- return VictimType.Animal;
- return VictimType.Invalid;
- }
- }
- class DeathData
- {
- public Victim victim = new Victim();
- public Attacker attacker = new Attacker();
- public DeathReason reason = DeathReason.Unknown;
- public string damageType = string.Empty;
- public string weapon = string.Empty;
- public List<string> attachments = new List<string>();
- public string bodypart = string.Empty;
- public float distance
- {
- get
- {
- try
- {
- foreach (string death in new List<string> { "Cold", "Drowned", "Heat", "Suicide", "Generic", "Posion", "Radiation", "Thirst", "Hunger", "Fall" })
- {
- if (reason == GetDeathReason(death))
- attacker.entity = victim.entity;
- }
- return victim.entity.Distance(attacker.entity.transform.position);
- }
- catch (Exception)
- {
- return 0f;
- }
- }
- }
- public DeathReason TryGetReason()
- {
- if (victim.type == VictimType.Helicopter)
- return DeathReason.HelicopterDeath;
- else if (attacker.type == AttackerType.Helicopter)
- return DeathReason.Helicopter;
- else if (attacker.type == AttackerType.Turret)
- return DeathReason.Turret;
- else if (attacker.type == AttackerType.Trap)
- return DeathReason.Trap;
- else if (attacker.type == AttackerType.Structure)
- return DeathReason.Structure;
- else if (attacker.type == AttackerType.Animal)
- return DeathReason.Animal;
- else if (victim.type == VictimType.Animal)
- return DeathReason.AnimalDeath;
- else if (weapon == "F1 Grenade")
- return DeathReason.Explosion;
- else if (victim.type == VictimType.Player)
- return GetDeathReason(damageType);
- return DeathReason.Unknown;
- }
- public DeathReason GetDeathReason(string damage)
- {
- //Interface.Oxide.RootPluginManager.GetPlugin("DeathNotes").Call("BroadcastChat", "GetDeathReason");
- List<DeathReason> Reason = (from DeathReason current in Enum.GetValues(typeof(DeathReason)) where current.ToString() == damage select current).ToList();
- if (Reason.Count == 0)
- return DeathReason.Unknown;
- return Reason[0];
- }
- [JsonIgnore]
- internal string JSON
- {
- get
- {
- return JsonConvert.SerializeObject(this, Formatting.Indented);
- }
- }
- }
- ////////////////////////////////////////
- /// Enums / Types
- ////////////////////////////////////////
- enum VictimType
- {
- Player,
- Helicopter,
- Animal,
- Invalid
- }
- enum AttackerType
- {
- Player,
- Helicopter,
- Animal,
- Turret,
- Structure,
- Trap,
- Self,
- Invalid
- }
- enum DeathReason
- {
- Turret,
- Helicopter,
- HelicopterDeath,
- Structure,
- Trap,
- Animal,
- AnimalDeath,
- Generic,
- Hunger,
- Thirst,
- Cold,
- Drowned,
- Heat,
- Bleeding,
- Poison,
- Suicide,
- Bullet,
- Slash,
- Blunt,
- Fall,
- Radiation,
- Stab,
- Explosion,
- Unknown
- }
- ////////////////////////////////////////
- /// Plugin Related Hooks
- ////////////////////////////////////////
- static public void _Loaded()
- {
- RegisterPerm("see");
- _LoadConfig();
- _LoadData();
- _LoadMessages();
- foreach (BasePlayer player in BasePlayer.activePlayerList)
- if (!canRead.ContainsKey(player.userID) && HasPerm(player.userID, "see"))
- canRead.Add(player.userID, true);
- }
- static public void _OnPlayerInit(BasePlayer player)
- {
- if (!canRead.ContainsKey(player.userID))
- {
- canRead.Add(player.userID, true);
- _SaveData();
- }
- }
- ////////////////////////////////////////
- /// Plugin Related Methods
- ////////////////////////////////////////
- static public void _LoadData()
- {
- canRead = Interface.Oxide.DataFileSystem.ReadObject<Dictionary<ulong, bool>>("DeathNotes");
- }
- static public void _SaveData()
- {
- Interface.Oxide.DataFileSystem.WriteObject("DeathNotes", canRead);
- }
- static public void _LoadConfig()
- {
- SetConfig("Settings", "Chat Icon (SteamID)", "76561198077847390");
- SetConfig("Settings", "Message Radius Enabled", false);
- SetConfig("Settings", "Message Radius", 300f);
- SetConfig("Settings", "Log to File", false);
- SetConfig("Settings", "Write to Console", true);
- SetConfig("Settings", "Use Popup Notifications", false);
- SetConfig("Settings", "Title", "Death Notes");
- SetConfig("Settings", "Formatting", "[{Title}]: {Message}");
- SetConfig("Settings", "Console Formatting", "{Message}");
- SetConfig("Settings", "Attachments Split", " | ");
- SetConfig("Settings", "Attachments Formatting", " ({attachments})");
- SetConfig("Settings", "Title Color", "#80D000");
- SetConfig("Settings", "Victim Color", "#C4FF00");
- SetConfig("Settings", "Attacker Color", "#C4FF00");
- SetConfig("Settings", "Weapon Color", "#C4FF00");
- SetConfig("Settings", "Attachments Color", "#C4FF00");
- SetConfig("Settings", "Distance Color", "#C4FF00");
- SetConfig("Settings", "Bodypart Color", "#C4FF00");
- SetConfig("Settings", "Message Color", "#696969");
- SetConfig("Names", new Dictionary<string, object> { });
- SetConfig("Bodyparts", new Dictionary<string, object> { });
- SetConfig("Weapons", new Dictionary<string, object> { });
- SetConfig("Attachments", new Dictionary<string, object> { });
- SetConfig("Messages", "Bleeding", new List<string> { "{victim} bled out." });
- SetConfig("Messages", "Blunt", new List<string> { "{attacker} used a {weapon} to knock {victim} out." });
- SetConfig("Messages", "Bullet", new List<string> { "{victim} was shot in the {bodypart} by {attacker} with a {weapon}{attachments} from {distance}m." });
- SetConfig("Messages", "Cold", new List<string> { "{victim} became an iceblock." });
- SetConfig("Messages", "Drowned", new List<string> { "{victim} tried to swim." });
- SetConfig("Messages", "Explosion", new List<string> { "{victim} was shredded by {attacker}'s {weapon}" });
- SetConfig("Messages", "Fall", new List<string> { "{victim} did a header into the ground." });
- SetConfig("Messages", "Generic", new List<string> { "The death took {victim} with him." });
- SetConfig("Messages", "Heat", new List<string> { "{victim} burned to ashes." });
- SetConfig("Messages", "Helicopter", new List<string> { "{victim} was shot to pieces by a {attacker}." });
- SetConfig("Messages", "HelicopterDeath", new List<string> { "The {victim} was taken down." });
- SetConfig("Messages", "Animal", new List<string> { "A {attacker} followed {victim} until it finally caught him." });
- SetConfig("Messages", "AnimalDeath", new List<string> { "{attacker} killed a {victim} with a {weapon}{attachments} from {distance}m." });
- SetConfig("Messages", "Hunger", new List<string> { "{victim} forgot to eat." });
- SetConfig("Messages", "Poison", new List<string> { "{victim} died after being poisoned." });
- SetConfig("Messages", "Radiation", new List<string> { "{victim} became a bit too radioactive." });
- SetConfig("Messages", "Slash", new List<string> { "{attacker} slashed {victim} in half." });
- SetConfig("Messages", "Stab", new List<string> { "{victim} was stabbed to death by {attacker} using a {weapon}." });
- SetConfig("Messages", "Structure", new List<string> { "A {attacker} impaled {victim}." });
- SetConfig("Messages", "Suicide", new List<string> { "{victim} had enough of life." });
- SetConfig("Messages", "Thirst", new List<string> { "{victim} dried internally." });
- SetConfig("Messages", "Trap", new List<string> { "{victim} ran into a {attacker}" });
- SetConfig("Messages", "Turret", new List<string> { "A {attacker} defended its home against {victim}." });
- SetConfig("Messages", "Unknown", new List<string> { "{victim} died. Nobody knows why, it just happened." });
- Kirc.dis._SaveConfig();
- }
- static public void _LoadMessages()
- {
- Kirc.dis._lang.RegisterMessages(new Dictionary<string, string>
- {
- {"No Permission", "You don't have permission to use this command."},
- {"Hidden", "You do no longer see death messages."},
- {"Unhidden", "You will now see death messages."}
- }, Kirc.dis);
- }
- ////////////////////////////////////////
- /// DeathNotes Information
- ////////////////////////////////////////
- static public void _GetInfo(BasePlayer player)
- {
- /*webrequest.EnqueueGet("http://oxidemod.org/plugins/819/", (code, response) => {
- if (code != 200)
- {
- PrintWarning("Failed to get information!");
- return;
- }
- string version_published = "0.0.0";
- string version_installed = this.Version.ToString();
- Match version = new Regex(@"<h3>Version (\d{1,2}\.\d{1,2}(\.\d{1,2})?)<\/h3>").Match(response);
- if (version.Success)
- {
- version_published = version.Groups[1].ToString();
- }
- SendChatMessage(player, $"<size=25><color=#C4FF00>DeathNotes</color></size> <size=20><color=#696969>by LaserHydra</color>{Environment.NewLine}<color=#696969>Latest <color=#C4FF00>{version_published}</color>{Environment.NewLine}Installed <color=#C4FF00>{version_installed}</color></color></size>");
- }, this);*/
- }
- ////////////////////////////////////////
- /// Death Related
- ////////////////////////////////////////
- static public HitInfo TryGetLastWounded(ulong uid, HitInfo info)
- {
- if (LastWounded.ContainsKey(uid))
- {
- HitInfo output = LastWounded[uid];
- LastWounded.Remove(uid);
- return output;
- }
- return info;
- }
- static public void _OnEntityTakeDamage(BaseCombatEntity victim, HitInfo info)
- {
- if (victim != null && victim.ToPlayer() != null && info != null && info?.Initiator != null && info?.Initiator?.ToPlayer() != null)
- {
- Kirc.dis._NextTick(() =>
- {
- if (victim.ToPlayer().IsWounded())
- LastWounded[victim.ToPlayer().userID] = info;
- });
- }
- }
- static public void _OnEntityDeath(BaseCombatEntity victim, HitInfo info)
- {
- if (victim == null)
- return;
- if (victim.ToPlayer() != null)
- {
- if (victim.ToPlayer().IsWounded())
- info = TryGetLastWounded(victim.ToPlayer().userID, info);
- }
- if (info?.Initiator?.ToPlayer() == null && (bool)victim?.name?.Contains("autospawn"))
- return;
- DeathData data = new DeathData();
- data.victim.entity = victim;
- data.victim.type = data.victim.TryGetType();
- if (data.victim.type == VictimType.Invalid)
- return;
- data.victim.name = data.victim.TryGetName();
- if (info?.Initiator != null)
- data.attacker.entity = info?.Initiator as BaseCombatEntity;
- else
- data.attacker.entity = victim.lastAttacker as BaseCombatEntity;
- data.attacker.type = data.attacker.TryGetType();
- data.attacker.name = data.attacker.TryGetName();
- data.weapon = info?.Weapon?.GetItem()?.info?.displayName?.english ?? FormatThrownWeapon(info?.WeaponPrefab?.name ?? "No Weapon");
- data.attachments = GetAttachments(info);
- data.damageType = FirstUpper(victim.lastDamage.ToString());
- if (data.weapon == "Heli Rocket")
- {
- data.attacker.name = "Patrol Helicopter";
- data.reason = DeathReason.Helicopter;
- }
- if (info?.HitBone != null)
- data.bodypart = FirstUpper(GetBoneName(victim, ((uint)info?.HitBone)) ?? string.Empty);
- else
- data.bodypart = FirstUpper("Body") ?? string.Empty;
- data.reason = data.TryGetReason();
- DeathData newData = UpdateData(data);
- if (string.IsNullOrEmpty(GetDeathMessage(newData, false)))
- return;
- foreach (BasePlayer player in BasePlayer.activePlayerList)
- {
- if (!canRead.ContainsKey(player.userID) && HasPerm(player.userID, "see"))
- canRead.Add(player.userID, true);
- if (HasPerm(player.userID, "see") && InRadius(player, data.attacker.entity) && canRead.ContainsKey(player.userID) && canRead[player.userID])
- //SendChatMessage(player, GetDeathMessage(newData, false), null, GetConfig("76561198077847390", "Settings", "Chat Icon (SteamID)"));
- Kirc.dis.irc.Say((string)Kirc.dis.Config["channel"], GetDeathMessage(newData, false));
- }
- if (GetConfig(true, "Settings", "Write to Console"))
- Kirc.dis.Log(StripTags(GetDeathMessage(newData, true)));
- if (GetConfig(false, "Settings", "Log to File"))
- ConVar.Server.Log("oxide/logs/Kills.txt", StripTags(GetDeathMessage(newData, true)));
- if (debug)
- {
- Kirc.dis.Log("DATA: " + Environment.NewLine + data.JSON);
- Kirc.dis.Log("UPDATED DATA: " + Environment.NewLine + newData.JSON);
- }
- }
- ////////////////////////////////////////
- /// Formatting Methods
- ////////////////////////////////////////
- static string FormatThrownWeapon(string unformatted)
- {
- if (unformatted == string.Empty)
- return string.Empty;
- string formatted = FirstUpper(unformatted.Split('/').Last().Replace(".prefab", "").Replace(".entity", ""));
- if (formatted == "Knife Bone")
- formatted = "Bone Knife";
- else if (formatted == "Spear Wooden")
- formatted = "Wooden Spear";
- else if (formatted == "Spear Stone")
- formatted = "Stone Spear";
- else if (formatted == "Axe Salvaged")
- formatted = "Salvaged Axe";
- else if (formatted == "Hammer Salvaged")
- formatted = "Salvaged Hammer";
- else if (formatted == "Icepick Salvaged")
- formatted = "Salvaged Icepick";
- else if (formatted == "Stonehatchet")
- formatted = "Stone Hatchet";
- else if (formatted == "Explosive Timed")
- formatted = "Timed Explosive Charge";
- else if (formatted == "Grenade F1")
- formatted = "F1 Grenade";
- else if (formatted == "Rocket Heli")
- formatted = "Heli Rocket";
- else if (formatted == "Rocket Hv")
- formatted = "HV-Rocket";
- else if (formatted == "Rocket basic")
- formatted = "Rocket";
- else if (formatted == "Rocket Fire")
- formatted = "Incendiary Rocket";
- return formatted;
- }
- static string StripTags(string original)
- {
- List<string> regexTags = new List<string>
- {
- @"<color=.+?>",
- @"<size=.+?>"
- };
- List<string> tags = new List<string>
- {
- "</color>",
- "</size>",
- "<i>",
- "</i>",
- "<b>",
- "</b>"
- };
- foreach (string tag in tags)
- original = original.Replace(tag, "");
- foreach (string regexTag in regexTags)
- original = new Regex(regexTag).Replace(original, "");
- return original;
- }
- static string FirstUpper(string original)
- {
- if (original == string.Empty)
- return string.Empty;
- List<string> output = new List<string>();
- foreach (string word in original.Split(' '))
- output.Add(word.Substring(0, 1).ToUpper() + word.Substring(1, word.Length - 1));
- return ListToString(output, 0, " ");
- }
- ////////////////////////////////////////
- /// Death Variables Methods
- ////////////////////////////////////////
- static List<string> GetAttachments(HitInfo info)
- {
- List<string> attachments = new List<string>();
- if (info?.Weapon?.GetItem()?.contents?.itemList != null)
- {
- foreach (var content in info?.Weapon?.GetItem().contents?.itemList as List<Item>)
- {
- attachments.Add(content?.info?.displayName?.english);
- }
- }
- return attachments;
- }
- static string GetBoneName(BaseCombatEntity entity, uint boneId)
- {
- return entity?.skeletonProperties?.FindBone(boneId)?.name?.english ?? "Body";
- }
- static bool InRadius(BasePlayer player, BaseCombatEntity attacker)
- {
- if (GetConfig(false, "Settings", "Message Radius Enabled"))
- {
- try
- {
- if (player.Distance(attacker) <= GetConfig(300f, "Settings", "Message Radius"))
- return true;
- else
- return false;
- }
- catch (Exception)
- {
- return false;
- }
- }
- return true;
- }
- static string GetDeathMessage(DeathData data, bool console)
- {
- string message = string.Empty;
- List<string> messages = new List<string>();
- try
- {
- messages = GetConfig(new List<string>(), "Messages", data.reason.ToString());
- }
- catch (InvalidCastException)
- {
- messages = (from msg in GetConfig(new List<object>(), "Messages", data.reason.ToString()) select msg.ToString()).ToList();
- }
- if (messages.Count == 0)
- return message;
- string attachmentsString = data.attachments.Count == 0 ? string.Empty : GetConfig(" ({attachments})", "Settings", "Attachments Formatting").Replace("{attachments}", ListToString(data.attachments, 0, GetConfig(" | ", "Settings", "Attachments Split")));
- if (console)
- message = GetConfig("{Message}", "Settings", "Console Formatting").Replace("{Title}", $"<color={GetConfig("#80D000", "Settings", "Title Color")}>{GetConfig("Death Notes", "Settings", "Title")}</color>").Replace("{Message}", $"<color={GetConfig("#696969", "Settings", "Message Color")}>{messages[UnityEngine.Random.Range(0, messages.Count - 1)].ToString()}</color>");
- else
- message = GetConfig("[{Title}]: {Message}", "Settings", "Formatting").Replace("{Title}", $"<color={GetConfig("#80D000", "Settings", "Title Color")}>{GetConfig("Death Notes", "Settings", "Title")}</color>").Replace("{Message}", $"<color={GetConfig("#696969", "Settings", "Message Color")}>{messages[UnityEngine.Random.Range(0, messages.Count - 1)].ToString()}</color>");
- message = message.Replace("{attacker}", $"<color={GetConfig("#C4FF00", "Settings", "Attacker Color")}>{data.attacker.name}</color>");
- message = message.Replace("{victim}", $"<color={GetConfig("#C4FF00", "Settings", "Victim Color")}>{data.victim.name}</color>");
- message = message.Replace("{distance}", $"<color={GetConfig("#C4FF00", "Settings", "Distance Color")}>{Math.Round(data.distance, 2).ToString()}</color>");
- message = message.Replace("{weapon}", $"<color={GetConfig("#C4FF00", "Settings", "Weapon Color")}>{data.weapon}</color>");
- message = message.Replace("{bodypart}", $"<color={GetConfig("#C4FF00", "Settings", "Bodypart Color")}>{data.bodypart}</color>");
- message = message.Replace("{attachments}", $"<color={GetConfig("#C4FF00", "Settings", "Attachments Color")}>{attachmentsString}</color>");
- return message;
- }
- static DeathData UpdateData(DeathData data)
- {
- bool configUpdated = false;
- if (data.victim.type != VictimType.Player)
- {
- if (_Config.Get("Names", data.victim.name) == null)
- {
- SetConfig("Names", data.victim.name, data.victim.name);
- configUpdated = true;
- }
- else
- data.victim.name = GetConfig(data.victim.name, "Names", data.victim.name);
- }
- if (data.attacker.type != AttackerType.Player)
- {
- if (_Config.Get("Names", data.attacker.name) == null)
- {
- SetConfig("Names", data.attacker.name, data.attacker.name);
- configUpdated = true;
- }
- else
- data.attacker.name = GetConfig(data.attacker.name, "Names", data.attacker.name);
- }
- if (_Config.Get("Bodyparts", data.bodypart) == null)
- {
- SetConfig("Bodyparts", data.bodypart, data.bodypart);
- configUpdated = true;
- }
- else
- data.bodypart = GetConfig(data.bodypart, "Bodyparts", data.bodypart);
- if (_Config.Get("Weapons", data.weapon) == null)
- {
- SetConfig("Weapons", data.weapon, data.weapon);
- configUpdated = true;
- }
- else
- data.weapon = GetConfig(data.weapon, "Weapons", data.weapon);
- string[] attachmentsCopy = new string[data.attachments.Count];
- data.attachments.CopyTo(attachmentsCopy);
- foreach (string attachment in attachmentsCopy)
- {
- if (_Config.Get("Attachments", attachment) == null)
- {
- SetConfig("Attachments", attachment, attachment);
- configUpdated = true;
- }
- else
- {
- data.attachments.Remove(attachment);
- data.attachments.Add(GetConfig(attachment, "Attachments", attachment));
- }
- }
- if (configUpdated)
- Kirc.dis._SaveConfig();
- return data;
- }
- ////////////////////////////////////////
- /// Converting
- ////////////////////////////////////////
- static string ListToString(List<string> list, int first, string seperator)
- {
- return String.Join(seperator, list.Skip(first).ToArray());
- }
- ////////////////////////////////////////
- /// Config & Message Related
- ////////////////////////////////////////
- static void SetConfig(params object[] args)
- {
- List<string> stringArgs = (from arg in args select arg.ToString()).ToList<string>();
- stringArgs.RemoveAt(args.Length - 1);
- if (_Config.Get(stringArgs.ToArray()) == null) _Config.Set(args);
- }
- static T GetConfig<T>(T defaultVal, params object[] args)
- {
- List<string> stringArgs = (from arg in args select arg.ToString()).ToList<string>();
- if (_Config.Get(stringArgs.ToArray()) == null)
- {
- Kirc.dis.Log($"The plugin failed to read something from the config: {ListToString(stringArgs, 0, "/")}{Environment.NewLine}Please reload the plugin and see if this message is still showing. If so, please post this into the support thread of this plugin.");
- return defaultVal;
- }
- return (T)Convert.ChangeType(_Config.Get(stringArgs.ToArray()), typeof(T));
- }
- static string GetMsg(string key, object userID = null)
- {
- return Kirc.dis._lang.GetMessage(key, Kirc.dis, userID.ToString());
- }
- ////////////////////////////////////////
- /// Permission Related
- ////////////////////////////////////////
- static void RegisterPerm(params string[] permArray)
- {
- string perm = ListToString(permArray.ToList(), 0, ".");
- Kirc.dis._permission.RegisterPermission($"{PermissionPrefix}.{perm}", Kirc.dis);
- }
- static bool HasPerm(object uid, params string[] permArray)
- {
- uid = uid.ToString();
- string perm = ListToString(permArray.ToList(), 0, ".");
- return Kirc.dis._permission.UserHasPermission(uid.ToString(), $"{PermissionPrefix}.{perm}");
- }
- static string PermissionPrefix
- {
- get
- {
- return Kirc.dis.Title.Replace(" ", "").ToLower();
- }
- }
- ////////////////////////////////////////
- /// Chat Handling
- ////////////////////////////////////////
- static public void BroadcastChat(string prefix, string msg = null) => Kirc.dis._rust.BroadcastChat(msg == null ? prefix : "<color=#C4FF00>" + prefix + "</color>: " + msg);
- static public void SendChatMessage(BasePlayer player, string prefix, string msg = null, object uid = null) => Kirc.dis._rust.SendChatMessage(player, msg == null ? prefix : "<color=#C4FF00>" + prefix + "</color>: " + msg, null, uid?.ToString() ?? "0");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement