Beispiel #1
0
        static async Task HNY()
        {
            string title = "Happy New Year!";
            string sub   = "- 2021 -";

            await rcon.ConnectAsync();

            await rcon.SendCommandAsync($"/title @a subtitle \"{sub}\" ");

            await rcon.SendCommandAsync($"/title @a title \"{title}\" ");
        }
Beispiel #2
0
        public async void ConsoleControl() //控制台
        {
            LogUpdate("\n正在尝试连接至RCON服务器...", null, null);
            try
            {
                RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password);
                await rcon.ConnectAsync();

                Title = "ASM - 管理: " + IP_address + ':' + Port.ToString();
                LogUpdate("\nRCON服务器已成功连接 IP:" + IP_address + " Port:" + Port.ToString(), null, null);
                LogUpdate("\n正在尝试打开玩家检测器...", null, null);
                Task PlayerUpdate = Task.Run(() =>
                {
                    Application.Current.Dispatcher.Invoke((Action)(() =>
                    {
                        PlayerNumUpdate();
                    }));
                });
                LogUpdate("\n玩家检测器已开启", null, null);
                LogUpdate("\n", null, null);
            }
            catch (AuthenticationException)
            {
                MessageExt.Instance.ShowDialog("您的RCON连接密码无法通过验证, 请检查输入的密码是否正确", "错误");
            }
        }
        public async Task <IActionResult> ExecuteRconCommand(Guid serverId)
        {
            // TODO: Put this somewhere sensible
            // TODO: Handle non-Minecraft servers
            // TODO: Figure out how to stream responses and events
            var server = await _servers.GetServerByIdAsync(serverId);

            var config        = server.DeserialiseConfiguration() as MinecraftConfiguration;
            var containerPort = config.RconContainerPort;
            // TODO: Is this reliable?

            var container = server
                            .Containers
                            .Find(c => c.ServerPorts.Any(p => p.ContainerPort == containerPort));

            if (container == null)
            {
                // TODO: Remove this once the Rcon port is properly exposed
                container = server.Containers.First();
            }

            // TODO: Don't hardcode this
            var ipAddresses = await Dns.GetHostAddressesAsync($"TRICERATOPS_{container.Name}");

            var rcon = new RCON(ipAddresses[0], containerPort, "testing");
            await rcon.ConnectAsync();

            string help = await rcon.SendCommandAsync("help");

            return(Json($"We got help from the server: {help}"));
        }
Beispiel #4
0
 public async Task testBadAuthAsync()
 {
     //Warning ! This test can ban your ip in the server if sv_rcon_maxfailure is set to 0
     //Use removeip to unban your ip (Default ban period is 60 min)
     rconClient.Dispose();
     rconClient = new RCON(_ip, _port, "wrong PW");
     await rconClient.ConnectAsync();
 }
Beispiel #5
0
        public async void PlayerNumUpdate() //玩家人数刷新
        {
            RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password);
            await rcon.ConnectAsync();

            while (true)
            {
                var ret = await rcon.SendCommandAsync("list");

                ret = ret.Replace("There are ", "").Replace("a max of ", "").Replace(" players online", "");
                string[] PlayerInfo = Regex.Split(ret, " of ", RegexOptions.IgnoreCase);
                string[] PlayerList;
                try
                {
                    PlayerList = Regex.Split(Regex.Split(PlayerInfo[1], ": ", RegexOptions.IgnoreCase)[1], ", ", RegexOptions.IgnoreCase);
                }
                catch
                {
                    PlayerList = new string[] { };
                }
                ushort PlayerNum = ushort.Parse(PlayerInfo[0]);

                if (PlayerList.Length == 0)
                {
                    PlayerListBox.Items.Clear();
                }
                List <string> PlayerListShowTemp = new List <string> {
                };
                for (int i = 0; i < PlayerList.Length; ++i) //PlayerListBox.Items与PlayerList差异添加
                {
                    if (PlayerListBox.Items.IndexOf(PlayerList[i]) == -1)
                    {
                        PlayerListBox.Items.Add(PlayerList[i]);
                    }
                }
                foreach (string i in PlayerListBox.Items) //避免foreach不可中途删除导致的错误
                {
                    PlayerListShowTemp.Add(i);
                }
                string[] PlayerListShow = PlayerListShowTemp.ToArray();
                for (int i = 0; i < PlayerListShow.Length; ++i) //PlayerListBox.Items与PlayerList差异删除
                {
                    try
                    {
                        if (PlayerListBox.Items.IndexOf(PlayerList[i]) == -1)
                        {
                            PlayerListBox.Items.Remove(PlayerList[i]);
                        }
                    }
                    catch
                    {
                        PlayerListBox.Items.Remove(PlayerListShow[i]);;
                    }
                }
                PlayerNumLabel.Content = PlayerInfo[0] + " 个玩家在线";
                await Task.Delay(1000);
            }
        }
