### Install Minecraft Version Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Installs a specified Minecraft version into the provided Minecraft directory. The library checks for a local JSON file first and attempts to download it from Mojang servers if unavailable. This function ensures the installation is correct and should be called before launching. ```python minecraft_launcher_lib.install.install_minecraft_version("1.17", minecraft_directory) ``` -------------------------------- ### Get Available Minecraft Versions Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Fetches a list of all available Minecraft versions for the specified directory. Each version object includes an 'id' and 'type' (e.g., 'release', 'snapshot'). This information is crucial for selecting which version to install or launch. ```python [ { "id": "some_id", "type": "release" }, { "id": "some_other_id", "type": "snapshot" } ] ``` -------------------------------- ### Python PyQt Installation Example Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/examples/PyQtInstallation A basic example demonstrating the shebang line for a Python script intended to be run with Python 3. This is often the first line in scripts utilizing libraries like PyQt. ```python #!/usr/bin/env python3 ``` -------------------------------- ### Python: Install Minecraft Version with subprocess Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/troubleshooting Ensures all necessary components for a Minecraft version are installed before launching. It's recommended to call this function before starting Minecraft, even if using an installer like Optifine. This example demonstrates using Python's `subprocess` module, which is preferred over `os.system` for better control and security when executing shell commands. ```Python import subprocess def install_minecraft_version(version_id): command = ["python", "-m", "minecraft_launcher_lib.install", version_id] try: subprocess.run(command, check=True) print(f"Successfully installed Minecraft version {version_id}") except subprocess.CalledProcessError as e: print(f"Error installing Minecraft version {version_id}: {e}") # Example usage: # install_minecraft_version("1.18.2") ``` -------------------------------- ### Install and Launch Minecraft with Microsoft Authentication (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/SimpleLaunch.rst This Python script demonstrates the process of installing the latest Minecraft version, authenticating using a Microsoft account, and then launching the game. It requires the 'minecraft-launcher-lib' library and utilizes subprocess for execution. The script prompts the user to log in via a browser and input the redirected URL to obtain authentication details. ```python #!/usr/bin/env python3 # This example shows how to simple install and launch the latest version of Minecraft. import minecraft_launcher_lib import subprocess import sys # Set the data for your Azure Application here. For more information look at the documentation. CLIENT_ID = "YOUR CLIENT ID" REDIRECT_URL = "YOUR REDIRECT URL" # Get latest version latest_version = minecraft_launcher_lib.utils.get_latest_version()["release"] # Get Minecraft directory minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() # Make sure, the latest version of Minecraft is installed minecraft_launcher_lib.install.install_minecraft_version(latest_version, minecraft_directory) # Login login_url, state, code_verifier = minecraft_launcher_lib.microsoft_account.get_secure_login_data(CLIENT_ID, REDIRECT_URL) print(f"Please open {login_url} in your browser and copy the url you are redirected into the prompt below.") code_url = input() # Get the code from the url try: auth_code = minecraft_launcher_lib.microsoft_account.parse_auth_code_url(code_url, state) except AssertionError: print("States do not match!") sys.exit(1) except KeyError: print("Url not valid") sys.exit(1) # Get the login data login_data = minecraft_launcher_lib.microsoft_account.complete_login(CLIENT_ID, None, REDIRECT_URL, auth_code, code_verifier) # Get Minecraft command options = { "username": login_data["name"], "uuid": login_data["id"], "token": login_data["access_token"] } minecraft_command = minecraft_launcher_lib.command.get_minecraft_command(latest_version, minecraft_directory, options) # Start Minecraft subprocess.run(minecraft_command, cwd=minecraft_directory) ``` -------------------------------- ### Generate Test Minecraft Launch Options Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Generates a minimal dictionary of options required to launch Minecraft, suitable for testing purposes. This includes placeholder values for username, UUID, and access token. ```python options = minecraft_launcher_lib.utils.generate_test_options() ``` -------------------------------- ### Install Module Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/index Handles the installation of Minecraft versions. ```APIDOC ## POST /install/install_minecraft_version ### Description Installs a specified Minecraft version. ### Method POST ### Endpoint /install/install_minecraft_version ### Parameters #### Request Body - **version** (string) - Required - The version of Minecraft to install. ### Request Example ```json { "version": "1.20.1" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the installation. #### Response Example ```json { "status": "Installation successful." } ``` ``` -------------------------------- ### Python: Track Minecraft Installation Progress with Callbacks Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/get_installation_progress.rst This Python snippet demonstrates how to use callbacks to monitor the installation progress of a Minecraft version. It defines functions to set the installation status, report current progress, and update the maximum progress value. These callback functions are passed to the `install_minecraft_version` function. ```python import minecraft_launcher_lib current_max = 0 def set_status(status: str): print(status) def set_progress(progress: int): if current_max != 0: print(f"{progress}/{current_max}") def set_max(new_max: int): global current_max current_max = new_max minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() callback = { "setStatus": set_status, "setProgress": set_progress, "setMax": set_max } minecraft_launcher_lib.install.install_minecraft_version("1.17", minecraft_directory, callback=callback) ``` -------------------------------- ### PyQt GUI for Minecraft Installation with Progress Bar Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/PyQtInstallation.rst This Python script demonstrates how to build a PyQt graphical user interface for installing Minecraft. It utilizes the `minecraft-launcher-lib` to handle the installation process, including version fetching, downloading, and progress reporting. The GUI allows users to select a Minecraft version, specify an installation directory, and initiates the installation with a progress bar. It supports both single-threaded (which freezes the GUI) and multi-threaded installation (which keeps the GUI responsive). ```python #!/usr/bin/env python3 # This example shows how to install Minecraft with a ProgressBar in PyQt from PyQt6.QtWidgets import QApplication, QWidget, QLabel, QComboBox, QLineEdit, QPushButton, QProgressBar, QFileDialog, QFormLayout, QHBoxLayout, QVBoxLayout from PyQt6.QtCore import QThread, pyqtSignal import minecraft_launcher_lib import sys class InstallThread(QThread): progress_max = pyqtSignal("int") progress = pyqtSignal("int") text = pyqtSignal("QString") def __init__(self) -> None: QThread.__init__(self) self._callback_dict = { "setStatus": lambda text: self.text.emit(text), "setMax": lambda max_progress: self.progress_max.emit(max_progress), "setProgress": lambda progress: self.progress.emit(progress), } def set_data(self, version: str, directory) -> None: self._version = version self._directory = directory def run(self) -> None: minecraft_launcher_lib.install.install_minecraft_version(self._version, self._directory, callback=self._callback_dict) class Window(QWidget): def __init__(self) -> None: super().__init__() self._install_thread = InstallThread() self._version_combo_box = QComboBox() self._path_edit = QLineEdit() self._path_browse_button = QPushButton("Browse") self._progress_bar = QProgressBar() self._install_single_thread_button = QPushButton("Install Single Thread") self._install_multi_thread_button = QPushButton("Install Multi Thread") for i in minecraft_launcher_lib.utils.get_version_list(): self._version_combo_box.addItem(i["id"]) self._path_edit.setText(minecraft_launcher_lib.utils.get_minecraft_directory()) self._progress_bar.setTextVisible(True) self._install_thread.progress_max.connect(lambda maximum: self._progress_bar.setMaximum(maximum)) self._install_thread.progress.connect(lambda value: self._progress_bar.setValue(value)) self._install_thread.text.connect(lambda text: self._progress_bar.setFormat(text)) self._install_thread.finished.connect(self._install_thread_finished) self._path_browse_button.clicked.connect(self._path_browse_button_clicked) self._install_single_thread_button.clicked.connect(self._install_minecraft_single_thread) self._install_multi_thread_button.clicked.connect(self._install_minecraft_multi_thread) path_layout = QHBoxLayout() path_layout.addWidget(self._path_edit) path_layout.addWidget(self._path_browse_button) form_layout = QFormLayout() form_layout.addRow(QLabel("Version:"), self._version_combo_box) form_layout.addRow(QLabel("Path:"), path_layout) button_layout = QHBoxLayout() button_layout.addWidget(self._install_single_thread_button) button_layout.addWidget(self._install_multi_thread_button) main_layout = QVBoxLayout() main_layout.addLayout(form_layout) main_layout.addWidget(self._progress_bar) main_layout.addLayout(button_layout) self.setLayout(main_layout) self.setWindowTitle("PyQtInstallation") def _install_thread_finished(self) -> None: # This function is called after the Multi Thread Installation has been finished self._install_single_thread_button.setEnabled(True) self._install_multi_thread_button.setEnabled(True) def _path_browse_button_clicked(self) -> None: path = QFileDialog.getExistingDirectory(self, directory=self._path_edit.text()) if path != "": self._path_edit.setText(path) def _install_minecraft_single_thread(self) -> None: # This function installs Minecraft in the same Thread as the GUI # This is much simpler than using a other Thread, but the GUI will freeze until the function is completed callback = { "setStatus": lambda text: self._progress_bar.setFormat(text), "setProgress": lambda value: self._progress_bar.setValue(value), "setMax": lambda maximum: self._progress_bar.setMaximum(maximum) } minecraft_launcher_lib.install.install_minecraft_version(self._version_combo_box.currentText(), self._path_edit.text(), callback=callback) def _install_minecraft_multi_thread(self) -> None: # This functions installs Minecraft on a other Thread than the GUI self._install_single_thread_button.setEnabled(False) self._install_multi_thread_button.setEnabled(False) self._install_thread.set_data(self._version_combo_box.currentText(), self._path_edit.text()) self._install_thread.start() if __name__ == "__main__": app = QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec()) ``` -------------------------------- ### Get Available Minecraft Versions - Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/tutorial/getting_started Fetches a list of all available Minecraft versions within the specified Minecraft directory. Each version entry includes an 'id' and 'type' (e.g., 'release', 'snapshot'). This information is crucial for selecting which version to install or launch. ```python # Get a list of all Minecraft versions available_versions = minecraft_launcher_lib.utils.get_available_versions(minecraft_directory) # Example output: # [ # { # "id": "some_id", # "type": "release" # }, # { # "id": "some_other_id", # "type": "snapshot" # } # ] ``` -------------------------------- ### Get Latest Minecraft Versions Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Retrieves the latest available release and snapshot versions of Minecraft. This is useful for always launching the most recent stable or development version. ```python latest_release = minecraft_launcher_lib.utils.get_latest_version()["release"] latest_snapshot = minecraft_launcher_lib.utils.get_latest_version()["snapshot"] ``` -------------------------------- ### Get Minecraft Launch Command Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Constructs the command-line arguments required to launch a specific Minecraft version with the given directory and options. The output is a list of strings compatible with Python's subprocess module. ```python minecraft_command = minecraft_launcher_lib.command.get_minecraft_command("1.17", minecraft_directory, options) ``` -------------------------------- ### Install from PyPI using pip Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/installation.rst Installs the minecraft-launcher-lib library using pip from the Python Package Index (PyPI). This is the recommended and most common installation method for general users. ```shell pip install -U minecraft-launcher-lib ``` -------------------------------- ### Install and Launch Mrpack Modpack - Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/Mrpack.rst This Python script utilizes the minecraft-launcher-lib to handle the installation of .mrpack files. It prompts the user for the .mrpack file path, Minecraft directory, and modpack installation directory. It also allows selection of optional files included in the modpack and provides an option to launch Minecraft after installation. ```python #!/usr/bin/env python3 # This example shows how use the mrpack module import minecraft_launcher_lib import subprocess import sys import os def ask_yes_no(text: str) -> bool: while True: answer = input(f"{text} [Y/N]: ").strip().upper() if answer == "Y": return True elif answer == "N": return False else: print("Invalid answer. Use Y or N.") def main() -> None: mrpack_path = input("Please enter the Path to your .mrpack File: ") if not os.path.isfile(mrpack_path): print(f"{mrpack_path} was not found", file=sys.stderr) sys.exit(1) try: mrpack_information = minecraft_launcher_lib.mrpack.get_mrpack_information(mrpack_path) except Exception: print(f"{mrpack_path} is not a valid .mrpack File") sys.exit(1) # Print some Information print("You have selected the following Pack:") print("Name: " + mrpack_information["name"]) print("Summary: " + mrpack_information["summary"]) print("Minecraft version: " + mrpack_information["minecraftVersion"]) if not ask_yes_no("Do you want to install this Pack?"): return # Ask the User for the Directories minecraft_directory = input("Please enter the Path to your Minecraft directory (leave empty for default): ") if minecraft_directory == "": minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() modpack_directory = input("Please enter the Path to the Directory you want to install the Modpack (leave empty for your Minecraft directory): ") if modpack_directory == "": modpack_directory = minecraft_directory # Adds the Optional Files mrpack_install_options: minecraft_launcher_lib.types.MrpackInstallOptions = {"optionalFiles": []} for i in mrpack_information["optionalFiles"]: if ask_yes_no(f"The Pack includes the Optional File {i}. Do you want to install it?"): mrpack_install_options["optionalFiles"].append(i) # Install print("Installing") minecraft_launcher_lib.mrpack.install_mrpack(mrpack_path, minecraft_directory, modpack_directory=modpack_directory, mrpack_install_options=mrpack_install_options, callback={"setStatus": print}) print("Finished") if not ask_yes_no("Do you want to start Minecraft?"): return # We skip the Login in this Example options = minecraft_launcher_lib.utils.generate_test_options() options["gameDirectory"] = modpack_directory command = minecraft_launcher_lib.command.get_minecraft_command(minecraft_launcher_lib.mrpack.get_mrpack_launch_version(mrpack_path), minecraft_directory, options) subprocess.run(command) if __name__ == "__main__": main() ``` -------------------------------- ### Install and Launch Modpack using Mrpack Module Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/examples/Mrpack This Python script showcases the usage of the `mrpack` module to install a Minecraft modpack from a .mrpack file. It handles user input for file paths, displays pack information, prompts for installation confirmation, and optionally launches the game. Dependencies include the `minecraft-launcher-lib` library and standard Python modules like `subprocess`, `sys`, and `os`. The script expects a valid path to a .mrpack file as input and may output installation status and game launch commands. ```python #!/usr/bin/env python3 # This example shows how use the mrpack module import minecraft_launcher_lib import subprocess import sys import os def ask_yes_no(text: str) -> bool: while True: answer = input(f"{text} [Y/N]: ").strip().upper() if answer == "Y": return True elif answer == "N": return False else: print("Invalid answer. Use Y or N.") def main() -> None: mrpack_path = input("Please enter the Path to your .mrpack File: ") if not os.path.isfile(mrpack_path): print(f"{mrpack_path} was not found", file=sys.stderr) sys.exit(1) try: mrpack_information = minecraft_launcher_lib.mrpack.get_mrpack_information(mrpack_path) except Exception: print(f"{mrpack_path} is not a valid .mrpack File") sys.exit(1) # Print some Information print("You have selected the following Pack:") print("Name: " + mrpack_information["name"]) print("Summary: " + mrpack_information["summary"]) print("Minecraft version: " + mrpack_information["minecraftVersion"]) if not ask_yes_no("Do you want to install this Pack?"): return # Ask the User for the Directories minecraft_directory = input("Please enter the Path to your Minecraft directory (leave empty for default): ") if minecraft_directory == "": minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() modpack_directory = input("Please enter the Path to the Directory you want to install the Modpack (leave empty for your Minecraft directory): ") if modpack_directory == "": modpack_directory = minecraft_directory # Adds the Optional Files mrpack_install_options: minecraft_launcher_lib.types.MrpackInstallOptions = {"optionalFiles": []} for i in mrpack_information["optionalFiles"]: if ask_yes_no(f"The Pack includes the Optional File {i}. Do you want to install it?"): mrpack_install_options["optionalFiles"].append(i) # Install print("Installing") minecraft_launcher_lib.mrpack.install_mrpack(mrpack_path, minecraft_directory, modpack_directory=modpack_directory, mrpack_install_options=mrpack_install_options, callback={"setStatus": print}) print("Finished") if not ask_yes_no("Do you want to start Minecraft?"): return # We skip the Login in this Example options = minecraft_launcher_lib.utils.generate_test_options() options["gameDirectory"] = modpack_directory command = minecraft_launcher_lib.command.get_minecraft_command(minecraft_launcher_lib.mrpack.get_mrpack_launch_version(mrpack_path), minecraft_directory, options) subprocess.run(command) if __name__ == "__main__": main() ``` -------------------------------- ### Get Minecraft Directory Path Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/tutorial/getting_started.rst Retrieves the default Minecraft directory path for the current system or allows specifying a custom path. This is a prerequisite for many library operations. ```python # Get the Minecraft Directory of your System minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() # Or use your own minecraft_directory = "path/to/your/minecraft/directory" ``` -------------------------------- ### Install and Launch Minecraft with Mod Loader (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/ModLoader.rst This Python script utilizes the minecraft-launcher-lib to allow users to select a mod loader, choose a Minecraft version, specify their Minecraft directory, and then install the mod loader. It concludes by offering to launch Minecraft with the newly installed mod loader. Dependencies include the 'minecraft-launcher-lib' and 'subprocess' modules. ```python #!/usr/bin/env python3 # This example shows how use the mod loader module import minecraft_launcher_lib import subprocess def choose(options: list[str]) -> int: for pos, text in enumerate(options): print(f"{pos + 1}: {text}") while True: try: answer = int(input(f"Select[1-{len(options)}]:")) - 1 if answer >= 0 and answer < len(options): return answer except ValueError: pass def ask_yes_no(text: str) -> bool: while True: answer = input(f"{text}[y/n]:").strip().upper() if answer == "Y": return True elif answer == "N": return False else: print("Invalid answer. Use y or n.") def main() -> None: id_list = minecraft_launcher_lib.mod_loader.list_mod_loader() name_list = [] for current_id in id_list: name_list.append(minecraft_launcher_lib.mod_loader.get_mod_loader(current_id).get_name()) print("Please select a mod loader:") loader = minecraft_launcher_lib.mod_loader.get_mod_loader(id_list[choose(name_list)]) version_list = loader.get_minecraft_versions(True) print() print("Please select the Minecraft version for which you want to install the mod loader.") vanilla_version = version_list[choose(version_list)] print() minecraft_directory = input("Enter the path to your Minecraft directory (leave blank for default):").strip() if minecraft_directory == "": minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() installed_version = loader.install(vanilla_version, minecraft_directory, callback={"setStatus": print}) print("Finished") if not ask_yes_no("Do you want to launch Minecraft?"): return command = minecraft_launcher_lib.command.get_minecraft_command(installed_version, minecraft_directory, minecraft_launcher_lib.utils.generate_test_options()) subprocess.run(command, cwd=minecraft_directory) if __name__ == "__main__": main() ``` -------------------------------- ### Python: Install and Launch Latest Minecraft Version Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/examples/SimpleLaunch This Python script demonstrates how to automatically install and launch the latest release of Minecraft using the minecraft-launcher-lib. It handles version checking, installation, Microsoft account authentication, and game command generation. Ensure you have the necessary dependencies installed and replace placeholder values for CLIENT_ID and REDIRECT_URL. ```python #!/usr/bin/env python3 # This example shows how to simple install and launch the latest version of Minecraft. import minecraft_launcher_lib import subprocess import sys # Set the data for your Azure Application here. For more information look at the documentation. CLIENT_ID = "YOUR CLIENT ID" REDIRECT_URL = "YOUR REDIRECT URL" # Get latest version latest_version = minecraft_launcher_lib.utils.get_latest_version()["release"] # Get Minecraft directory minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() # Make sure, the latest version of Minecraft is installed minecraft_launcher_lib.install.install_minecraft_version(latest_version, minecraft_directory) # Login login_url, state, code_verifier = minecraft_launcher_lib.microsoft_account.get_secure_login_data(CLIENT_ID, REDIRECT_URL) print(f"Please open {login_url} in your browser and copy the url you are redirected into the prompt below.") code_url = input() # Get the code from the url try: auth_code = minecraft_launcher_lib.microsoft_account.parse_auth_code_url(code_url, state) except AssertionError: print("States do not match!") sys.exit(1) except KeyError: print("Url not valid") sys.exit(1) # Get the login data login_data = minecraft_launcher_lib.microsoft_account.complete_login(CLIENT_ID, None, REDIRECT_URL, auth_code, code_verifier) # Get Minecraft command options = { "username": login_data["name"], "uuid": login_data["id"], "token": login_data["access_token"] } minecraft_command = minecraft_launcher_lib.command.get_minecraft_command(latest_version, minecraft_directory, options) # Start Minecraft subprocess.run(minecraft_command, cwd=minecraft_directory) ``` -------------------------------- ### Install from Source using pip Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/installation.rst Installs the minecraft-launcher-lib library directly from its source code repository. This method is useful for developers or users who need the latest unreleased changes, but should be used with caution. ```shell pip install -U git+https://codeberg.org/JakobDev/minecraft-launcher-lib.git ``` -------------------------------- ### Show Minecraft Installation Progress (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/InstallationProgress.rst This Python script illustrates how to display the progress of a Minecraft installation to the user. It utilizes a helper function `printProgressBar` for visual feedback in the console and integrates with the `minecraft_launcher_lib` library's installation process via a callback dictionary. The callback handles status updates, progress values, and maximum values for the progress bar. ```python #!/usr/bin/env python3 # This example shows how to show the progress of installation to the user. import minecraft_launcher_lib # Taken from https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd) # Print New Line on Complete if iteration == total: print() def maximum(max_value, value): max_value[0] = value def main(): # lambda doesn't allow setting vars, so we need this little hack max_value = [0] callback = { "setStatus": lambda text: print(text), "setProgress": lambda value: printProgressBar(value, max_value[0]), "setMax": lambda value: maximum(max_value, value) } version = minecraft_launcher_lib.utils.get_latest_version()["release"] directory = minecraft_launcher_lib.utils.get_minecraft_directory() minecraft_launcher_lib.install.install_minecraft_version(version, directory, callback=callback) if __name__ == "__main__": main() ``` -------------------------------- ### Get Java Installation Information (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/java_utils Retrieves detailed information about a specific Java installation by executing the Java executable. This function takes the path to the Java installation directory as input and returns a dictionary containing details like the name, version, and path of the Java executable. It may be a security risk as it executes the Java binary. Raises ValueError for invalid paths. ```python import minecraft_launcher_lib from pathlib import Path java_path_str = "" java_path = Path(java_path_str) information = minecraft_launcher_lib.java_utils.get_java_information(java_path) print("Name: " + information["name"]) print("Version: " + information["version"]) print("Java path: " + information["java_path"]) ``` -------------------------------- ### Install Sphinx and Read the Docs Theme Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/develop/build_and_edit_documentation.rst Installs the necessary packages, Sphinx and the Read the Docs theme, required for building the documentation. This command uses pip for package management. ```shell pip install sphinx sphinx-rtd-theme ``` -------------------------------- ### Show Minecraft Installation Progress using Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/examples/InstallationProgress This Python script utilizes the minecraft-launcher-lib library to download and install a specific Minecraft version. It includes a custom progress bar function to provide visual feedback on the installation's status and progress, updating the user on the current operation and percentage complete. The script requires the minecraft-launcher-lib to be installed. ```python #!/usr/bin/env python3 # This example shows how to show the progress of installation to the user. import minecraft_launcher_lib # Taken from https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"): ''' Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) ''' percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd) # Print New Line on Complete if iteration == total: print() def maximum(max_value, value): max_value[0] = value def main(): # lambda doesn't allow setting vars, so we need this little hack max_value = [0] callback = { "setStatus": lambda text: print(text), "setProgress": lambda value: printProgressBar(value, max_value[0]), "setMax": lambda value: maximum(max_value, value) } version = minecraft_launcher_lib.utils.get_latest_version()["release"] directory = minecraft_launcher_lib.utils.get_minecraft_directory() minecraft_launcher_lib.install.install_minecraft_version(version, directory, callback=callback) if __name__ == "__main__": main() ``` -------------------------------- ### Install Minecraft Version with Callback (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/install Installs a specific Minecraft version to a given directory, with options to monitor progress via a callback dictionary. This function also handles verification and repair of existing installations, downloading only necessary files. It requires the minecraft-launcher-lib library and expects the version string and Minecraft directory path as input. ```python import minecraft_launcher_lib import minecraft_launcher_lib.utils minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() callback = { "setStatus": lambda status: print(f"Status: {status}"), "setProgress": lambda progress: print(f"Progress: {progress}"), "setMax": lambda max_progress: print(f"Max Progress: {max_progress}") } try: minecraft_launcher_lib.install.install_minecraft_version("1.21", minecraft_directory, callback) print("Minecraft 1.21 installed successfully.") except minecraft_launcher_lib.exceptions.VersionNotFound: print("Error: Minecraft version not found.") except minecraft_launcher_lib.exceptions.FileOutsideMinecraftDirectory: print("Error: A file operation attempted to go outside the Minecraft directory.") except Exception as e: print(f"An unexpected error occurred: {e}") ``` -------------------------------- ### Mod Loader Installation Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/mod_loader This section describes how to install a mod loader for a specified Minecraft version. It includes details on necessary parameters such as Minecraft version, directory, and optional parameters like loader version, callback, and Java executable path. It also outlines potential exceptions that might be raised during the installation process. ```APIDOC ## Install Mod Loader ### Description Installs a specified mod loader for a given Minecraft version. ### Method This is a conceptual representation of a function call, not a direct HTTP method. ### Endpoint N/A (Python function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Represented by function arguments) - **minecraft_version** (str) - Required - The vanilla Minecraft version for which to install the mod loader. If not installed, minecraft-launcher-lib will also install the vanilla version. - **minecraft_directory** (str | PathLike) - Required - The path to your Minecraft directory. - **loader_version** (str | None) - Optional - The version of the mod loader as returned by `get_loader_versions()`. If not set, the latest one will be used. - **callback** (CallbackDict | None) - Optional - See Get Installation Progress. - **java** (str | PathLike | None) - Optional - If set, use this Java executable to execute programs during the installation. ### Request Example ```python import minecraft_launcher_lib minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() mod_loader = minecraft_launcher_lib.mod_loader.get_mod_loader("fabric") mod_loader.install("1.19.4", minecraft_directory, loader_version="0.14.21") ``` ### Response #### Success Response (200) Returns the installed version string. - **installed_version** (str) - The version of the installed mod loader. #### Response Example ```json { "installed_version": "0.14.21" } ``` ### Error Handling - **VersionNotFound**: An invalid minecraft version was passed. - **UnsupportedVersion**: The given Minecraft version is not supported by the mod loader. - **CalledProcessError**: The execution of a program failed. ``` -------------------------------- ### Basic Minecraft Version Installation (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/install Installs a specified Minecraft version to the designated directory without progress monitoring. This function is essential for setting up a new Minecraft installation or ensuring an existing one is complete and correct by downloading only missing or corrupted files. It requires the minecraft-launcher-lib library. ```python import minecraft_launcher_lib import minecraft_launcher_lib.utils minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() minecraft_launcher_lib.install.install_minecraft_version("1.21", minecraft_directory) ``` -------------------------------- ### Launch Minecraft with PyQt and Display Output Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/examples/PyQtLauncherWithOutput This Python script uses PyQt6 to build a graphical launcher for Minecraft. It handles user login, version selection, and initiates the Minecraft process. The output from the Minecraft game process is captured and displayed in a QPlainTextEdit widget, providing real-time feedback. Dependencies include PyQt6 and minecraft-launcher-lib. Input requires a username, password, and selected Minecraft version. Output is the game's console log. ```python #!/usr/bin/env python3 # This example shows a simple launcher with PyQt that shows the output of Minecraft in a text filed from PyQt6.QtWidgets import QApplication, QWidget, QPlainTextEdit, QLabel, QLineEdit, QPushButton, QComboBox, QMessageBox, QHBoxLayout, QVBoxLayout from PyQt6.QtCore import QProcess import minecraft_launcher_lib import sys class GameOutputWidget(QPlainTextEdit): def __init__(self, launch_button): super().__init__() self.setReadOnly(True) self.launch_button = launch_button # Disable line wrap self.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap) def display_output(self): # This function displays the output of Minecraft in the text field cursor = self.textCursor() cursor.movePosition(cursor.MoveOperation.End) cursor.insertText(bytes(self.process.readAll()).decode()) cursor.movePosition(cursor.MoveOperation.End) self.ensureCursorVisible() def execute_command(self, command): # QProcess.start takes as first argument the program and as second the list of arguments # So we need the filter the program from the command arguments = command[1:] # Deactivate the launch button self.launch_button.setEnabled(False) # Clear the text field self.setPlainText("") self.process = QProcess(self) # Activate the launch button when Minecraft is closed self.process.finished.connect(lambda: self.launch_button.setEnabled(True)) # Connect the function to display the output self.process.readyRead.connect(self.dataReady) # Start Minecraft self.process.start("java", arguments) class MainWindow(QWidget): def __init__(self): super().__init__() self.username_edit = QLineEdit() self.password_edit = QLineEdit() self.version_select = QComboBox() launch_button = QPushButton("Launch") self.output_widget = GameOutputWidget(launch_button) # Set the password field to display * self.password_edit.setEchoMode(QLineEdit.EchoMode.Password) launch_button.clicked.connect(self.launch_minecraft) # Add all versions to the Version ComboBox self.minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() for i in minecraft_launcher_lib.utils.get_available_versions(self.minecraft_directory): # Only add release versions if i["type"] == "release": self.version_select.addItem(i["id"]) # Create the layouts bottom_layout = QHBoxLayout() bottom_layout.addWidget(QLabel("Username:")) bottom_layout.addWidget(self.username_edit) bottom_layout.addWidget(QLabel("Password:")) bottom_layout.addWidget(self.password_edit) bottom_layout.addWidget(QLabel("Version:")) bottom_layout.addWidget(self.version_select) bottom_layout.addWidget(launch_button) main_layout = QVBoxLayout() main_layout.addWidget(self.output_widget) main_layout.addLayout(bottom_layout) self.setLayout(main_layout) self.setGeometry(0, 0, 800, 600) self.setWindowTitle("PyQt Launcher with Output") def launch_minecraft(self): # Get the selected version version = self.version_select.currentText() # Make sure the version is installed minecraft_launcher_lib.install.install_minecraft_version(version, self.minecraft_directory) # Login login_data = minecraft_launcher_lib.account.login_user(self.username_edit.text(), self.password_edit.text()) # Check if the login is correct if "errorMessage" in login_data: message_box = QMessageBox() message_box.setWindowTitle("Invalid credentials") message_box.setText("Invalid username or password") message_box.setStandardButtons(QMessageBox.StandardButtons.Ok) message_box.exec() return options = { "username": login_data["selectedProfile"]["name"], "uuid": login_data["selectedProfile"]["id"], "token": login_data["accessToken"] } # Get the command command = minecraft_launcher_lib.command.get_minecraft_command(version, self.minecraft_directory, options) # Call the function from the self.output_widget.execute_command(command) def main(): app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec()) if __name__ == "__main__": main() ``` -------------------------------- ### Get Latest Fabric Installer Version Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/fabric Fetches the latest installer version for the Fabric modloader. This information can be used to download the most recent installer. ```python import minecraft_launcher_lib print("Latest installer version: " + minecraft_launcher_lib.fabric.get_latest_installer_version()) ``` -------------------------------- ### Get Latest Quilt Installer Version Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/quilt Fetches the latest version number for the Quilt modloader installer. The function returns a string representing the latest installer version. ```python import minecraft_launcher_lib print("Latest installer version: " + minecraft_launcher_lib.quilt.get_latest_installer_version()) ``` -------------------------------- ### Run Command and Execute PyQt Application Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/PyQtLauncherWithOutput.rst This snippet shows how to execute a command using an output widget and then run a PyQt application. It requires the PyQt5 library and sys module. The main function sets up the application and the main window, then starts the event loop. ```python self.output_widget.execute_command(command) def main(): app = QApplication(sys.argv) w = MainWindow() w.show() sys.exit(app.exec()) if __name__ == "__main__": main() ``` -------------------------------- ### Get Installed Minecraft Versions - Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/utils Lists all Minecraft versions that are currently installed on the user's system. It requires the path to the Minecraft directory as input. ```python import minecraft_launcher_lib minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() for version in minecraft_launcher_lib.utils.get_installed_versions(minecraft_directory): print(version["id"]) ``` -------------------------------- ### Convert Vanilla Profile to Minecraft Options Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/vanilla_launcher Converts a VanillaLauncherProfile object into a dictionary of Minecraft options, suitable for use with `get_minecraft_command()`. It requires a VanillaLauncherProfile as input and returns MinecraftOptions. Note that login data must be added separately before execution. ```python import minecraft_launcher_lib import subprocess minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() profiles = minecraft_launcher_lib.vanilla_launcher.load_vanilla_launcher_profiles(minecraft_directory) test_options = minecraft_launcher_lib.utils.generate_test_options() profile_options = minecraft_launcher_lib.vanilla_launcher.vanilla_launcher_profile_to_minecraft_options(profiles[0]) options = test_options | profile_options minecraft_version = minecraft_launcher_lib.vanilla_launcher.get_vanilla_launcher_profile_version(profiles[0]) command = minecraft_launcher_lib.command.get_minecraft_command(minecraft_version, minecraft_directory, options) subprocess.run(command, cwd=minecraft_directory) ``` -------------------------------- ### Prevent GUI Freeze with Threading in PyQt Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/PyQtInstallation.rst This Python code snippet shows how to prevent the GUI from freezing during an installation process by using a separate thread. It disables installation buttons, sets data for an installation thread, and then starts the thread. This approach ensures a responsive user interface. ```python # This is more complex than using the same Thread, but the GUI will not freeze self._install_single_thread_button.setEnabled(False) self._install_multi_thread_button.setEnabled(False) self._install_thread.set_data(self._version_combo_box.currentText(), self._path_edit.text()) self._install_thread.start() ``` -------------------------------- ### Get Installed JVM Runtimes - Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/runtime Retrieves a list of all JVM runtimes that are currently installed within a specified Minecraft directory. This helps in checking which runtimes are already available on the system. It requires the path to the Minecraft directory as input and returns a list of installed runtime identifiers. ```python import minecraft_launcher_lib from pathlib import Path minecraft_directory = minecraft_launcher_lib.utils.get_minecraft_directory() # Or specify your path for runtime in minecraft_launcher_lib.runtime.get_installed_jvm_runtimes(minecraft_directory): print(runtime) ``` -------------------------------- ### PyQt Microsoft Account Login with minecraft-launcher-lib Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/_sources/examples/PyQtLoginWindow.rst This Python script utilizes PyQt6 and the minecraft_launcher_lib to create a graphical login window for Microsoft accounts. It handles the OAuth 2.0 flow, including obtaining login URLs, parsing authorization codes, and completing the login process. The script also manages saving and refreshing authentication tokens, displaying user account information, and exiting upon successful login. Dependencies include PyQt6, PyQt6-WebEngine, and the minecraft_launcher_lib. ```python #!/usr/bin/env python3 # This example shows how to use the PyQt WebEngine for the Login # It needs the PyQt6 and PyQt6-WebEngine packages from PyQt6.QtWidgets import QApplication, QMessageBox from PyQt6.QtWebEngineWidgets import QWebEngineView from PyQt6.QtWebEngineCore import QWebEngineProfile from PyQt6.QtCore import QUrl, QLocale import minecraft_launcher_lib import json import sys import os CLIENT_ID = "YOUR CLIENT ID" REDIRECT_URL = "YOUR REDIRECT URL" class LoginWindow(QWebEngineView): def __init__(self): super().__init__() self.setWindowTitle("Login Window Example") # Set the path where the refresh token is saved self.refresh_token_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), "refresh_token.json") # Login with refresh token, if it exists if os.path.isfile(self.refresh_token_file): with open(self.refresh_token_file, "r", encoding="utf-8") as f: refresh_token = json.load(f) # Do the login with refresh token try: account_informaton = minecraft_launcher_lib.microsoft_account.complete_refresh(CLIENT_ID, None, REDIRECT_URL, refresh_token) self.show_account_information(account_informaton) # Show the window if the refresh token is invalid except minecraft_launcher_lib.exceptions.InvalidRefreshToken: pass # Open the login url login_url, self.state, self.code_verifier = minecraft_launcher_lib.microsoft_account.get_secure_login_data(CLIENT_ID, REDIRECT_URL) self.load(QUrl(login_url)) # Connects a function that is called when the url changed self.urlChanged.connect(self.new_url) self.show() def new_url(self, url: QUrl): try: # Get the code from the url auth_code = minecraft_launcher_lib.microsoft_account.parse_auth_code_url(url.toString(), self.state) # Do the login account_information = minecraft_launcher_lib.microsoft_account.complete_login(CLIENT_ID, None, REDIRECT_URL, auth_code, self.code_verifier) # Show the login information self.show_account_information(account_information) except AssertionError: print("States do not match!") except KeyError: print("Url not valid") def show_account_information(self, information_dict): information_string = f'Username: {information_dict["name"]}
' information_string += f'UUID: {information_dict["id"]}
' information_string += f'Token: {information_dict["access_token"]}
' # Save the refresh token in a file with open(self.refresh_token_file, "w", encoding="utf-8") as f: json.dump(information_dict["refresh_token"], f, ensure_ascii=False, indent=4) message_box = QMessageBox() message_box.setWindowTitle("Account information") message_box.setText(information_string) message_box.setStandardButtons(QMessageBox.StandardButton.Ok) message_box.exec() # Exit the program sys.exit(0) if __name__ == "__main__": app = QApplication(sys.argv) # This line sets the language of the webpage to the system language QWebEngineProfile.defaultProfile().setHttpAcceptLanguage(QLocale.system().name().split("_")[0]) w = LoginWindow() sys.exit(app.exec()) ``` -------------------------------- ### Get Library Version - Python Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/utils Returns the currently installed version of the minecraft-launcher-lib. This is useful for checking compatibility or debugging. ```python import minecraft_launcher_lib print(f"You are using version {minecraft_launcher_lib.utils.get_library_version()} of minecraft-launcher-lib") ``` -------------------------------- ### Get Installed Version String (Python) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/modules/mod_loader Calculates and returns the specific version string under which the mod loader will be installed for a given vanilla Minecraft version and loader version. This is often used in conjunction with commands like `get_minecraft_command()`. ```python import minecraft_launcher_lib.mod_loader vanilla_version = "1.21" loader_version = "0.16.14" mod_loader = minecraft_launcher_lib.mod_loader.get_mod_loader("fabric") installed_version = mod_loader.get_installed_version(vanilla_version, loader_version) print(installed_version) ``` -------------------------------- ### Build Documentation Locally (Unix/Windows) Source: https://minecraft-launcher-lib.readthedocs.io/en/stable/develop/build_and_edit_documentation Commands to build the documentation locally using Sphinx. 'make html' is used on Unix-based systems, while '.\make.bat html' is used on Windows. The output is generated in the '_build/html' directory, which can then be viewed in a web browser. ```shell # Unix based Systems make html ``` ```shell # Windows .\make.bat html ```