/// <summary>
        /// Start a new Client
        /// </summary>
        private static void InitializeClient()
        {
            SessionToken session = new SessionToken();

            ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;

            if (Settings.Password == "-")
            {
                ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode.");
                result             = ProtocolHandler.LoginResult.Success;
                session.PlayerID   = "0";
                session.PlayerName = Settings.Login;
            }
            else
            {
                // Validate cached session or login new session.
                if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower()))
                {
                    session = SessionCache.Get(Settings.Login.ToLower());
                    result  = ProtocolHandler.GetTokenValidation(session);
                    if (result != ProtocolHandler.LoginResult.Success)
                    {
                        ConsoleIO.WriteLineFormatted("§8Cached session is invalid or expired.");
                        if (Settings.Password == "")
                        {
                            RequestPassword();
                        }
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted("§8Cached session is still valid for " + session.PlayerName + '.');
                    }
                }

                if (result != ProtocolHandler.LoginResult.Success)
                {
                    Console.WriteLine("Connecting to Minecraft.net...");
                    result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, out session);

                    if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None)
                    {
                        SessionCache.Store(Settings.Login.ToLower(), session);
                    }
                }
            }

            if (result == ProtocolHandler.LoginResult.Success)
            {
                Settings.Username = session.PlayerName;

                if (Settings.ConsoleTitle != "")
                {
                    Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                }

                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.setPlayerIconAsync(Settings.Username);
                }

                if (Settings.DebugMessages)
                {
                    Console.WriteLine("Success. (session ID: " + session.ID + ')');
                }

                //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE

                if (Settings.ServerIP == "")
                {
                    Console.Write("Server IP : ");
                    Settings.SetServerIP(Console.ReadLine());
                }

                //Get server version
                int       protocolversion = 0;
                ForgeInfo forgeInfo       = null;

                if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
                {
                    protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);

                    if (protocolversion != 0)
                    {
                        ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')');
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode.");
                    }

                    if (useMcVersionOnce)
                    {
                        useMcVersionOnce       = false;
                        Settings.ServerVersion = "";
                    }
                }

                if (protocolversion == 0)
                {
                    Console.WriteLine("Retrieving Server Info...");
                    if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
                    {
                        HandleFailure("Failed to ping this IP.", true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                if (protocolversion != 0)
                {
                    try
                    {
                        //Start the main TCP client
                        if (Settings.SingleCommand != "")
                        {
                            Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
                        }
                        else
                        {
                            Client = new McTcpClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
                        }

                        //Update console title
                        if (Settings.ConsoleTitle != "")
                        {
                            Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                        }
                    }
                    catch (NotSupportedException) { HandleFailure("Cannot connect to the server : This version is not supported !", true); }
                }
                else
                {
                    HandleFailure("Failed to determine server version.", true);
                }
            }
            else
            {
                string failureMessage = "Minecraft Login failed : ";
                switch (result)
                {
                case ProtocolHandler.LoginResult.AccountMigrated: failureMessage += "Account migrated, use e-mail as username."; break;

                case ProtocolHandler.LoginResult.ServiceUnavailable: failureMessage += "Login servers are unavailable. Please try again later."; break;

                case ProtocolHandler.LoginResult.WrongPassword: failureMessage += "Incorrect password, blacklisted IP or too many logins."; break;

                case ProtocolHandler.LoginResult.InvalidResponse: failureMessage += "Invalid server response."; break;

                case ProtocolHandler.LoginResult.NotPremium: failureMessage += "User not premium."; break;

                case ProtocolHandler.LoginResult.OtherError: failureMessage += "Network error."; break;

                case ProtocolHandler.LoginResult.SSLError: failureMessage += "SSL Error."; break;

                default: failureMessage += "Unknown Error."; break;
                }
                if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
                {
                    ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program."
                                                 + '\n' + "The first time, you have to import HTTPS certificates using:"
                                                 + '\n' + "mozroots --import --ask-remove");
                    return;
                }
                HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
            }
        }
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                Console.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO")
            {
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadSettings(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadSettings("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Other command-line arguments
            if (args.Length >= 1)
            {
                Settings.Login = args[0];
                if (args.Length >= 2)
                {
                    Settings.Password = args[1];
                    if (args.Length >= 3)
                    {
                        Settings.SetServerIP(args[2]);

                        //Single command?
                        if (args.Length >= 4)
                        {
                            Settings.SingleCommand = args[3];
                        }
                    }
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    ConsoleIO.WriteLineFormatted(cacheLoaded ? "§8Session data has been successfully loaded from disk." : "§8No sessions could be loaded from disk");
                }
            }

            //Asking the user to type in missing data such as Username and Password

            if (Settings.Login == "")
            {
                Console.Write(ConsoleIO.BasicIO ? "Please type the username or email of your choice.\n" : "Login : "******"" && (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())))
            {
                RequestPassword();
            }

            startupargs = args;
            InitializeClient();
        }
示例#3
0
        /// <summary>
        /// Starts the main chat client, wich will login to the server using the MinecraftCom class.
        /// </summary>
        /// <param name="user">The chosen username of a premium Minecraft Account</param>
        /// <param name="sessionID">A valid sessionID obtained with MinecraftCom.GetLogin()</param>
        /// <param name="server_ip">The server IP</param>
        /// <param name="port">The server port to use</param>
        /// <param name="protocolversion">Minecraft protocol version to use</param>
        /// <param name="uuid">The player's UUID for online-mode authentication</param>
        /// <param name="singlecommand">If set to true, the client will send a single command and then disconnect from the server</param>
        /// <param name="command">The text or command to send. Will only be sent if singlecommand is set to true.</param>
        private void StartClient(string user, string uuid, string sessionID, string server_ip, ushort port, int protocolversion, ForgeInfo forgeInfo, bool singlecommand, string command)
        {
            bool retry = false;

            this.sessionid = sessionID;
            this.uuid      = uuid;
            this.username  = user;
            this.host      = server_ip;
            this.port      = port;

            if (!singlecommand)
            {
                if (botsOnHold.Count == 0)
                {
                    BotLoad(new ChatBots.BalanceLogger(6000, "players.txt", "Balances.txt"));
                    BotLoad(new ChatBots.MoneyBot());
                    BotLoad(new ChatBots.FactionLogger(6000));
                    Console.WriteLine("MoneyBot loaded");
                    if (Settings.AntiAFK_Enabled)
                    {
                        BotLoad(new ChatBots.AntiAFK(Settings.AntiAFK_Delay));
                    }
                    if (Settings.Hangman_Enabled)
                    {
                        BotLoad(new ChatBots.HangmanGame(Settings.Hangman_English));
                    }
                    if (Settings.Alerts_Enabled)
                    {
                        BotLoad(new ChatBots.Alerts());
                    }
                    if (Settings.ChatLog_Enabled)
                    {
                        BotLoad(new ChatBots.ChatLog(Settings.ExpandVars(Settings.ChatLog_File), Settings.ChatLog_Filter, Settings.ChatLog_DateTime));
                    }
                    if (Settings.PlayerLog_Enabled)
                    {
                        BotLoad(new ChatBots.PlayerListLogger(Settings.PlayerLog_Delay, Settings.ExpandVars(Settings.PlayerLog_File)));
                    }
                    if (Settings.AutoRelog_Enabled)
                    {
                        BotLoad(new ChatBots.AutoRelog(Settings.AutoRelog_Delay, Settings.AutoRelog_Retries));
                    }
                    if (Settings.ScriptScheduler_Enabled)
                    {
                        BotLoad(new ChatBots.ScriptScheduler(Settings.ExpandVars(Settings.ScriptScheduler_TasksFile)));
                    }
                    if (Settings.RemoteCtrl_Enabled)
                    {
                        BotLoad(new ChatBots.RemoteControl());
                    }
                    if (Settings.AutoRespond_Enabled)
                    {
                        BotLoad(new ChatBots.AutoRespond(Settings.AutoRespond_Matches));
                    }
                    //Add your ChatBot here by uncommenting and adapting
                    //BotLoad(new ChatBots.YourBot());
                }
            }

            try
            {
                client = ProxyHandler.newTcpClient(host, port);
                client.ReceiveBufferSize = 1024 * 1024;
                handler = Protocol.ProtocolHandler.GetProtocolHandler(client, protocolversion, forgeInfo, this);
                Console.WriteLine("Version is supported.\nLogging in...");

                try
                {
                    if (handler.Login())
                    {
                        if (singlecommand)
                        {
                            handler.SendChatMessage(command);
                            ConsoleIO.WriteLineFormatted("§7Command §8" + command + "§7 sent.");
                            Thread.Sleep(5000);
                            handler.Disconnect();
                            Thread.Sleep(1000);
                        }
                        else
                        {
                            foreach (ChatBot bot in botsOnHold)
                            {
                                BotLoad(bot, false);
                            }
                            botsOnHold.Clear();

                            Console.WriteLine("Server was successfully joined.\nType '"
                                              + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar)
                                              + "quit' to leave the server.");

                            cmdprompt      = new Thread(new ThreadStart(CommandPrompt));
                            cmdprompt.Name = "MCC Command prompt";
                            cmdprompt.Start();
                        }
                    }
                }
                catch (Exception e)
                {
                    ConsoleIO.WriteLineFormatted("§8" + e.Message);
                    Console.WriteLine("Failed to join this server.");
                    retry = true;
                }
            }
            catch (SocketException e)
            {
                ConsoleIO.WriteLineFormatted("§8" + e.Message);
                Console.WriteLine("Failed to connect to this IP.");
                retry = true;
            }

            if (retry)
            {
                if (ReconnectionAttemptsLeft > 0)
                {
                    ConsoleIO.WriteLogLine("Waiting 5 seconds (" + ReconnectionAttemptsLeft + " attempts left)...");
                    Thread.Sleep(5000); ReconnectionAttemptsLeft--; Program.Restart();
                }
                else if (!singlecommand && Settings.interactiveMode)
                {
                    Program.HandleFailure();
                }
            }
        }
示例#4
0
        /// <summary>
        /// Perform an internal MCC command (not a server command, use SendText() instead for that!)
        /// </summary>
        /// <param name="command">The command</param>
        /// <param name="interactive_mode">Set to true if command was sent by the user using the command prompt</param>
        /// <param name="response_msg">May contain a confirmation or error message after processing the command, or "" otherwise.</param>
        /// <returns>TRUE if the command was indeed an internal MCC command</returns>
        public bool PerformInternalCommand(string command, ref string response_msg)
        {
            /* Load commands from the 'Commands' namespace */

            if (cmds.Count == 0)
            {
                Type[] cmds_classes = Program.GetTypesInNamespace("MinecraftClient.Commands");
                foreach (Type type in cmds_classes)
                {
                    if (type.IsSubclassOf(typeof(Command)))
                    {
                        try
                        {
                            Command cmd = (Command)Activator.CreateInstance(type);
                            cmds[cmd.CMDName.ToLower()] = cmd;
                            cmd_names.Add(cmd.CMDName.ToLower());
                            foreach (string alias in cmd.getCMDAliases())
                            {
                                cmds[alias.ToLower()] = cmd;
                            }
                        }
                        catch (Exception e)
                        {
                            ConsoleIO.WriteLine(e.Message);
                        }
                    }
                }
            }

            /* Process the provided command */

            string command_name = command.Split(' ')[0].ToLower();

            if (command_name == "help")
            {
                if (Command.hasArg(command))
                {
                    string help_cmdname = Command.getArgs(command)[0].ToLower();
                    if (help_cmdname == "help")
                    {
                        response_msg = "help <cmdname>: show brief help about a command.";
                    }
                    else if (cmds.ContainsKey(help_cmdname))
                    {
                        response_msg = cmds[help_cmdname].CMDDesc;
                    }
                    else
                    {
                        response_msg = "Unknown command '" + command_name + "'. Use 'help' for command list.";
                    }
                }
                else
                {
                    response_msg = "help <cmdname>. Available commands: " + String.Join(", ", cmd_names.ToArray()) + ". For server help, use '" + Settings.internalCmdChar + "send /help' instead.";
                }
            }
            else if (cmds.ContainsKey(command_name))
            {
                response_msg = cmds[command_name].Run(this, command);
            }
            else
            {
                response_msg = "Unknown command '" + command_name + "'. Use '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "help' for help.";
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Console Client for MC {0} to {1} - v{2} - By ORelio & Contributors", MCLowestVersion, MCHighestVersion, Version);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                ConsoleIO.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO" || args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
            {
                if (args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
                {
                    ConsoleIO.BasicIO_NoColor = true;
                }
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadSettings(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadSettings("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Load external translation file. Should be called AFTER settings loaded
            Translations.LoadExternalTranslationFile(Settings.Language);

            //Other command-line arguments
            if (args.Length >= 1)
            {
                Settings.Login = args[0];
                if (args.Length >= 2)
                {
                    Settings.Password = args[1];
                    if (args.Length >= 3)
                    {
                        Settings.SetServerIP(args[2]);

                        //Single command?
                        if (args.Length >= 4)
                        {
                            Settings.SingleCommand = args[3];
                        }
                    }
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Test line to troubleshoot invisible colors
            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted(Translations.Get("debug.color_test", "[0123456789ABCDEF]: [§00§11§22§33§44§55§66§77§88§99§aA§bB§cC§dD§eE§fF§r]"));
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    Translations.WriteLineFormatted(cacheLoaded ? "debug.session_cache_ok" : "debug.session_cache_fail");
                }
            }

            //Asking the user to type in missing data such as Username and Password
            bool useBrowser = Settings.AccountType == ProtocolHandler.AccountType.Microsoft && Settings.LoginMethod == "browser";

            if (Settings.Login == "")
            {
                if (useBrowser)
                {
                    ConsoleIO.WriteLine("Press Enter to skip session cache checking and continue sign-in with browser");
                }
                Console.Write(ConsoleIO.BasicIO ? Translations.Get("mcc.login_basic_io") + "\n" : Translations.Get("mcc.login"));
                Settings.Login = Console.ReadLine();
            }
            if (Settings.Password == "" &&
                (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())) &&
                !useBrowser)
            {
                RequestPassword();
            }


            startupargs = args;
            InitializeClient();
        }
        /// <summary>
        /// Handle fatal errors such as ping failure, login failure, server disconnection, and so on.
        /// Allows AutoRelog to perform on fatal errors, prompt for server version, and offline commands.
        /// </summary>
        /// <param name="errorMessage">Error message to display and optionally pass to AutoRelog bot</param>
        /// <param name="versionError">Specify if the error is related to an incompatible or unkown server version</param>
        /// <param name="disconnectReason">If set, the error message will be processed by the AutoRelog bot</param>
        public static void HandleFailure(string errorMessage = null, bool versionError = false, ChatBots.AutoRelog.DisconnectReason?disconnectReason = null)
        {
            if (!String.IsNullOrEmpty(errorMessage))
            {
                ConsoleIO.Reset();
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);
                }
                Console.WriteLine(errorMessage);

                if (disconnectReason.HasValue)
                {
                    if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage))
                    {
                        return; //AutoRelog is triggering a restart of the client
                    }
                }
            }

            if (Settings.interactiveMode)
            {
                if (versionError)
                {
                    Translations.Write("mcc.server_version");
                    Settings.ServerVersion = Console.ReadLine();
                    if (Settings.ServerVersion != "")
                    {
                        useMcVersionOnce = true;
                        Restart();
                        return;
                    }
                }

                if (offlinePrompt == null)
                {
                    offlinePrompt = new Thread(new ThreadStart(delegate
                    {
                        string command = " ";
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.disconnected", (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar)));
                        Translations.WriteLineFormatted("mcc.press_exit");
                        while (command.Length > 0)
                        {
                            if (!ConsoleIO.BasicIO)
                            {
                                ConsoleIO.Write('>');
                            }
                            command = Console.ReadLine().Trim();
                            if (command.Length > 0)
                            {
                                string message = "";

                                if (Settings.internalCmdChar != ' ' &&
                                    command[0] == Settings.internalCmdChar)
                                {
                                    command = command.Substring(1);
                                }

                                if (command.StartsWith("reco"))
                                {
                                    message = new Commands.Reco().Run(null, Settings.ExpandVars(command), null);
                                }
                                else if (command.StartsWith("connect"))
                                {
                                    message = new Commands.Connect().Run(null, Settings.ExpandVars(command), null);
                                }
                                else if (command.StartsWith("exit") || command.StartsWith("quit"))
                                {
                                    message = new Commands.Exit().Run(null, Settings.ExpandVars(command), null);
                                }
                                else if (command.StartsWith("help"))
                                {
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Reco().GetCmdDescTranslated());
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Connect().GetCmdDescTranslated());
                                }
                                else
                                {
                                    ConsoleIO.WriteLineFormatted(Translations.Get("icmd.unknown", command.Split(' ')[0]));
                                }

                                if (message != "")
                                {
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + message);
                                }
                            }
                        }
                    }));
                    offlinePrompt.Start();
                }
            }
            else
            {
                // Not in interactive mode, just exit and let the calling script handle the failure
                if (disconnectReason.HasValue)
                {
                    // Return distinct exit codes for known failures.
                    if (disconnectReason.Value == ChatBot.DisconnectReason.UserLogout)
                    {
                        Exit(1);
                    }
                    if (disconnectReason.Value == ChatBot.DisconnectReason.InGameKick)
                    {
                        Exit(2);
                    }
                    if (disconnectReason.Value == ChatBot.DisconnectReason.ConnectionLost)
                    {
                        Exit(3);
                    }
                    if (disconnectReason.Value == ChatBot.DisconnectReason.LoginRejected)
                    {
                        Exit(4);
                    }
                }
                Exit();
            }
        }
        /// <summary>
        /// Handle fatal errors such as ping failure, login failure, server disconnection, and so on.
        /// Allows AutoRelog to perform on fatal errors, prompt for server version, and offline commands.
        /// </summary>
        /// <param name="errorMessage">Error message to display and optionally pass to AutoRelog bot</param>
        /// <param name="versionError">Specify if the error is related to an incompatible or unkown server version</param>
        /// <param name="disconnectReason">If set, the error message will be processed by the AutoRelog bot</param>
        public static void HandleFailure(string errorMessage = null, bool versionError = false, ChatBots.AutoRelog.DisconnectReason?disconnectReason = null)
        {
            if (!String.IsNullOrEmpty(errorMessage))
            {
                ConsoleIO.Reset();
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(true);
                }
                Console.WriteLine(errorMessage);

                if (disconnectReason.HasValue)
                {
                    if (ChatBots.AutoRelog.OnDisconnectStatic(disconnectReason.Value, errorMessage))
                    {
                        return; //AutoRelog is triggering a restart of the client
                    }
                }
            }

            if (Settings.interactiveMode)
            {
                if (versionError)
                {
                    Console.Write("Server version : ");
                    Settings.ServerVersion = Console.ReadLine();
                    if (Settings.ServerVersion != "")
                    {
                        useMcVersionOnce = true;
                        Restart();
                        return;
                    }
                }

                if (offlinePrompt == null)
                {
                    offlinePrompt = new Thread(new ThreadStart(delegate
                    {
                        string command = " ";
                        ConsoleIO.WriteLineFormatted("Not connected to any server. Use '" + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + "help' for help.");
                        ConsoleIO.WriteLineFormatted("Or press Enter to exit Minecraft Console Client.");
                        while (command.Length > 0)
                        {
                            if (!ConsoleIO.BasicIO)
                            {
                                ConsoleIO.Write('>');
                            }
                            command = Console.ReadLine().Trim();
                            if (command.Length > 0)
                            {
                                string message = "";

                                if (Settings.internalCmdChar != ' ' &&
                                    command[0] == Settings.internalCmdChar)
                                {
                                    command = command.Substring(1);
                                }

                                if (command.StartsWith("reco"))
                                {
                                    message = new Commands.Reco().Run(null, Settings.ExpandVars(command));
                                }
                                else if (command.StartsWith("connect"))
                                {
                                    message = new Commands.Connect().Run(null, Settings.ExpandVars(command));
                                }
                                else if (command.StartsWith("exit") || command.StartsWith("quit"))
                                {
                                    message = new Commands.Exit().Run(null, Settings.ExpandVars(command));
                                }
                                else if (command.StartsWith("help"))
                                {
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Reco().CMDDesc);
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + (Settings.internalCmdChar == ' ' ? "" : "" + Settings.internalCmdChar) + new Commands.Connect().CMDDesc);
                                }
                                else
                                {
                                    ConsoleIO.WriteLineFormatted("§8Unknown command '" + command.Split(' ')[0] + "'.");
                                }

                                if (message != "")
                                {
                                    ConsoleIO.WriteLineFormatted("§8MCC: " + message);
                                }
                            }
                        }
                    }));
                    offlinePrompt.Start();
                }
            }
            else
            {
                Exit();
            }
        }
        /// <summary>
        /// Start a new Client
        /// </summary>
        private static void InitializeClient()
        {
            SessionToken session = new SessionToken();

            ProtocolHandler.LoginResult result = ProtocolHandler.LoginResult.LoginRequired;

            if (Settings.Password == "-")
            {
                Translations.WriteLineFormatted("mcc.offline");
                result             = ProtocolHandler.LoginResult.Success;
                session.PlayerID   = "0";
                session.PlayerName = Settings.Login;
            }
            else
            {
                // Validate cached session or login new session.
                if (Settings.SessionCaching != CacheType.None && SessionCache.Contains(Settings.Login.ToLower()))
                {
                    session = SessionCache.Get(Settings.Login.ToLower());
                    result  = ProtocolHandler.GetTokenValidation(session);
                    if (result != ProtocolHandler.LoginResult.Success)
                    {
                        Translations.WriteLineFormatted("mcc.session_invalid");
                        if (Settings.Password == "")
                        {
                            RequestPassword();
                        }
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.session_valid", session.PlayerName));
                    }
                }

                if (result != ProtocolHandler.LoginResult.Success)
                {
                    Translations.WriteLine("mcc.connecting", Settings.AccountType == ProtocolHandler.AccountType.Mojang ? "Minecraft.net" : "Microsoft");
                    result = ProtocolHandler.GetLogin(Settings.Login, Settings.Password, Settings.AccountType, out session);

                    if (result == ProtocolHandler.LoginResult.Success && Settings.SessionCaching != CacheType.None)
                    {
                        SessionCache.Store(Settings.Login.ToLower(), session);
                    }
                }
            }

            if (result == ProtocolHandler.LoginResult.Success)
            {
                Settings.Username = session.PlayerName;

                if (Settings.ConsoleTitle != "")
                {
                    Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                }

                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.setPlayerIconAsync(Settings.Username);
                }

                if (Settings.DebugMessages)
                {
                    Translations.WriteLine("debug.session_id", session.ID);
                }

                //ProtocolHandler.RealmsListWorlds(Settings.Username, PlayerID, sessionID); //TODO REMOVE

                if (Settings.ServerIP == "")
                {
                    Translations.Write("mcc.ip");
                    Settings.SetServerIP(Console.ReadLine());
                }

                //Get server version
                int       protocolversion = 0;
                ForgeInfo forgeInfo       = null;

                if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
                {
                    protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);

                    if (protocolversion != 0)
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.use_version", Settings.ServerVersion, protocolversion));
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted(Translations.Get("mcc.unknown_version", Settings.ServerVersion));
                    }

                    if (useMcVersionOnce)
                    {
                        useMcVersionOnce       = false;
                        Settings.ServerVersion = "";
                    }
                }

                //Retrieve server info if version is not manually set OR if need to retrieve Forge information
                if (protocolversion == 0 || Settings.ServerAutodetectForge || (Settings.ServerForceForge && !ProtocolHandler.ProtocolMayForceForge(protocolversion)))
                {
                    if (protocolversion != 0)
                    {
                        Translations.WriteLine("mcc.forge");
                    }
                    else
                    {
                        Translations.WriteLine("mcc.retrieve");
                    }
                    if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion, ref forgeInfo))
                    {
                        HandleFailure(Translations.Get("error.ping"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                //Force-enable Forge support?
                if (Settings.ServerForceForge && forgeInfo == null)
                {
                    if (ProtocolHandler.ProtocolMayForceForge(protocolversion))
                    {
                        Translations.WriteLine("mcc.forgeforce");
                        forgeInfo = ProtocolHandler.ProtocolForceForge(protocolversion);
                    }
                    else
                    {
                        HandleFailure(Translations.Get("error.forgeforce"), true, ChatBots.AutoRelog.DisconnectReason.ConnectionLost);
                        return;
                    }
                }

                //Proceed to server login
                if (protocolversion != 0)
                {
                    try
                    {
                        //Start the main TCP client
                        if (Settings.SingleCommand != "")
                        {
                            client = new McClient(session.PlayerName, session.PlayerID, session.ID, Settings.ServerIP, Settings.ServerPort, protocolversion, forgeInfo, Settings.SingleCommand);
                        }
                        else
                        {
                            client = new McClient(session.PlayerName, session.PlayerID, session.ID, protocolversion, forgeInfo, Settings.ServerIP, Settings.ServerPort);
                        }

                        //Update console title
                        if (Settings.ConsoleTitle != "")
                        {
                            Console.Title = Settings.ExpandVars(Settings.ConsoleTitle);
                        }
                    }
                    catch (NotSupportedException) { HandleFailure(Translations.Get("error.unsupported"), true); }
                }
                else
                {
                    HandleFailure(Translations.Get("error.determine"), true);
                }
            }
            else
            {
                string failureMessage = Translations.Get("error.login");
                string failureReason  = "";
                switch (result)
                {
                case ProtocolHandler.LoginResult.AccountMigrated: failureReason = "error.login.migrated"; break;

                case ProtocolHandler.LoginResult.ServiceUnavailable: failureReason = "error.login.server"; break;

                case ProtocolHandler.LoginResult.WrongPassword: failureReason = "error.login.blocked"; break;

                case ProtocolHandler.LoginResult.InvalidResponse: failureReason = "error.login.response"; break;

                case ProtocolHandler.LoginResult.NotPremium: failureReason = "error.login.premium"; break;

                case ProtocolHandler.LoginResult.OtherError: failureReason = "error.login.network"; break;

                case ProtocolHandler.LoginResult.SSLError: failureReason = "error.login.ssl"; break;

                case ProtocolHandler.LoginResult.UserCancel: failureReason = "error.login.cancel"; break;

                default: failureReason = "error.login.unknown"; break;
                }
                failureMessage += Translations.Get(failureReason);

                if (result == ProtocolHandler.LoginResult.SSLError && isUsingMono)
                {
                    Translations.WriteLineFormatted("error.login.ssl_help");
                    return;
                }
                HandleFailure(failureMessage, false, ChatBot.DisconnectReason.LoginRejected);
            }
        }
 /// <summary>
 /// Translate the key and write a Minecraft-Like formatted string to the standard output, using §c color codes
 /// See minecraft.gamepedia.com/Classic_server_protocol#Color_Codes for more info
 /// </summary>
 /// <param name="key">Translation key</param>
 /// <param name="acceptnewlines">If false, space are printed instead of newlines</param>
 /// <param name="displayTimestamp">
 /// If false, no timestamp is prepended.
 /// If true, "hh-mm-ss" timestamp will be prepended.
 /// If unspecified, value is retrieved from EnableTimestamps.
 /// </param>
 public static void WriteLineFormatted(string key, bool acceptnewlines = true, bool?displayTimestamp = null)
 {
     ConsoleIO.WriteLineFormatted(Get(key), acceptnewlines, displayTimestamp);
 }
 /// <summary>
 /// Translate the key and write the result with a prefixed log line. Prefix is set in LogPrefix.
 /// </summary>
 /// <param name="key">Translation key</param>
 /// <param name="acceptnewlines">Allow line breaks</param>
 public static void WriteLogLine(string key, bool acceptnewlines = true)
 {
     ConsoleIO.WriteLogLine(Get(key), acceptnewlines);
 }
 /// <summary>
 /// Translate the key and write the result to the standard output, without newline character
 /// </summary>
 /// <param name="key">Translation key</param>
 public static void Write(string key)
 {
     ConsoleIO.Write(Get(key));
 }
示例#12
0
        /// <summary>
        /// Write a Minecraft-Like formatted string to the standard output, using §c color codes
        /// See minecraft.gamepedia.com/Classic_server_protocol#Color_Codes for more info
        /// </summary>
        /// <param name="str">String to write</param>
        /// <param name="acceptnewlines">If false, space are printed instead of newlines</param>
        /// <param name="displayTimestamps">
        /// If false, no timestamp is prepended.
        /// If true, "hh-mm-ss" timestamp will be prepended.
        /// If unspecified, value is retrieved from EnableTimestamps.
        /// </param>
        public static void WriteLineFormatted(string str, bool acceptnewlines = true, bool?displayTimestamp = null)
        {
            if (ChatFilter.chatFilter(str))
            {
                return;
            }
            if (!String.IsNullOrEmpty(str))
            {
                if (!acceptnewlines)
                {
                    str = str.Replace('\n', ' ');
                }
                if (displayTimestamp == null)
                {
                    displayTimestamp = EnableTimestamps;
                }
                if (displayTimestamp.Value)
                {
                    int hour = DateTime.Now.Hour, minute = DateTime.Now.Minute, second = DateTime.Now.Second;
                    ConsoleIO.Write(String.Format("{0}:{1}:{2} ", hour.ToString("00"), minute.ToString("00"), second.ToString("00")));
                }
                if (BasicIO)
                {
                    Console.WriteLine(str);
                    return;
                }
                string[] parts = str.Split(new char[] { '§' });
                if (parts[0].Length > 0)
                {
                    ConsoleIO.Write(parts[0]);
                }
                for (int i = 1; i < parts.Length; i++)
                {
                    if (parts[i].Length > 0)
                    {
                        switch (parts[i][0])
                        {
                        case '0': Console.ForegroundColor = ConsoleColor.Gray; break;     //Should be Black but Black is non-readable on a black background

                        case '1': Console.ForegroundColor = ConsoleColor.DarkBlue; break;

                        case '2': Console.ForegroundColor = ConsoleColor.DarkGreen; break;

                        case '3': Console.ForegroundColor = ConsoleColor.DarkCyan; break;

                        case '4': Console.ForegroundColor = ConsoleColor.DarkRed; break;

                        case '5': Console.ForegroundColor = ConsoleColor.DarkMagenta; break;

                        case '6': Console.ForegroundColor = ConsoleColor.DarkYellow; break;

                        case '7': Console.ForegroundColor = ConsoleColor.Gray; break;

                        case '8': Console.ForegroundColor = ConsoleColor.DarkGray; break;

                        case '9': Console.ForegroundColor = ConsoleColor.Blue; break;

                        case 'a': Console.ForegroundColor = ConsoleColor.Green; break;

                        case 'b': Console.ForegroundColor = ConsoleColor.Cyan; break;

                        case 'c': Console.ForegroundColor = ConsoleColor.Red; break;

                        case 'd': Console.ForegroundColor = ConsoleColor.Magenta; break;

                        case 'e': Console.ForegroundColor = ConsoleColor.Yellow; break;

                        case 'f': Console.ForegroundColor = ConsoleColor.White; break;

                        case 'r': Console.ForegroundColor = ConsoleColor.Gray; break;
                        }

                        if (parts[i].Length > 1)
                        {
                            ConsoleIO.Write(parts[i].Substring(1, parts[i].Length - 1));
                        }
                    }
                }
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            ConsoleIO.Write('\n');
        }
示例#13
0
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine("Minecraft Console Client v{0} - for MC {1} to {2} - Github.com/MCCTeam", Version, MCLowestVersion, MCHighestVersion);

            //Build information to facilitate processing of bug reports
            if (BuildInfo != null)
            {
                ConsoleIO.WriteLineFormatted("§8" + BuildInfo);
            }

            //Debug input ?
            if (args.Length == 1 && args[0] == "--keyboard-debug")
            {
                ConsoleIO.WriteLine("Keyboard debug mode: Press any key to display info");
                ConsoleIO.DebugReadInput();
            }

            //Setup ConsoleIO
            ConsoleIO.LogPrefix = "§8[MCC] ";
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO" || args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
            {
                if (args.Length >= 1 && args[args.Length - 1] == "BasicIO-NoColor")
                {
                    ConsoleIO.BasicIO_NoColor = true;
                }
                ConsoleIO.BasicIO = true;
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Take advantage of Windows 10 / Mac / Linux UTF-8 console
            if (isUsingMono || WindowsVersion.WinMajorVersion >= 10)
            {
                Console.OutputEncoding = Console.InputEncoding = Encoding.UTF8;
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadFile(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadFile("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Load external translation file. Should be called AFTER settings loaded
            Translations.LoadExternalTranslationFile(Settings.Language);

            //Other command-line arguments
            if (args.Length >= 1)
            {
                if (args.Contains("--help"))
                {
                    Console.WriteLine("Command-Line Help:");
                    Console.WriteLine("MinecraftClient.exe <username> <password> <server>");
                    Console.WriteLine("MinecraftClient.exe <username> <password> <server> \"/mycommand\"");
                    Console.WriteLine("MinecraftClient.exe --setting=value [--other settings]");
                    Console.WriteLine("MinecraftClient.exe --section.setting=value [--other settings]");
                    Console.WriteLine("MinecraftClient.exe <settings-file.ini> [--other settings]");
                    return;
                }

                try
                {
                    Settings.LoadArguments(args);
                }
                catch (ArgumentException e)
                {
                    Settings.interactiveMode = false;
                    HandleFailure(e.Message);
                    return;
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.ExpandVars(Settings.ConsoleTitle);
            }

            //Test line to troubleshoot invisible colors
            if (Settings.DebugMessages)
            {
                ConsoleIO.WriteLineFormatted(Translations.Get("debug.color_test", "[0123456789ABCDEF]: [§00§11§22§33§44§55§66§77§88§99§aA§bB§cC§dD§eE§fF§r]"));
            }

            //Load cached sessions from disk if necessary
            if (Settings.SessionCaching == CacheType.Disk)
            {
                bool cacheLoaded = SessionCache.InitializeDiskCache();
                if (Settings.DebugMessages)
                {
                    Translations.WriteLineFormatted(cacheLoaded ? "debug.session_cache_ok" : "debug.session_cache_fail");
                }
            }

            //Asking the user to type in missing data such as Username and Password
            bool useBrowser = Settings.AccountType == ProtocolHandler.AccountType.Microsoft && Settings.LoginMethod == "browser";

            if (Settings.Login == "" && !useBrowser)
            {
                Console.Write(ConsoleIO.BasicIO ? Translations.Get("mcc.login_basic_io") + "\n" : Translations.Get("mcc.login"));
                Settings.Login = Console.ReadLine();
            }
            if (Settings.Password == "" &&
                (Settings.SessionCaching == CacheType.None || !SessionCache.Contains(Settings.Login.ToLower())) &&
                !useBrowser)
            {
                RequestPassword();
            }

            // Setup exit cleaning code
            ExitCleanUp.Add(delegate()
            {
                // Do NOT use Program.Exit() as creating new Thread cause program to freeze
                if (client != null)
                {
                    client.Disconnect(); ConsoleIO.Reset();
                }
                if (offlinePrompt != null)
                {
                    offlinePrompt.Abort(); offlinePrompt = null; ConsoleIO.Reset();
                }
                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.revertToMCCIcon();
                }
            });


            startupargs = args;
            InitializeClient();
        }
示例#14
0
        /// <summary>
        /// The main entry point of Minecraft Console Client
        /// </summary>

        static void Main(string[] args)
        {
            Console.WriteLine("Console Client for MC 1.4.6 to 1.8.1 - v" + Version + " - By ORelio & Contributors");

            //Basic Input/Output ?
            if (args.Length >= 1 && args[args.Length - 1] == "BasicIO")
            {
                ConsoleIO.basicIO      = true;
                Console.OutputEncoding = Console.InputEncoding = Encoding.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
                args = args.Where(o => !Object.ReferenceEquals(o, args[args.Length - 1])).ToArray();
            }

            //Process ini configuration file
            if (args.Length >= 1 && System.IO.File.Exists(args[0]) && System.IO.Path.GetExtension(args[0]).ToLower() == ".ini")
            {
                Settings.LoadSettings(args[0]);

                //remove ini configuration file from arguments array
                List <string> args_tmp = args.ToList <string>();
                args_tmp.RemoveAt(0);
                args = args_tmp.ToArray();
            }
            else if (System.IO.File.Exists("MinecraftClient.ini"))
            {
                Settings.LoadSettings("MinecraftClient.ini");
            }
            else
            {
                Settings.WriteDefaultSettings("MinecraftClient.ini");
            }

            //Other command-line arguments
            if (args.Length >= 1)
            {
                Settings.Login = args[0];
                if (args.Length >= 2)
                {
                    Settings.Password = args[1];
                    if (args.Length >= 3)
                    {
                        Settings.setServerIP(args[2]);

                        //Single command?
                        if (args.Length >= 4)
                        {
                            Settings.SingleCommand = args[3];
                        }
                    }
                }
            }

            if (Settings.ConsoleTitle != "")
            {
                Settings.Username = "******";
                Console.Title     = Settings.expandVars(Settings.ConsoleTitle);
            }

            //Asking the user to type in missing data such as Username and Password

            if (Settings.Login == "")
            {
                Console.Write(ConsoleIO.basicIO ? "Please type the username of your choice.\n" : "Username : "******"")
            {
                Console.Write(ConsoleIO.basicIO ? "Please type the password for " + Settings.Login + ".\n" : "Password : "******"")
                {
                    Settings.Password = "******";
                }
                if (!ConsoleIO.basicIO)
                {
                    //Hide password length
                    Console.CursorTop--; Console.Write("Password : <******>");
                    for (int i = 19; i < Console.BufferWidth; i++)
                    {
                        Console.Write(' ');
                    }
                }
            }

            startupargs = args;
            InitializeClient();
        }
示例#15
0
        /// <summary>
        /// Start a new Client
        /// </summary>

        private static void InitializeClient()
        {
            ProtocolHandler.LoginResult result;
            Settings.Username = Settings.Login;
            string sessionID = "";
            string UUID      = "";

            if (Settings.Password == "-")
            {
                ConsoleIO.WriteLineFormatted("§8You chose to run in offline mode.");
                result    = ProtocolHandler.LoginResult.Success;
                sessionID = "0";
            }
            else
            {
                Console.WriteLine("Connecting to Minecraft.net...");
                result = ProtocolHandler.GetLogin(ref Settings.Username, Settings.Password, ref sessionID, ref UUID);
            }

            if (result == ProtocolHandler.LoginResult.Success)
            {
                if (Settings.ConsoleTitle != "")
                {
                    Console.Title = Settings.expandVars(Settings.ConsoleTitle);
                }

                if (Settings.playerHeadAsIcon)
                {
                    ConsoleIcon.setPlayerIconAsync(Settings.Username);
                }

                Console.WriteLine("Success. (session ID: " + sessionID + ')');

                if (Settings.ServerIP == "")
                {
                    Console.Write("Server IP : ");
                    Settings.setServerIP(Console.ReadLine());
                }

                //Get server version
                int protocolversion = 0;

                if (Settings.ServerVersion != "" && Settings.ServerVersion.ToLower() != "auto")
                {
                    protocolversion = Protocol.ProtocolHandler.MCVer2ProtocolVersion(Settings.ServerVersion);
                    if (protocolversion != 0)
                    {
                        ConsoleIO.WriteLineFormatted("§8Using Minecraft version " + Settings.ServerVersion + " (protocol v" + protocolversion + ')');
                    }
                    else
                    {
                        ConsoleIO.WriteLineFormatted("§8Unknown or not supported MC version '" + Settings.ServerVersion + "'.\nSwitching to autodetection mode.");
                    }
                }

                if (protocolversion == 0)
                {
                    Console.WriteLine("Retrieving Server Info...");
                    if (!ProtocolHandler.GetServerInfo(Settings.ServerIP, Settings.ServerPort, ref protocolversion))
                    {
                        Console.WriteLine("Failed to ping this IP.");
                        if (Settings.AutoRelog_Enabled)
                        {
                            ChatBots.AutoRelog bot = new ChatBots.AutoRelog(Settings.AutoRelog_Delay, Settings.AutoRelog_Retries);
                            if (!bot.OnDisconnect(ChatBot.DisconnectReason.ConnectionLost, "Failed to ping this IP."))
                            {
                                OfflineCommandPrompt();
                            }
                        }
                        else
                        {
                            OfflineCommandPrompt();
                        }
                        return;
                    }
                }

                if (protocolversion != 0)
                {
                    try
                    {
                        //Start the main TCP client
                        if (Settings.SingleCommand != "")
                        {
                            Client = new McTcpClient(Settings.Username, UUID, sessionID, Settings.ServerIP, Settings.ServerPort, protocolversion, Settings.SingleCommand);
                        }
                        else
                        {
                            Client = new McTcpClient(Settings.Username, UUID, sessionID, protocolversion, Settings.ServerIP, Settings.ServerPort);
                        }
                    }
                    catch (NotSupportedException)
                    {
                        Console.WriteLine("Cannot connect to the server : This version is not supported !");
                        OfflineCommandPrompt();
                    }
                }
                else
                {
                    Console.WriteLine("Failed to determine server version.");
                    OfflineCommandPrompt();
                }
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write("Connection failed : ");
                switch (result)
                {
                case ProtocolHandler.LoginResult.AccountMigrated: Console.WriteLine("Account migrated, use e-mail as username."); break;

                case ProtocolHandler.LoginResult.ServiceUnavailable: Console.WriteLine("Login servers are unavailable. Please try again later."); break;

                case ProtocolHandler.LoginResult.WrongPassword: Console.WriteLine("Incorrect password."); break;

                case ProtocolHandler.LoginResult.NotPremium: Console.WriteLine("User not premium."); break;

                case ProtocolHandler.LoginResult.OtherError: Console.WriteLine("Network error."); break;

                case ProtocolHandler.LoginResult.SSLError: Console.WriteLine("SSL Error.");
                    if (isUsingMono)
                    {
                        ConsoleIO.WriteLineFormatted("§8It appears that you are using Mono to run this program."
                                                     + '\n' + "The first time, you have to import HTTPS certificates using:"
                                                     + '\n' + "mozroots --import --ask-remove");
                        return;
                    }
                    break;
                }
                while (Console.KeyAvailable)
                {
                    Console.ReadKey(false);
                }
                if (Settings.SingleCommand == "")
                {
                    OfflineCommandPrompt();
                }
            }
        }