Beispiel #6
0
    public async Task TestRconPrintInfo()
    {
        var serverInfo = _settings.Left4DeadSettings.ServerInfo;

        using var rcon = new RCON(new IPEndPoint(IPAddress.Parse(serverInfo.Ip), serverInfo.Port), serverInfo.RconPassword);
        await rcon.ConnectAsync();

        var printInfo = await rcon.SendCommandAsync <PrintInfo>("sm_printinfo");
    }
Beispiel #7
0
    public async Task TestRconGameMode()
    {
        var serverInfo = _settings.Left4DeadSettings.ServerInfo;

        using var rcon = new RCON(new IPEndPoint(IPAddress.Parse(serverInfo.Ip), serverInfo.Port), serverInfo.RconPassword);
        await rcon.ConnectAsync();

        var gamemode = await rcon.SendCommandAsync <SmCvar>("sm_cvar mp_gamemode");
    }
Beispiel #8
0
        static async Task Main(string[] args)
        {
            String ip;
            int    port;
            String password;

            Console.WriteLine("Enter ip");
            ip = Console.ReadLine();
            Console.WriteLine("Enter port");
            port = int.Parse(Console.ReadLine());
            Console.WriteLine("Enter password");
            password = Console.ReadLine();

            var endpoint = new IPEndPoint(
                IPAddress.Parse(ip),
                port
                );

            rcon = new RCON(endpoint, password, 0);
            await rcon.ConnectAsync();

            bool connected = true;

            Console.WriteLine("Connected");

            rcon.OnDisconnected += () =>
            {
                Console.WriteLine("RCON Disconnected");
                connected = false;
            };

            while (connected)
            {
                String command = Console.ReadLine();
                if (command == "conctest")
                {
                    completed = 0;
                    List <Thread> threadList = new List <Thread>(ThreadCount);
                    for (int i = 0; i < ThreadCount; i++)
                    {
                        ThreadStart childref    = new ThreadStart(ConcurrentTestAsync);
                        Thread      childThread = new Thread(childref);
                        childThread.Start();
                        threadList.Add(childThread);
                    }
                    while (completed < ThreadCount)
                    {
                        await Task.Delay(1);
                    }
                    continue;
                }
                String response = await rcon.SendCommandAsync(command);

                Console.WriteLine(response);
            }
        }
Beispiel #9
0
        public async Task testLongResponseAsync()
        {
            rconClient.Dispose();
            rconClient = new RCON(_ip, _port, _password, 10000, true); //Enable multi packetsupport
            await rconClient.ConnectAsync();

            string response = await rconClient.SendCommandAsync("cvarList");

            Assert.IsTrue(response.EndsWith("total convars/concommands"));
        }
        static async Task Run()
        {
            ChestItemsData chestItemsData = new ChestItemsData();
            await rcon.ConnectAsync();

            var result = await rcon.SendCommandAsync(command);

            Console.WriteLine(result);

            chestItemsData.Extraction(result);
        }
        private async Task connectAsync()
        {
            if (IsConnected)
            {
                return;
            }

            await _rcon.ConnectAsync();

            IsConnected = true;
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            Users = FileManager <List <User> > .Load("users.json") ?? new List <User>();

            rCON.ConnectAsync().GetAwaiter().GetResult();
            Bot.OnMessage       += Bot_OnMessage;
            Bot.OnCallbackQuery += Bot_OnCallbackQuery;
            Bot.StartReceiving();
            while (true)
            {
                Thread.Sleep(int.MaxValue);
            }
        }
