CraftPresence
Полностью настройте то, как другие видят вашу игру в Discord!
Быстрое задание
Как далеко вы сможете убежать, прежде чем вас поймают толпы?
Проверка Minecraft
Подтвердите свой запуск
Пройдите быструю проверку, чтобы получить свой код.
CraftPresence
CraftPresence
Полностью настройте то, как другие видят вашу игру в Minecraft, с помощью Rich Presence API от Discord и DiscordIPC API от jagrosh!
Общие замечания
* Начиная с версии 2.5.0, UniLib теперь является не будет бежать Зависимость * UniLib — это новая библиотека, которую я создал для абстрагирования общих функций API для более общих вариантов использования, а также для будущих проектов. * Мод можно скачать здесь. * Этот мод не будет бежать Если библиотека UniLib не найдена или используется несовместимая версия, * Этот мод идентифицируется как не будет бежать мод * Это означает, что не будет бежать На стороне сервера. * Загрузчики модов Fabric и Quilt просто проигнорируют мод, в то время как другие загрузчики модов могут привести к сбою. * Некоторые версии мода для Minecraft 1.14.x и выше требуют Fabric API и загрузчика модов Fabric. * Некоторые версии мода для Minecraft 1.13.x требуют Rift API и загрузчика модов Rift. * Некоторые версии мода для Minecraft 1.1.0 и ниже требуют Risugami's ModLoader.
Особенности
Помимо возможности изменить свой статус в Discord с "Играю в Minecraft", этот мод предлагает множество вариантов настройки, позволяющих полностью определить, как другие видят вашу игру. От отображения текущего биома до того, в каком измерении вы находитесь, на каком сервере играете и многое другое. Возможности настройки безграничны, и единственным реальным ограничением является то, насколько креативно вы настроите свой экран.
Поддержка интеграции с лаунчерами и пакетами.
CraftPresence определит, содержит ли ваша директория запуска:
* Экземпляр ATLauncher (instance.json) * Действительный манифест Twitch/Overwolf/Curse/GDLauncher (manifest.json, minecraftinstance.json) * Экземпляр MCUpdater (instance.json) * Экземпляр Modrinth (profile.json) * Экземпляр MultiMC (instance.cfg) * Файл installedPacks от Technic (installedPacks)
При использовании любого из этих лаунчеров обратите внимание на следующее:
* До версии 1.6.0 на экране отображалось название пакета, а также его значок (если вы не на сервере). * Начиная с версии 1.6.0 и до версии 2.0.0, название пакета преобразуется в заполнитель `&PACK&`, который можно настроить для использования в RPC. * В версии 2.0 информация о пакете преобразуется в заполнители `pack.name` и `pack.icon`, которые можно настроить для использования в RPC.
Например, вот как мод преобразует название пакета в iconKey:
Пример: `All the Mods 7` будет интерпретировано как `allthemods7`
Примечание: В MultiMC изначально есть свойство Icon Key, которое используется вместо преобразования из отображаемого имени пакета.
Команды
В настоящее время CraftPresence предлагает следующие команды:
Помните следующее:
* Команды должны начинаться с префикса `/craftpresence` или `/cp`. * В версии 1.5.0 и выше эти команды можно использовать только через графический интерфейс команд, расположенный в графическом интерфейсе конфигурации.
___
* `/cp compile "[expr]"` — Проверка вывода выражения-заполнителя с помощью Starscript * `/cp search (type:typeName, [searchTerm], all)` — Поиск допустимых заполнителей, доступных для использования с Rich Presence * `/cp reload` — Перезагрузка данных мода * `/cp request` — Просмотр информации о запросе на присоединение * `/cp export` — Просмотр команд экспорта данных мода * `/cp view` — Команда справки для отображения команд, доступных для просмотра и управления различными данными отображения * `/cp view placeholders` — Отображение всех доступных заполнителей для использования в RPC * `/cp view currentData` — Отображение текущих данных RPC в текстовом виде * `/cp view assets (custom | all)` — Отображение всех доступных ключей значков ресурсов * `/cp view dimensions` — Отображение всех доступных для использования названий измерений; требуется включить `Показать текущее измерение` * `/cp view biomes` — Отображение всех доступных для использования названий биомов. * Требуется включить параметр `Show Current Biome` * `/cp view servers` — отображает все доступные адреса серверов, требуется включить параметр `Show Game State` * `/cp view screens` — отображает все доступные имена графического интерфейса, если включен параметр Per-Gui * `/cp view items` — отображает все доступные имена предметов, если включен параметр Per-Item * `/cp view entities` — отображает все доступные имена сущностей, если включен параметр Per-Entity * `/cp reboot` — перезагружает RPC * `/cp shutdown` — выключает RPC (можно включить с помощью `/cp reboot`) * `/cp (help | ?)` — команда справки для отображения вышеуказанных команд и пояснений
Привязки клавиш
В настоящее время CraftPresence содержит следующие сочетания клавиш:
Примечание:
* В версиях с 1.5.5 по 1.8.0 настройки сочетаний клавиш теперь выполняются в параметрах специальных возможностей в графическом интерфейсе конфигурации, а не в обычном меню управления. * В версиях 1.8.0 и выше настройки сочетаний клавиш теперь можно выполнять либо в специальном меню графического интерфейса конфигурации, либо в обычном меню управления (в соответствующих версиях).
___
* `Открыть графический интерфейс конфигурации` — сочетание клавиш для открытия графического интерфейса конфигурации CraftPresence (по умолчанию: клавиша GRAVE/TILDE)
О заполнителях и функциях
В некоторых областях конфигурации CraftPresence предоставляет заглушки и функции для упрощения работы:
Помните следующее:
* В версии 2.0.0 заполнители были переписаны для совместимости со Starscript. * Более старый список в этом разделе можно посмотреть здесь. * Все заполнители, функции и выражения кода должны быть заключены в фигурные скобки (например: `{foo.bar}`). * Если вам необходимо объединить заполнитель с другими данными в аргументе функции, используйте функцию `getResult`. * Дополнительные функции и стандартные переменные доступны в StandardLib.
___
Список-заполнитель
Следующие заполнители доступны для использования в любом месте CraftPresence:
* General Placeholders: * `general.brand` - The Minecraft branding label * `general.icon` - The default display icon * `general.mods` - The amount of mods currently in your mods folder * `general.title` - The Minecraft title label * `general.version` - The Minecraft version label * `general.protocol` - The Minecraft version protocol label * Menu Event Placeholders (Loading and Main Menu): * `menu.message` - The main menu's display data, while applicable * `menu.icon` - The main menu's display icon, while applicable * Pack Placeholders: * `pack.name` - The currently detected pack's name * `pack.icon` - The currently detected pack's icon * `pack.type` - The currently detected pack's type * Player Placeholders: * `player.name` - Your username * `player.uuid.short` - Your UUID (Trimmed Format) * `player.uuid.full` - Your UUID (Full Format, if valid UUID) * `player.icon` - Your player head icon, while applicable * `player.position.x` - Your current in-game X position * `player.position.y` - Your current in-game Y position * `player.position.z` - Your current in-game Z position * `player.health.current` - Your current in-game health * `player.health.max` - Your current in-game maximum health * `player.mode` - Your current game mode * Gui Placeholders: * `screen.message` - The current Gui Screen's display data, while applicable * `screen.name` - The current Gui Screen name * `screen.icon` - The current Gui Screen icon * `screen.default.icon` - The default Gui Screen icon * Biome Placeholders: * `biome.message` - The current biome's display data, while in-game * `biome.name` - The current biome name * `biome.identifier` - The current biome identifier * `biome.icon` - The current biome icon * `biome.default.icon` - The default biome icon * Dimension Placeholders: * `dimension.message` - The current dimension's display data, while in-game * `dimension.name` - The current dimension name * `dimension.identifier` - The current dimension identifier * `dimension.icon` - The current dimension icon * `dimension.default.icon` - The default dimension icon * Entity Placeholders: * `entity.default.icon` - The default entity icon * `entity.target.message` - The currently targeted entity's display data, while applicable * `entity.target.name` - The currently targeted entity's name * `entity.target.icon` - The currently targeted entity's icon * `entity.riding.message` - The currently riding entity's display data, while applicable * `entity.riding.name` - The currently riding entity's name * `entity.riding.icon` - The currently riding entity's icon * World Placeholders: * `world.difficulty` - The current world's difficulty * `world.weather.name` - The current world's weather name * `world.name` - The name of the current world * `world.type` - The current world type * `world.time.format_24` - The current world's in-game time (24-hour format) * `world.time.format_12` - The current world's in-game time (12-hour format) * `world.time.day` - The current world's in-game day count * Server Placeholders: * `server.message` - The current server's display data, while in-game * `server.icon` - The current server icon * `server.default.icon` - The default server icon * `server.players.current` - The server's current player count * `server.players.max` - The server's maximum player count * `server.address.full` - (MP) The raw current server address * `server.address.short` - (MP) The formatted current server address * `server.name` - (MP) The current server name * `server.motd.raw` - (MP) The current raw server motd * `server.minigame` - (Realm) The current realm minigame name * `server.type` - (Realm) The current realm world type * Item Placeholders: * `item.message.default` - The default item display data, while applicable * `item.message.holding` - The held item(s) display data, while applicable * `item.message.equipped` - The equipped item(s) display data, while applicable * `item.[slotId].name` - Current `slotId` item name * `item.[slotId].message` - Current `slotId` item message * Integration - Replay Mod: * `replaymod.time.current` - When in the Video Renderer, retrieves the `renderTimeTaken` field * `replaymod.time.remaining` - When in the Video Renderer, retrieves the `renderTimeLeft` field * Extra Placeholders (Advanced Usage): * `_general.instance` - The `Minecraft` Instance * `_general.player` - The `Minecraft` Player Instance * `_general.world` - The `Minecraft` World Instance * ``config.instance` - Экземпляр конфигурации мода * ``[moduleName].instance` — Экземпляр одного из модулей CraftPresence. * Порядок модулей: `biome, dimension, entity, item, screen, server, <...>` * `data.biome.instance` — Экземпляр текущего биома игрока. * `data.biome.class` — Классовый объект текущего биома игрока. * `data.dimension.instance` — Экземпляр текущего измерения игрока. * `data.dimension.class` — Классовый объект текущего измерения игрока. * `data.entity.target.instance` — Экземпляр текущей целевой сущности. * `data.entity.target.class` — Классовый объект текущей целевой сущности. * `data.entity.riding.instance` — Экземпляр текущей верховой сущности. * `data.entity.riding.class` — Классовый объект текущей верховой сущности. * `data.item.[slotId].instance` — Экземпляр текущего `slotId` * `data.item.[slotId].class` — Объект класса для текущего `slotId` * `data.screen.instance` — Экземпляр текущего графического экрана * `data.server.motd.line_[number]` — Извлекает конкретную строку из `server.motd.raw` * `data.[moduleName].time` — Метка времени, в которую модуль изменил свое основное состояние * Используйте `data.general.time` для текущей метки времени начала RPC
Список функций
Следующие функции доступны для использования в любой точке CraftPresence:
* `asIcon(input, whitespaceIndex ?: )` - Converts a String into a Valid and Acceptable Icon Format * `asIdentifier(target, formatToId ?: false, avoid ?: false)` - Converts an Identifier into a properly formatted and interpretable Name * `asProperWord(input, avoid ?: false, skipSymbolReplacement ?: false, caseCheckTimes ?: -1)` - Converts input into a Properly Readable String * `capitalizeWords(input, timesToCheck ?: -1)` - Capitalizes the words within a specified string * `clampDouble(num, min, max)` - Clamps the Specified Number between a minimum and maximum limit * `clampFloat(num, min, max)` - Clamps the Specified Number between a minimum and maximum limit * `clampInt(num, min, max)` - Clamps the Specified Number between a minimum and maximum limit * `clampLong(num, min, max)` - Clamps the Specified Number between a minimum and maximum limit * `convertTime(input, originalPattern, newPattern)` - Convert the specified string into the specified date format, if able * `convertTimeFormat(dateString, fromFormat, toFormat)` - Convert a Date String from one format to another format * `convertTimeZone(dateString, fromFormat, fromTimeZone, toTimeZone)` - Convert a Date String from one timezone to another timezone * `dateToEpochMilli(dateString, format, timeZone ?: null)` - Convert Date String to Epoch Timestamp in milliseconds * `dateToEpochSecond(dateString, format, timeZone ?: null)` - Convert Date String to Epoch Timestamp in seconds * `epochMilliToDate(epochMilli, format, timeZone ?: null)` - Convert Epoch Timestamp to Date String in the given format and timezone * `epochSecondToDate(epochSecond, format, timeZone ?: null)` - Convert Epoch Timestamp to Date String in the given format and timezone * `executeMethod(classToAccess=Object|String|Class, instance=Object, methodName=String, <parameterType, parameter>...)` - Invokes the specified Method in the Target Class via Reflection * `format(input=String, args=Object...)` - Returns a formatted string using the specified format string and arguments * `formatAddress(input, returnPort ?: false)` - Formats an IP Address based on Input * `getArrayElement(content=Array, index)` - Retrieves the array element from the specified content, or null if unable * `getAsset(input)` - Retrieves the Specified DiscordAsset data from an Icon Key, if present * `getAssetId(input)` - Retrieves the Parsed Icon ID from the specified key, if present * `getAssetKey(input)` - Retrieves the Parsed Icon Key from the specified key, if present * `getAssetType(input)` - Retrieves the Parsed Image Type from the specified key, if present * `getAssetUrl(input)` - Retrieves the Parsed Image Url from the specified key, if present * `getClass(reference=Object|String)` - Attempt to retrieve a class object, via the string path or object reference * `getComponent(data=DataComponentHolder, path=String)` - (MC 1.20.5+) Attempt to retrieve the Component Data with the specified path * `getCurrentTime()` - Retrieve the current time, as an Instant * `getElapsedMillis()` - Retrieve the elapsed time, in milliseconds * `getElapsedNanos()` - Retrieve the elapsed time, in nanoseconds * `getElapsedSeconds()` - Retrieve the elapsed time, in seconds * `getField(classToAccess=Object|String|Class, instance=Object, fieldName=String...)` - Retrieves the Specified Field(s) via Reflection * `getFields(classObj=Object|String|Class)` - Retrieve the available field names for a class object * `getFirst(args)` - Retrieve the first non-null string from the specified arguments, or return null * `getJsonElement(url|jsonString, path=Object...)` - Retrieves the json element from the specified content, or null if unable * `getMethods(classObj=Object|String|Class)` - Retrieve the available method names for a class object * `getNamespace(input)` - Retrieve the namespace portion of an Identifier-Style Object * `getNbt(data=Entity|ItemStack, path=String...)` - Attempt to retrieve the NBT Tag with the specified path * `getOrDefault(target, alternative ?: )` - Retrieve the primary value if non-empty; Otherwise, use the secondary value * `getPath(input)` - Retrieve the path portion of an Identifier-Style Object * `getResult(input)` - Perform recursive conversion on the specified input * `hasField(classObj=Object|String|Class, fieldName)` - Retrieves whether the specified class contains the specified field name * `isColor(input)` - Determines whether an inputted String classifies as a valid Color Code * `isCustomAsset(input)` - Determines if the Specified Icon Key is present under the Custom Assets List * `isUuid(input)` - Checks via Regex whether the specified String classifies as a valid Uuid * `isValidAsset(input)` - Determines if the Specified Icon Key is present under the Current Client ID * `isValidId(input)` - Determines if the specified Client ID is valid * `isWithinValue(value, min, max, contains_min ?: false, contains_max ?: false, check_sanity ?: true)` - Determines whether the specified value is within the specified range * `length(input)` - Returns the length of the specified string * `lerpDouble(num, min, max)` - Linearly Interpolate between the specified values * `lerpFloat(num, min, max)` - Linearly Interpolate between the specified values * `mcTranslate(input=String, args=Object...)` - Translates an Unlocalized String, based on the game translations retrieved for the current language * `minify(input, length)` - Reduces the Length of a String to the Specified Length * `nullOrEmpty(input, allowWhitespace ?: false)` - Determines whether a String classifies as NULL or EMPTY * `randomAsset()` - Attempts to retrieve a Random Icon Key from the available assets * `randomString(args)` - Retrieves a random element from the specified arguments, as a string * `removeRepeatWords(input)` - Removes Duplicated Words within an inputted String * `roundDouble(num, places ?: 0)` - Rounds a Double to the defined decimal place, if possible * `snapToStep(num, valueStep)` - Rounds the Specified Value to the nearest value, using the Step Rate Value * `split(input, regex, limit ?: 0)` - Splits this string around matches of the given regular expression * `stripAllFormatting(input)` - Strips Color and Formatting Codes from the inputted String * `stripColors(input)` - Strips Color Codes from the inputted String * `stripFormatting(input)` - Strips Formatting Codes from the inputted String * `timeFromEpochMilli(epochMilli)` - Retrieve a Time Instant from the specified epoch time * `timeFromEpochSecond(epochSecond)` - Retrieve a Time Instant from the specified epoch time * `timeFromString(dateString, fromFormat, fromTimeZone ?: null)` - Format a Date String from one timezone and format into a valid Instant instance * `timeToEpochMilli(data)` - Gets the number of milliseconds from the Java Epoch, derived from specified args * `timeToEpochSecond(data)` - Gets the number of seconds from the Java Epoch, derived from specified args * `timeToString(date, toFormat, toTimeZone ?: null)` - Format a Date String using the specified timezone and format. * `toCamelCase(input)` — Преобразует строку в допустимый формат Camel-Case. * `translate(input=String, args=Object...)` — Переводит нелокализованную строку на основе переводов модуля, полученных для текущего языка.
Оговорки и дополнительная информация
Проблемы с Minecraft + дополнительная информация о постройках
Несмотря на все усилия, проблемы могут возникать из-за состояния кодовой базы Minecraft.
Эти проблемы могут препятствовать работе некоторых частей бэкэнда, а также приводить к неработоспособности отдельных компонентов мода.
С учетом вышесказанного, пожалуйста, обратите внимание на следующее:
* Разные вопросы * Поскольку все больше элементов игры становятся основанными на данных, некоторые модифицированные данные больше не могут быть автоматически получены без предварительного нахождения в игровом мире. * На данный момент это изменение затрагивает модули биомов и измерений, которые отображают только стандартные данные, а дополнительные данные необходимо сначала обнаружить. * Разные вопросы * `MC-112292`: При взаимодействии с методом `RenderUtils#drawItemStack`, используемым в рендерере предметов версии 2, блоки, использующие определенные рендереры, могут отображаться некорректно. * Кроме того, исключительно в версии 1.15.x могут возникать проблемы с уровнем по оси Z на экранах, использующих этот метод. * Разные вопросы * В этих версиях модули «Биом» и «Измерение» являются Разные вопросы с данными по умолчанию, из-за отсутствия логики для этих методов (первоначально реализовано в альфа-версии 1.2.6) * Разные вопросы * Из-за проблем с обфускацией в более ранних версиях Minecraft при использовании некоторых частей мода могут появляться некорректные данные. * В этом случае модули биомов и измерений могут не определить автоматически некоторую необходимую информацию. * В качестве резервного варианта мод также предусматривает добавление выбираемых данных модуля при первом обнаружении соответствующего биома/измерения. * Для решения этой проблемы также можно использовать опцию «Добавить новый», которая есть в некоторых списках модулей.
Кроме того, некоторые настройки или вызовы API могут работать по-разному в определенных версиях MC.
Запрос значка
Не нашли понравившийся значок или у вас есть предложение по значку для добавления/изменения в стандартном идентификаторе клиента?
В таком случае вы можете отправить запрос в мою систему отслеживания ошибок, указав следующие требования:
* При добавлении иконки из измерения укажите ссылку на мод, от которого происходит это измерение. * Это необходимо, поскольку должны использоваться определенные идентификаторы иконок, которые можно найти в моде или в логах/чате после входа в измерение, так как CraftPresence сообщит вам ожидаемый идентификатор. * Размер иконки должен быть от `512x512` до `1024x1024` (минимальный или рекомендуемый размер для наилучшего качества). * Иконки этих размеров можно использовать, но качество может быть невысоким. * Если вы запрашиваете изменение или удаление иконки из идентификатора клиента по умолчанию, укажите причину. * В основном это необходимо для того, чтобы можно было зафиксировать причину изменения для дальнейшего использования.
Кроме того, вы можете создать свой собственный набор значков, следуя этому руководству.
Поддержка
Нужна помощь с одним из моих модов или хотите оставить отзыв?
Со мной можно связаться следующими способами:
* Электронная почта * CurseForge * Discord ::
Кроме того, документация по коду этого мода доступна здесь, а дополнительные руководства — на вики.
Лицензирование
Этот мод распространяется под лицензиями MIT и Apache 2.0.
В настоящее время в рамках данного проекта используются следующие внутренние зависимости:
* Starscript от MeteorDevelopment * DiscordIPC API от jagrosh * UniLib от CDAGaming
Условия использования Discord
Как и другие RPC-моды, этот мод использует ваши внутриигровые данные для отправки отображаемой информации стороннему сервису (в данном случае, Discord).
С условиями предоставления услуг, касающимися создания Discord-идентификатора для иконок, можно ознакомиться здесь.
С условиями использования Discord можно ознакомиться здесь.