Beispiel #13
0
        private async void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            string tmp_detail = "";

            if (IP_Textbox.Text != "" && Port_Textbox.Text != "")
            {
                if (!IPAddress.TryParse(IP_Textbox.Text, out IPAddress IPCheck))
                {
                    tmp_detail += "Illegal IP address\n";
                }
                if (int.Parse(Port_Textbox.Text) < 0 || int.Parse(Port_Textbox.Text) > 65536)
                {
                    tmp_detail += "Wrong port";
                }
                if (tmp_detail != "")
                {
                    MessageExt.Instance.ShowDialog(tmp_detail, "Error");
                }
                else
                {
                    if (CheckConnect(IP_Textbox.Text, int.Parse(Port_Textbox.Text)))
                    {
                        IP_address = IP_Textbox.Text;
                        Port       = ushort.Parse(Port_Textbox.Text);
                        Password   = Password_Passwordbox.Password;

                        var rcon = new RCON(IPAddress.Parse(IP_address), Port, Password);
                        try
                        {
                            await rcon.ConnectAsync();

                            SaveConnectFile(IP_address, Port, Password);

                            this.ShowInTaskbar = false;
                            this.Visibility    = Visibility.Hidden;

                            Manage manage_window = new Manage();
                            manage_window.ShowDialog();
                        }
                        catch (AuthenticationException)
                        {
                            MessageExt.Instance.ShowDialog("您的RCON密码验证失败", "错误");
                        }
                    }
                    else
                    {
                        MessageExt.Instance.ShowDialog("无法连接至服务器,请检查您输入的IP地址和RCON端口是否正确,且保证服务器开启了RCON", "错误");
                    }
                }
            }
        }
Beispiel #14
0
 private void PlayerControlDEOP_Copy_Click(object sender, RoutedEventArgs e)
 {
     MessageExt.Instance.ShowYesNo("确认要将玩家" + PlayerControlNameLabel.Content + "的权限变更为成员吗?", "提示", new Action(() =>
     {
         this.Dispatcher.Invoke((Action)async delegate()
         {
             RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password);
             await rcon.ConnectAsync();
             await rcon.SendCommandAsync("deop " + PlayerControlNameLabel.Content);
             await rcon.SendCommandAsync("tellraw @a [{\"text\":\"ASM\",\"color\":\"aqua\",\"bold\":true},{\"text\":\" >>> \",\"color\":\"green\",\"bold\":false},{\"text\":\"" + PlayerControlNameLabel.Content + "的权限等级已调整为成员\",\"color\":\"gold\"}]");
         });
     }));
     PlayerControlGrid.Visibility = Visibility.Hidden;
 }
        public async Task <RCON> GetRconConnection()
        {
            SshClient client = await sshClient.Value;

            // TODO automagic restart
            if (!client.IsConnected)
            {
                throw new InvalidOperationException("Cannot get an RCON connection; SSH has been disconnected.");
            }

            RCON rcon = new RCON(IPAddress.Loopback, localRconPort, providerConfig.RconPassword);
            await rcon.ConnectAsync();

            return(rcon);
        }
Beispiel #16
0
 private async Task Connect()
 {
     try
     {
         await _rcon.ConnectAsync().ConfigureAwait(false);
     }
     // {"No connection could be made because the target machine actively refused it. 127.0.0.1:27020"}
     catch (System.Net.Sockets.SocketException ex)
         when(ex.Message?.Contains("No connection could be made because the target machine actively refused it") == true)
         {
             // can't connect
         }
     catch (System.Net.Sockets.SocketException ex)
     {
         Logging.LogException($"Exception attempting to connect to rcon server ({_config.Ip}:{_config.RconPort})", ex, typeof(SteamManager), LogLevel.DEBUG, ExceptionLevel.Ignored);
     }
 }
Beispiel #17
0
        private async Task CommandSend(string ipAddress, string mcCommand)
        {
            try
            {
                var    serveraddress = IPAddress.Parse(ipAddress); //IPアドレスとして扱うための変換
                var    serverpass    = "******";                //RCONでログインするためのパスワード
                ushort port          = 25575;                      //RCONのポート番号

                var rcon = new RCON(serveraddress, port, serverpass);
                await rcon.ConnectAsync(); //接続

                var result = await rcon.SendCommandAsync(mcCommand);

                logMessage = result;
            }
            catch (Exception ex)
            {
                logMessage = ex.Message;
            }
        }
        private async Task Execute(string your_ip, string command)
        {
            var    serveraddress = IPAddress.Parse(your_ip); //IPアドレスとして扱うための変換
            var    serverpass    = "******";              //RCONでログインするためのパスワード
            ushort port          = 25575;                    //サーバのポート番号

            try
            {
                var rcon = new RCON(serveraddress, port, serverpass);
                await rcon.ConnectAsync(); //接続

                var result = await rcon.SendCommandAsync(command);

                log = result;
            }
            catch (Exception e)
            {
                log = e.ToString();
            }
        }
        public string Get()
        {
            string result = "";

            if (!Startup.RCONTEST)
            {
                result = "Rcon test disabled";
            }
            else
            {
                try
                {
                    string[] rc = Startup.RCON.Split(":");
                    //test local server
                    var rcon = new RCON(IPAddress.Parse(rc[0]), ushort.Parse(rc[1]), rc[2]);
                    rcon.ConnectAsync().Wait();
                    result = rcon.SendCommandAsync("say NetCoreShop activated").Result;
                    // Set vip OK
                    //result = rcon.SendCommandAsync("lp user Edwardsky parent set vip").Result;

                    //give 64 apples
                    //result = rcon.SendCommandAsync("give Edwardsky apple 64").Result;
                    //op Ok
                    //result = rcon.SendCommandAsync("op Edwardsky").Result;

                    // Set money OK
                    //result = rcon.SendCommandAsync("economy give Edwardsky 100000").Result;


                    // Status status = rcon.SendCommandAsync<Status>("status").Result;

                    // result = status.Version;
                }
                catch (Exception ex)
                {
                    result = ex.ToString();
                }
            }
            return(result);
        }
        private async Task Announce(string version)
        {
            var duration = 5;
            var rcon     = new RCON(IPAddress.Parse(Configuration.RconIp), Configuration.RconPort, Configuration.RconPassword);

            try
            {
                await rcon.ConnectAsync();

                await rcon.SendCommandAsync($"say Minecraft v{version} is available, server will go down for updates in {duration} minutes");

                await Task.Delay((duration - 1) * 1000 * 60);

                await rcon.SendCommandAsync($"say Minecraft v{version} is available, server will go down for updates in 1 minute");

                await Task.Delay(1 * 1000 * 60);
            }
            catch (Exception exception)
            {
                Logger.LogWarning("Could not connect to rcon to warn of server shutdown: {0}", exception.Message);
            }
        }
Beispiel #21
0
        public async Task InitializeRconAsync()
        {
            try
            {
                Rcon = new RCON(IPAddress.Parse(IP), Port, RconPassword);

                await Rcon.ConnectAsync();

                //await Rcon.SendCommandAsync("say DiscordGo connected.");
                await Rcon.SendCommandAsync($"logaddress_add {Helpers.GetPublicIPAddress()}:{Config.LogPort}");

                //Match.IsLive = true;

                Authed = true;
                return;
            }
            catch (Exception e)
            {
                Authed = false;
                Console.WriteLine($"EXCEPTION: {e}");
                return;
            }
        }
Beispiel #22
0
        private async void Connect_Click(object sender, RoutedEventArgs e)
        {
            if (rcon == null && !busy)
            {
                busy = true;

                SetClientStatus(ClientStatus.Connecting);
                PrintText("Connecting to {0}:{1}", rconAddress.Text, rconPort.Text);

                IPAddress[] ips = Dns.GetHostAddresses(rconAddress.Text);
                if (ips.Length == 0)
                {
                    SetClientStatus(ClientStatus.Disconnected);
                    PrintText("Error: Can't find any IP address for {0}", rconAddress.Text);
                    busy = false;
                    return;
                }

                try {
                    rcon = new RCON(ips[0], UInt16.Parse(rconPort.Text), rconPassword.Password);
                    rcon.OnDisconnected += Rcon_Disconnected;
                    await rcon.ConnectAsync();
                }
                catch (Exception exc) {
                    SetClientStatus(ClientStatus.Disconnected);
                    PrintText("Error: Can't connect ({0})", exc.Message);
                    rcon = null;
                    busy = false;
                    return;
                }

                SetClientStatus(ClientStatus.Connected);
                PrintText("Connected!");

                busy = false;
            }
        }
Beispiel #23
0
        private async Task <Status> RunRCON(string command)
        {
            ipaddress = ConfigurationManager.AppSettings["IPAddress"];
            password  = ConfigurationManager.AppSettings["ServerAdminPassword"];
            port      = Int32.Parse(ConfigurationManager.AppSettings["RConPort"]);
            var endpoint = new IPEndPoint(
                IPAddress.Parse(ipaddress),
                port
                );
            var rcon = new RCON(endpoint, password);

            Process[] pname = Process.GetProcessesByName("ShooterGameServer");
            if (pname.Length == 0)
            {
                return(Status.OFFLINE);
            }
            else
            {
                try
                {
                    await rcon.ConnectAsync();

                    Debug.WriteLine("Rcon connected");
                    if (!String.IsNullOrEmpty(command))
                    {
                        await rcon.SendCommandAsync(command);
                    }
                    return(Status.ONLINE);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: No connection - {0}", ex.ToString());
                    return(Status.STARTING);
                }
            }
        }
Beispiel #24
0
        private async void CommandRunBtn_Click(object sender, RoutedEventArgs e)
        {
            string command = CommandText.Text;
            var    rcon    = new RCON(IPAddress.Parse(IP_address), Port, Password);
            await rcon.ConnectAsync();

            var ret = await rcon.SendCommandAsync(command);

            if (ret == "")
            {
                LogUpdate("命令成功执行", command, null);
            }
            else if (ret.IndexOf('§') == -1)
            {
                LogUpdate(ret, command, null);
            }
            else
            {
                ret = Regex.Replace(ret, @"§[a-g0-9]", "");
                LogUpdate(ret, command, null);

                /* 彩色输出(失败)
                 * LogUpdate(null, command, null);
                 * ret += "§0";
                 * string tempStr = "";
                 * string[] process = Regex.Split(ret, "\n", RegexOptions.IgnoreCase);
                 * string color = "§0";
                 * var realColor = Brushes.Black;
                 * foreach (string i in process)
                 * {
                 *  for (int j = 0; j < i.Length; ++j)
                 *  {
                 *      if (i[j] == '§')
                 *      {
                 *          if (tempStr != "")
                 *          {
                 *              if (color == "§0")
                 *              {
                 *                  realColor = Brushes.Black;
                 *              }
                 *              else if (color == "§1")
                 *              {
                 *                  realColor = Brushes.DarkBlue;
                 *              }
                 *              else if (color == "§2")
                 *              {
                 *                  realColor = Brushes.DarkGreen;
                 *              }
                 *              else if (color == "§3")
                 *              {
                 *                  realColor = Brushes.Aqua; //Wrong
                 *              }
                 *              else if (color == "§4")
                 *              {
                 *                  realColor = Brushes.DarkRed;
                 *              }
                 *              else if (color == "§5")
                 *              {
                 *                  realColor = Brushes.DarkViolet;
                 *              }
                 *              else if (color == "§6")
                 *              {
                 *                  realColor = Brushes.Gold;
                 *              }
                 *              else if (color == "§7")
                 *              {
                 *                  realColor = Brushes.Gray;
                 *              }
                 *              else if (color == "§8")
                 *              {
                 *                  realColor = Brushes.DarkGray;
                 *              }
                 *              else if (color == "§9")
                 *              {
                 *                  realColor = Brushes.Blue;
                 *              }
                 *              else if (color == "§a")
                 *              {
                 *                  realColor = Brushes.Green;
                 *              }
                 *              else if (color == "§b")
                 *              {
                 *                  realColor = Brushes.Aqua;
                 *              }
                 *              else if (color == "§c")
                 *              {
                 *                  realColor = Brushes.Red;
                 *              }
                 *              else if (color == "§d")
                 *              {
                 *                  realColor = Brushes.Pink;
                 *              }
                 *              else if (color == "§e")
                 *              {
                 *                  realColor = Brushes.Yellow;
                 *              }
                 *              else if (color == "§f")
                 *              {
                 *                  realColor = Brushes.White;
                 *              }
                 *              else if (color == "§g")
                 *              {
                 *                  realColor = Brushes.DarkGoldenrod;
                 *              }
                 *              Run commandLineTemp2 = new Run(tempStr) { Foreground = realColor };
                 *              commandTemp.Inlines.Add(commandLineTemp2);
                 *              tempStr = "";
                 *          }
                 *          color = i[j].ToString() + i[j + 1].ToString();
                 ++j;
                 *          continue;
                 *      }
                 *      else
                 *      {
                 *          tempStr += i[j];
                 *      }
                 *  }
                 * }
                 * Run commandLineTemp = new Run(tempStr) { Foreground = realColor };
                 * commandTemp.Inlines.Add(commandLineTemp);
                 * ConsoleTextBox.Document.Blocks.Add(commandTemp);
                 */
            }
        }
 public virtual Task ConnectAsync()
 {
     return(_rcon.ConnectAsync());
 }
Beispiel #26
0
 public async Task testInitAsync()
 {
     rconClient = new RCON(_ip, _port, _password, 1000, false);
     await rconClient.ConnectAsync();
 }
Beispiel #27
0
        public static async void FactorioThread()
        {
            RCON rcon = new RCON(IPAddress.Parse("127.0.0.1"), 25555, "password");

            while (true)
            {
                try {
                    await rcon.ConnectAsync();

                    break;
                }
                catch {
                    Thread.Sleep(1000);
                }
            }

            bool connected = true;

            while (true)
            {
                if (holdFSend)
                {
                    holdFSend = false;
                    string getdata = await rcon.SendCommandAsync(@"/silent-command remote.call(""send_items"",""send_items"")");

                    Dictionary <string, List <factorioItem> > pairs = new Dictionary <string, List <factorioItem> >();
                    pairs = JsonConvert.DeserializeObject <Dictionary <string, List <factorioItem> > >(getdata);
                    Console.WriteLine(getdata);
                }
                if (holdFReceive)
                {
                    holdFReceive = false;
                    var factorioItem1   = new factorioItem("transport-belt", 10);
                    var factorioItem2   = new factorioItem("wooden-chest", 100);
                    var factorioFluid1  = new factorioItem("water", 15000);
                    var factorioFluid2  = new factorioItem("steam", 25000);
                    var factorioEnergy1 = new factorioItem("energy", 111111);

                    Dictionary <string, int> factorioItems = new Dictionary <string, int>();
                    factorioItems.Add(factorioItem1.name, factorioItem1.count);
                    factorioItems.Add(factorioItem2.name, factorioItem2.count);

                    Dictionary <string, int> factorioFluids = new Dictionary <string, int>();
                    factorioFluids.Add(factorioFluid1.name, factorioFluid1.count);
                    factorioFluids.Add(factorioFluid2.name, factorioFluid2.count);

                    Dictionary <string, int> factorioEnergy = new Dictionary <string, int>();
                    factorioEnergy.Add(factorioEnergy1.name, factorioEnergy1.count);

                    string items  = JsonConvert.SerializeObject(factorioItems);
                    string fluids = JsonConvert.SerializeObject(factorioFluids);
                    string energy = JsonConvert.SerializeObject(factorioEnergy);

                    Console.WriteLine(items);
                    Console.WriteLine(fluids);
                    Console.WriteLine(energy);

                    string sendItems = await rcon.SendCommandAsync(string.Format(@"/command remote.call(""receive_items"",""inputItems"",'{0}')", items));

                    string sendFluids = await rcon.SendCommandAsync(string.Format(@"/silent-command remote.call(""receive_fluids"",""inputFluids"",'{0}')", fluids));

                    string sendEnergy = await rcon.SendCommandAsync(string.Format(@"/silent-command remote.call(""receive_energy"",""inputEnergy"",'{0}')", energy));
                }
            }
        }
Beispiel #28
0
        void Start()
        {
            var task = Task.Run(async() =>
            {
                try
                {
                    _token.Token.ThrowIfCancellationRequested();
                    var endpoint = new IPEndPoint(IPAddress.Parse(_ip), int.Parse(_port));
                    _RCON        = new RCON(endpoint, _rconpassword, 0);
                    await _RCON.ConnectAsync();

                    Connected = true;


                    _RCON.OnDisconnected += Rcon_OnDisconnected;
                    //this.playerThread = new Thread(async delegate ()
                    //{
                    //    List<Team> teams = owner.GetTeams();
                    //    List<Player> players = owner.GetPlayers();
                    //    var query = teams.Join
                    //    (players,
                    //     team => team.Id,
                    //     player => player.TeamId,
                    //     (team, player) => new { player, team });

                    //    Thread.Sleep(10000);
                    //    while (Connected)
                    //    {
                    //        string r = await _RCON.SendCommandAsync("listplayers").ConfigureAwait(false);
                    //        string[] s = r.Split("\r\n");

                    //        foreach (string str in s)
                    //        {
                    //            foreach (var v in query)
                    //            {
                    //                if (str.Contains(v.player.SteamID) && v.team.OpenMap != MapName)
                    //                {
                    //                    await _RCON.SendCommandAsync("kickplayer " + v.player.SteamID);
                    //                }
                    //            }
                    //        }
                    //    }
                    //});
                    //playerThread.Start();
                    this.chatThread = new Thread(async delegate()
                    {
                        Thread.Sleep(5000);
                        while (Connected)
                        {
                            try
                            {
                                string r   = await _RCON.SendCommandAsync("getchat").ConfigureAwait(false);
                                string[] s = r.Split("\r\n");

                                foreach (string str in s)
                                {
                                    if (str.Contains("Server received, But no response!!"))
                                    {
                                    }
                                    else
                                    {
                                        if (str.Contains("was killed by"))
                                        {
                                            //Tribemember Human - Lvl 36 was killed by a Titanomyrma Soldier - Lvl 140!
                                            var regex = Regex.Match(r, "ID [0-9]{1,}:");

                                            if (!regex.Success)
                                            {
                                                continue;
                                            }
                                            string chk = str;

                                            string pt1 = "", pt2 = "";

                                            //Tribe Tribe of Human, ID 1837849902: Day 23, 11:39:57: <RichColor Color="1, 0, 0, 1">Your Raptor - Lvl 52 (Raptor) was killed by Brontosaurus - Lvl 76 (Brontosaurus) (dannyisgay)!</>)
                                            int indexOfTribeMember = chk.IndexOf("Tribemember");
                                            if (indexOfTribeMember > 0)
                                            {
                                                chk = chk.Substring(chk.IndexOf("Tribemember"));
                                                chk = chk.Substring(0, chk.IndexOf("</>"));
                                            }
                                            else
                                            {
                                                pt1 = chk.Substring(0, chk.IndexOf(","));
                                                pt2 = chk.Substring(chk.IndexOf("Your"));
                                                pt2 = pt2.Substring(0, pt2.IndexOf("</>"));
                                            }

                                            string[] split = chk.Split(" ");

                                            string playerName = "";
                                            int offset        = 0;
                                            for (int i = 1; i < split.Length; i++)
                                            {
                                                if (split[i] == "-")
                                                {
                                                    break;
                                                }
                                                playerName += split[i];
                                                offset++;
                                            }
                                            playerName = playerName.Trim();

                                            Player plr = owner.GetPlayer(playerName);
                                            if (plr != null)
                                            {
                                                plr.DeathCount++;

                                                string killerName = "";
                                                for (int i = 7 + offset; i < split.Length; i++)
                                                {
                                                    if (split[i] == "-")
                                                    {
                                                        break;
                                                    }
                                                    killerName += split[i];
                                                    offset++;
                                                }

                                                Player klr = owner.GetPlayer(killerName);

                                                List <Team> teams = owner.GetTeams();

                                                bool pKill = false;
                                                foreach (var team in teams)
                                                {
                                                    string pattern = @$ "- Lvl [0-9]{1,3} was killed by {killerName} \({team.TribeName}\)";

                                                    var regex2 = Regex.Match(chk, pattern);
                                                    pKill      = regex2.Success;
                                                }

                                                if (klr != null && pKill)
                                                {
                                                    await owner.SendKillFeed(plr, klr);

                                                    Team t = owner.GetTeam(klr);
                                                    if (t != null)
                                                    {
                                                        t.MinutesRemaining += 60;
                                                    }
                                                }
                                                else
                                                // Check if Tribe Owned Dino killed player.
                                                {
                                                    teams.ForEach(async x =>
                                                    {
                                                        if (chk.Contains($"({x.TribeName}"))
                                                        {
                                                            await owner.SendKillFeed(chk, false).ConfigureAwait(false);
                                                            x.MinutesRemaining += 60;
                                                        }
                                                    });
                                                }
                                            }
                                            else
                                            {
                                                List <Team> teams = owner.GetTeams();
                                                teams.ForEach(async x =>
                                                {
                                                    if (pt2.Contains($"({x.TribeName}"))
                                                    {
                                                        await owner.SendKillFeed(pt1 + " - " + pt2, true).ConfigureAwait(false);
                                                    }
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                Connected = false;
                                _token.Cancel();
                                break;
                            }
                            Thread.Sleep(5000);
                        }
                    });
                    chatThread.Start();

                    await Task.Delay(-1, _token.Token).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Connected = false;
                    _token.Cancel();
                }
            });

            task.GetAwaiter().GetResult();

            Connected = false;
        }
Beispiel #29
0
        public async override Task CloseServer(Server server)
        {
            var     endpoint   = GetServerEndpoint(server);
            var     config     = new SourceConfigParser(server);
            Process serverProc = serverProcess[server.Id];

            bool succesfulShutdown = false;

            // Remove the PID and save
            using (var scope = _serviceScopeFactory.CreateScope())
                using (var db = scope.ServiceProvider.GetRequiredService <MonitorDBContext>())
                {
                    server.PID = null;

                    db.Update(server);
                    await db.SaveChangesAsync();
                }


            if (server.Graceful)
            {
                string rconPass = config.Get("rcon_password");

                if (!String.IsNullOrEmpty(rconPass))
                {
                    try
                    {
                        using (var rcon = new RCON(endpoint, rconPass))
                        {
                            await rcon.ConnectAsync();

                            await rcon.SendCommandAsync("quit");

                            succesfulShutdown = true;
                        }
                    }
                    catch (TimeoutException) { }
                    catch (AuthenticationException) { }
                }

                if (succesfulShutdown)
                {
                    using (var cts = new CancellationTokenSource())
                    {
                        cts.CancelAfter(30 * 1000);

                        await serverProc.WaitForExitAsync(cts.Token);

                        if (!serverProc.HasExited)
                        {
                            succesfulShutdown = false;
                        }
                    }
                }
            }

            if (!succesfulShutdown)
            {
                bool success = serverProc.CloseMainWindow();

                if (success)
                {
                    try
                    {
                        using (var cts = new CancellationTokenSource())
                        {
                            cts.CancelAfter(10 * 1000);

                            await serverProc.WaitForExitAsync(cts.Token);
                        }
                    }
                    catch (OperationCanceledException)
                    {
                        // Do nothing, this is intended
                    }
                }

                try
                {
                    if (!serverProc.HasExited)
                    {
                        serverProc.Kill();
                    }
                }
                catch
                {
                    // Ignore, process has finished
                }
            }

            // Automatically called by close event!
            //ServerClosed?.Invoke(server, new EventArgs());
        }
Beispiel #30
0
        private static async void Bot_OnMessage(object sender, MessageEventArgs e)
        {
            try
            {
                var msg     = e.Message;
                var msgFrom = e.Message.From;
                var msgText = e.Message.Text;
                int ui      = FindUser(msgFrom.Id);
                if (ui == -1)
                {
                    Users.Add(new User()
                    {
                        FName = msgFrom.FirstName, LName = msgFrom.LastName, UName = msgFrom.Username, Id = msgFrom.Id, PermissionLvl = 0
                    });
                    ui = FindUser(msgFrom.Id);
                }

                var user = Users[ui];
                Console.WriteLine($"[{DateTime.Now}] [{user.FName}] [{msgText}]");
                if (msgText == Passwd)
                {
                    Users[ui].PermissionLvl = 1;
                    await Bot.SendTextMessageAsync(msgFrom.Id, "Access Granted");

                    FileManager.Save("users.json", Users);
                    return;
                }
                if (msgText == "/start")
                {
                    await Bot.SendTextMessageAsync(msgFrom.Id, "Enter password");

                    return;
                }
                if (user.PermissionLvl == 1)
                {
                    if (!string.IsNullOrEmpty(user.Status))
                    {
                        if (user.Status == "SendCommandName")
                        {
                            if (msgText.Length > 30)
                            {
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Name must be 30 characters or less.");

                                return;
                            }
                            if (CheckNameCommand(user.Commands, msgText))
                            {
                                Users[ui].Status = "SendCommandText&*(" + msgText;
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Enter command");

                                return;
                            }
                            else
                            {
                                await Bot.SendTextMessageAsync(msgFrom.Id, "This name already exists");

                                return;
                            }
                        }
                        else if (user.Status.StartsWith("SendCommandText"))
                        {
                            string name = user.Status.Split("&*(")[1];
                            Users[ui].Commands.Add(new Command()
                            {
                                Name = name, CommandText = msgText
                            });
                            await Bot.SendTextMessageAsync(msgFrom.Id, "Successful binded");

                            Users[ui].Status = "";
                            FileManager.Save("users.json", Users);
                            return;
                        }
                        else if (user.Status == "DeleteCommand")
                        {
                            if (msgText == "/cancel")
                            {
                                Users[ui].Status = "";
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Cancelled");

                                return;
                            }
                            int index = FindCommand(user.Commands, msgText);
                            if (index == -1)
                            {
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Bind not found");

                                return;
                            }
                            else
                            {
                                Users[ui].Commands.RemoveAt(index);
                                Users[ui].Status = "";
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Command deleted");

                                FileManager.Save("users.json", Users);
                                return;
                            }
                        }
                    }
                    if (msgText.StartsWith("/"))
                    {
                        if (msgText == "/rconreconnect")
                        {
                            rCON = new RCON(IPAddress.Parse(Config.Get().IP), Config.Get().Port, Config.Get().Password);
                            await rCON.ConnectAsync();

                            await Bot.SendTextMessageAsync(msgFrom.Id, "Reconnected");

                            return;
                        }
                        else if (msgText == "/bind")
                        {
                            Users[ui].Status = "SendCommandName";
                            await Bot.SendTextMessageAsync(msgFrom.Id, "Enter new command name");

                            return;
                        }
                        else if (msgText == "/commandsmenu")
                        {
                            try
                            {
                                await Bot.SendTextMessageAsync(msgFrom.Id, "Menu", replyMarkup : Keyboard.GetMenu(user.Commands));
                            }
                            catch
                            {
                                await Bot.SendTextMessageAsync(msgFrom.Id, "You have not any binded command");
                            }
                            return;
                        }
                        else if (msgText == "/deletecommand")
                        {
                            Users[ui].Status = "DeleteCommand";
                            await Bot.SendTextMessageAsync(msgFrom.Id, "Enter command name to delete. /cancel - for cancel ( ͡° ͜ʖ ͡°)");

                            return;
                        }
                    }
                    var responce = await rCON.SendCommandAsync(msgText);

                    await Bot.SendTextMessageAsync(msgFrom.Id, responce);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                await Bot.SendTextMessageAsync(e.Message.From.Id, $"Error\n\n{ex.Message}");
            }
        }