Init first version project

This commit is contained in:
itqop 2024-10-21 11:05:56 +03:00
parent dfb8a7a565
commit 3fc9e8ef33
14 changed files with 1053 additions and 0 deletions

194
build.gradle Normal file
View File

@ -0,0 +1,194 @@
buildscript {
repositories {
// Эти репозитории предназначены только для Gradle-плагинов, другие репозитории размещайте в блоке ниже
mavenCentral()
}
dependencies {
// После удаления Mixin здесь больше не требуется зависимостей
}
}
plugins {
id 'eclipse'
id 'idea'
id 'net.minecraftforge.gradle' version '[6.0.16,6.2)'
}
group = mod_group_id
version = mod_version
base {
archivesName = mod_id
}
java {
toolchain.languageVersion = JavaLanguageVersion.of(17)
}
minecraft {
// Маппинги могут быть изменены в любое время и должны быть в следующем формате.
// Канал: Версия:
// official MCVersion Официальные имена полей/методов из файлов маппингов Mojang
// parchment YYYY.MM.DD-MCVersion Открытые имена параметров и javadocs, созданные сообществом, на основе official
// Вы должны быть в курсе лицензии Mojang при использовании 'official' или 'parchment' маппингов.
// Дополнительная информация здесь: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
// Parchment неофициальный проект, поддерживаемый ParchmentMC, отдельный от MinecraftForge
// Дополнительная настройка необходима для использования их маппингов: https://parchmentmc.org/docs/getting-started
// Используйте неофициальные маппинги на свой риск. Они могут не всегда работать.
// Просто повторно запустите задачу настройки после изменения маппингов для обновления рабочей области.
mappings channel: mapping_channel, version: mapping_version
// Когда true, это свойство будет заставлять все конфигурации запуска Eclipse/IntelliJ IDEA выполнять задачу "prepareX" для данной конфигурации запуска перед запуском игры.
// В большинстве случаев нет необходимости включать.
// enableEclipsePrepareRuns = true
// enableIdeaPrepareRuns = true
// Это свойство позволяет настроить задачи ProcessResources Gradle для запуска в IDE перед запуском игры.
// Должно быть установлено в true для корректной работы шаблона.
// См. https://docs.gradle.org/current/dsl/org.gradle.language.jvm.tasks.ProcessResources.html
copyIdeResources = true
// Когда true, это свойство добавит имя папки всех объявленных конфигураций запуска в сгенерированные конфигурации IDE.
// Имя папки можно установить в конфигурации запуска с помощью свойства "folderName".
// По умолчанию имя папки конфигурации запуска это имя Gradle-проекта, содержащего его.
// generateRunFolders = true
// Это свойство включает трансформеры доступа для использования в разработке.
// Они будут применены к артефакту Minecraft.
// Файл трансформера доступа может быть в любом месте проекта.
// Однако он должен находиться в "META-INF/accesstransformer.cfg" в финальном jar моде, чтобы быть загруженным Forge.
// Это расположение по умолчанию лучшая практика для автоматического размещения файла в правильном месте в финальном jar.
// См. https://docs.minecraftforge.net/en/latest/advanced/accesstransformers/ для дополнительной информации.
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')
// Конфигурации запуска по умолчанию.
// Их можно настроить, удалить или дублировать по мере необходимости.
runs {
// применяется ко всем конфигурациям запуска ниже
configureEach {
workingDirectory project.file('run')
// Рекомендуемые данные логирования для среды разработки
// Маркеры могут быть добавлены/удалены по мере необходимости, разделенные запятыми.
// "SCAN": Для сканирования модов.
// "REGISTRIES": Для срабатывания событий реестра.
// "REGISTRYDUMP": Для получения содержимого всех реестров.
property 'forge.logging.markers', 'REGISTRIES'
// Рекомендуемый уровень логирования для консоли
// Вы можете установить различные уровни здесь.
// Пожалуйста, прочитайте: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
"${mod_id}" {
source sourceSets.main
}
}
}
client {
// Список пространств имен, из которых загружаются gametest'ы. Пустой = все пространства имен.
property 'forge.enabledGameTestNamespaces', mod_id
}
server {
property 'forge.enabledGameTestNamespaces', mod_id
args '--nogui'
}
// Эта конфигурация запускает GameTestServer и выполняет все зарегистрированные gametest'ы, затем выходит.
// По умолчанию сервер упадет, если не предоставлены gametest'ы.
// Система gametest также включена по умолчанию для других конфигураций запуска через команду /test.
gameTestServer {
property 'forge.enabledGameTestNamespaces', mod_id
}
data {
// пример переопределения workingDirectory, установленного в configureEach выше
workingDirectory project.file('run-data')
// Укажите modid для генерации данных, куда выводить результирующий ресурс и где искать существующие ресурсы.
args '--mod', mod_id, '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
}
}
}
// Включите ресурсы, сгенерированные генераторами данных.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories {
// Добавляйте репозитории для зависимостей здесь
// ForgeGradle автоматически добавляет Forge maven и Maven Central для вас
// Если у вас есть зависимости модов в ./libs, вы можете объявить их как репозиторий следующим образом.
// См. https://docs.gradle.org/current/userguide/declaring_repositories.html#sub:flat_dir_resolver
// flatDir {
// dir 'libs'
// }
}
dependencies {
// Укажите версию Minecraft для использования.
// Любой артефакт может быть предоставлен, пока у него есть артефакт с классификатором "userdev" и он является совместимым патчером.
// Классификатор "userdev" будет запрошен и настроен ForgeGradle.
// Если groupId "net.minecraft" и artifactId один из ["client", "server", "joined"],
// то выполняется специальная обработка для настройки зависимости на ваниль без использования внешнего репозитория.
minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
// Пример зависимости мода с JEI - использование fg.deobf() обеспечивает ремаппинг зависимости на ваши маппинги разработки
// API JEI объявлен для использования во время компиляции, в то время как полный артефакт JEI используется во время выполнения
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-common-api:${jei_version}")
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}-forge-api:${jei_version}")
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}-forge:${jei_version}")
// Пример зависимости мода, использующего jar мода из ./libs с плоским репозиторием
// Это соответствует ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// groupId игнорируется при поиске в данном случае это "blank"
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// Для дополнительной информации:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
tasks.named('processResources', ProcessResources).configure {
var replaceProperties = [
minecraft_version : minecraft_version, minecraft_version_range: minecraft_version_range,
forge_version : forge_version, forge_version_range: forge_version_range,
loader_version_range: loader_version_range,
mod_id : mod_id, mod_name: mod_name, mod_license: mod_license, mod_version: mod_version,
mod_authors : mod_authors, mod_description: mod_description,
]
inputs.properties replaceProperties
filesMatching(['META-INF/mods.toml', 'pack.mcmeta']) {
expand replaceProperties + [project: project]
}
}
// Пример того, как получить свойства в манифест для чтения во время выполнения.
tasks.named('jar', Jar).configure {
manifest {
attributes([
"Specification-Title" : mod_id,
"Specification-Vendor" : mod_authors,
"Specification-Version" : "1", // Мы версия 1 самих себя
"Implementation-Title" : project.name,
"Implementation-Version" : project.jar.archiveVersion,
"Implementation-Vendor" : mod_authors,
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
// Это предпочтительный метод для переобфускации вашего jar файла
finalizedBy 'reobfJar'
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Используйте кодировку UTF-8 для компиляции Java
}

49
gradle.properties Normal file
View File

@ -0,0 +1,49 @@
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
# The Minecraft version must agree with the Forge version to get a valid artifact
minecraft_version=1.20.1
# The Minecraft version range can use any release version of Minecraft as bounds.
# Snapshots, pre-releases, and release candidates are not guaranteed to sort properly
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.20.1,)
# The Forge version must agree with the Minecraft version to get a valid artifact
forge_version=47.3.11
# The Forge version range can use any version of Forge as bounds or match the loader version range
forge_version_range=[47,)
# The loader version range can only use the major version of Forge/FML as bounds
loader_version_range=[47,)
# The mapping channel to use for mappings.
# The default set of supported mapping channels are ["official", "snapshot", "snapshot_nodoc", "stable", "stable_nodoc"].
# Additional mapping channels can be registered through the "channelProviders" extension in a Gradle plugin.
#
# | Channel | Version | |
# |-----------|----------------------|--------------------------------------------------------------------------------|
# | official | MCVersion | Official field/method names from Mojang mapping files |
# | parchment | YYYY.MM.DD-MCVersion | Open community-sourced parameter names and javadocs layered on top of official |
#
# You must be aware of the Mojang license when using the 'official' or 'parchment' mappings.
# See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
#
# Parchment is an unofficial project maintained by ParchmentMC, separate from Minecraft Forge.
# Additional setup is needed to use their mappings, see https://parchmentmc.org/docs/getting-started
mapping_channel=official
# The mapping version to query from the mapping channel.
# This must match the format required by the mapping channel.
mapping_version=1.20.1
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=chatit
# The human-readable display name for the mod.
mod_name=ChatIT
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=0.1-BETA
# The group ID for the mod. It is only important when publishing as an artifact to a Maven repository.
# This should match the base package used for the mod sources.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=org.itqop
# The authors of the mod. This is a simple text string that is used for display purposes in the mod list.
mod_authors=itqop
# The description of the mod. This is a simple multiline text string that is used for display purposes in the mod list.
mod_description=Chat for Forge

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

249
gradlew vendored Normal file
View File

@ -0,0 +1,249 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

15
settings.gradle Normal file
View File

@ -0,0 +1,15 @@
pluginManagement {
repositories {
gradlePluginPortal()
maven {
name = 'MinecraftForge'
url = 'https://maven.minecraftforge.net/'
}
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.7.0'
}
rootProject.name = 'ChatIT'

View File

@ -0,0 +1,38 @@
package org.itqop.chatit;
import com.mojang.logging.LogUtils;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import org.itqop.chatit.commands.ChatitCommand;
import org.itqop.chatit.handlers.ChatEventHandler;
import org.itqop.chatit.utils.Config;
import org.itqop.chatit.utils.PlayerConfigManager;
import org.slf4j.Logger;
@Mod(Chatit.MODID)
public class Chatit {
public static final String MODID = "chatit";
private static final Logger LOGGER = LogUtils.getLogger();
public Chatit() {
// Регистрация обработчиков событий
MinecraftForge.EVENT_BUS.register(this); // Для событий сервера
MinecraftForge.EVENT_BUS.register(ChatEventHandler.class); // Обработчик чата
MinecraftForge.EVENT_BUS.register(ChatitCommand.class); // Команда
// Регистрация конфигурации
ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, Config.COMMON_CONFIG);
}
@SubscribeEvent
public void onServerStarting(ServerStartingEvent event) {
// Загрузка конфигурации игроков при старте сервера
PlayerConfigManager.loadConfig();
LOGGER.info("ChatIT started and configuration loaded.");
}
}

View File

@ -0,0 +1,34 @@
package org.itqop.chatit.commands;
import com.mojang.brigadier.CommandDispatcher;
import net.minecraft.commands.Commands;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.network.chat.Component;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.itqop.chatit.utils.PlayerConfigManager;
@Mod.EventBusSubscriber
public class ChatitCommand {
@SubscribeEvent
public static void onRegisterCommands(RegisterCommandsEvent event) {
CommandDispatcher<CommandSourceStack> dispatcher = event.getDispatcher();
dispatcher.register(Commands.literal("chatit")
.then(Commands.literal("adult")
.requires(source -> source.hasPermission(2)) // Уровень разрешения 2 (операторы)
.executes(context -> {
ServerPlayer player = context.getSource().getPlayerOrException();
PlayerConfigManager.toggleAdultContent(player);
boolean current = PlayerConfigManager.hasAdultContentEnabled(player);
String status = current ? "включен" : "выключен";
player.sendSystemMessage(Component.literal("Параметр adult теперь " + status + "."));
return 1;
})
)
);
}
}

View File

@ -0,0 +1,114 @@
package org.itqop.chatit.handlers;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.event.ServerChatEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.MinecraftServer;
import net.minecraft.ChatFormatting;
import org.itqop.chatit.utils.PlayerConfigManager;
import org.itqop.chatit.utils.ProfanityChecker;
import java.util.concurrent.CompletableFuture;
@Mod.EventBusSubscriber
public class ChatEventHandler {
@SubscribeEvent
public static void onServerChat(ServerChatEvent event) {
ServerPlayer sender = event.getPlayer();
MinecraftServer server = sender.getServer();
String originalMessage = event.getMessage().getString();
// Отменяем стандартную отправку сообщения
event.setCanceled(true);
// Убеждаемся, что отправитель есть в настройках
PlayerConfigManager.ensurePlayerExists(sender);
// Проверка на наличие '!' для глобального сообщения
boolean isGlobal = originalMessage.startsWith("!");
String message = isGlobal ? originalMessage.substring(1) : originalMessage;
// Создаем заготовку сообщения для отправки после проверки
MutableComponent chatComponent = createChatMessage(sender, message, isGlobal);
// Запускаем асинхронную проверку сообщения
CompletableFuture<Double> future = ProfanityChecker.checkMessageAsync(message);
future.thenAccept(profanityScore -> {
if (server != null) {
server.execute(() -> {
// Обработка результата проверки
if (profanityScore > 0.5 && !PlayerConfigManager.hasAdultContentEnabled(sender)) {
// Отправляем сообщение только отправителю с префиксом [ERROR]
MutableComponent errorComponent = createErrorMessage(sender, message);
sender.sendSystemMessage(errorComponent);
} else {
for (ServerPlayer receiver : server.getPlayerList().getPlayers()) {
// Убеждаемся, что получатель есть в настройках
PlayerConfigManager.ensurePlayerExists(receiver);
// Если сообщение содержит маты и у получателя параметр adult OFF
if (profanityScore > 0.5 && !PlayerConfigManager.hasAdultContentEnabled(receiver)) {
continue; // Пропускаем отправку этому игроку
}
// Проверяем условия для отправки сообщения
if (isGlobal || (receiver.level() == sender.level() && receiver.position().distanceTo(sender.position()) <= 50)) {
receiver.sendSystemMessage(chatComponent);
}
}
}
});
}
}).exceptionally(ex -> {
ex.printStackTrace();
if (server != null) {
server.execute(() -> {
// В случае ошибки отправляем сообщение только отправителю с префиксом [ERROR]
MutableComponent errorComponent = createErrorMessage(sender, message);
sender.sendSystemMessage(errorComponent);
});
}
return null;
});
}
private static MutableComponent createErrorMessage(ServerPlayer player, String message) {
MutableComponent openBracket = Component.literal("[");
MutableComponent errorText = Component.literal("ERROR")
.withStyle(ChatFormatting.RED, ChatFormatting.BOLD);
MutableComponent closeBracket = Component.literal("] ");
MutableComponent prefixComponent = openBracket.append(errorText).append(closeBracket);
Component playerName = Component.literal(player.getName().getString());
Component messageComponent = Component.literal(": " + message);
return prefixComponent.append(playerName).append(messageComponent);
}
private static MutableComponent createChatMessage(ServerPlayer player, String message, boolean isGlobal) {
MutableComponent openBracket = Component.literal("[");
MutableComponent letterComponent;
MutableComponent closeBracket = Component.literal("] ");
if (isGlobal) {
letterComponent = Component.literal("G")
.withStyle(ChatFormatting.BOLD, ChatFormatting.GREEN);
} else {
letterComponent = Component.literal("L")
.withStyle(ChatFormatting.BOLD, ChatFormatting.YELLOW);
}
MutableComponent prefixComponent = openBracket.append(letterComponent).append(closeBracket);
Component playerName = Component.literal(player.getName().getString());
Component messageComponent = Component.literal(": " + message);
return prefixComponent.append(playerName).append(messageComponent);
}
}

View File

@ -0,0 +1,48 @@
package org.itqop.chatit.utils;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import org.itqop.chatit.Chatit;
@Mod.EventBusSubscriber(modid = Chatit.MODID, bus = Mod.EventBusSubscriber.Bus.MOD)
public class Config {
private static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();
public static ForgeConfigSpec COMMON_CONFIG;
public static ForgeConfigSpec.ConfigValue<String> HOST_API;
public static ForgeConfigSpec.BooleanValue DEFAULT_ADULT;
public static ForgeConfigSpec.BooleanValue USE_REGEX; // Добавили настройку regex
static {
BUILDER.comment("Настройки ChatIT");
HOST_API = BUILDER
.comment("URL API для проверки мата")
.define("host_api", "");
DEFAULT_ADULT = BUILDER
.comment("Значение adult по умолчанию для новых игроков")
.define("default_adult", false);
USE_REGEX = BUILDER
.comment("Использовать регулярное выражение при недоступности API")
.define("regex", true); // Значение по умолчанию false
COMMON_CONFIG = BUILDER.build();
}
public static String hostApi;
public static boolean defaultAdult;
public static boolean useRegex;
@SubscribeEvent
public static void onLoad(final ModConfigEvent event) {
hostApi = HOST_API.get();
defaultAdult = DEFAULT_ADULT.get();
useRegex = USE_REGEX.get();
}
}

View File

@ -0,0 +1,57 @@
package org.itqop.chatit.utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import net.minecraft.server.level.ServerPlayer;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class PlayerConfigManager {
private static final Gson GSON = new Gson();
private static final File CONFIG_FILE = new File("config/chatit_player_settings.json");
private static final Type CONFIG_TYPE = new TypeToken<Map<UUID, Boolean>>() {}.getType();
private static Map<UUID, Boolean> playerSettings = new HashMap<>();
public static void loadConfig() {
if (CONFIG_FILE.exists()) {
try (FileReader reader = new FileReader(CONFIG_FILE)) {
playerSettings = GSON.fromJson(reader, CONFIG_TYPE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void saveConfig() {
try (FileWriter writer = new FileWriter(CONFIG_FILE)) {
GSON.toJson(playerSettings, writer);
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean hasAdultContentEnabled(ServerPlayer player) {
return playerSettings.getOrDefault(player.getUUID(), Config.defaultAdult);
}
public static void toggleAdultContent(ServerPlayer player) {
boolean current = hasAdultContentEnabled(player);
playerSettings.put(player.getUUID(), !current);
saveConfig();
}
public static void ensurePlayerExists(ServerPlayer player) {
if (!playerSettings.containsKey(player.getUUID())) {
playerSettings.put(player.getUUID(), Config.defaultAdult);
saveConfig();
}
}
}

View File

@ -0,0 +1,87 @@
package org.itqop.chatit.utils;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.regex.Pattern;
import com.google.gson.Gson;
public class ProfanityChecker {
private static final Gson GSON = new Gson();
private static final HttpClient CLIENT = HttpClient.newHttpClient();
// Ваше регулярное выражение для проверки мата
private static final String PROFANITY_REGEX = "(?iu)\\b(?:(?:(?:у|[нз]а|(?:хитро|не)?вз?[ыьъ]|с[ьъ]|(?:и|ра)[зс]ъ?|(?:.\\B)+?[оаеи-])-?)?(?:[её](?:б(?!о[рй]|рач)|п[уа](?:ц|тс))|и[пб][ае][тцд][ьъ]).*?|(?:(?:н[иеа]|(?:ра|и)[зс]|[зд]?[ао](?:т|дн[оа])?|с(?:м[еи])?|а[пб]ч|в[ъы]?|пр[еи])-?)?ху(?:[яйиеёю]|л+и(?!ган)).*?|бл(?:[эя]|еа?)(?:[дт][ьъ]?)?|\\S*?(?:п(?:[иеё]зд|ид[аое]?р|ед(?:р(?!о)|[аое]р|ик)|охую)|бля(?:[дбц]|тс)|[ое]ху[яйиеё]|хуйн).*?|(?:о[тб]?|про|на|вы)?м(?:анд(?:[ауеыи](?:л(?:и[сзщ])?[ауеиы])?|ой|[ао]в.*?|юк(?:ов|[ауи])?|е[нт]ь|ища)|уд(?:[яаиое].+?|е?н(?:[ьюия]|ей))|[ао]л[ао]ф[ьъ](?:[яиюе]|[еёо]й))|елд[ауые].*?|ля[тд]ь|(?:[нз]а|по)х)\\b";
private static final Pattern PROFANITY_PATTERN = Pattern.compile(PROFANITY_REGEX);
public static CompletableFuture<Double> checkMessageAsync(String message) {
return CompletableFuture.supplyAsync(() -> {
try {
String apiUrl = Config.hostApi;
boolean useRegex = Config.useRegex;
if (apiUrl == null || apiUrl.isEmpty()) {
// Если URL API не задан
if (useRegex) {
// Используем регулярное выражение для проверки мата
if (containsProfanity(message)) {
return 1.0; // Мат найден
} else {
return 0.0; // Мат не найден
}
} else {
// Если regex=false, возвращаем 0.0 (нет мата)
return 0.0;
}
}
// Создаем JSON-запрос
String jsonRequest = GSON.toJson(new MessageRequest(message));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(apiUrl))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonRequest, StandardCharsets.UTF_8))
.build();
// Отправляем запрос и получаем ответ
HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
// Парсим ответ
String responseBody = response.body();
double result = Double.parseDouble(responseBody);
return result;
} catch (Exception e) {
e.printStackTrace();
if (Config.useRegex) {
// Если произошла ошибка и regex=true, используем регулярное выражение
if (containsProfanity(message)) {
return 1.0; // Мат найден
}
}
// В случае ошибки и regex=false считаем, что мата нет
return 0.0;
}
});
}
private static boolean containsProfanity(String message) {
return PROFANITY_PATTERN.matcher(message).find();
}
// Класс для сериализации JSON-запроса
private static class MessageRequest {
private final String text;
public MessageRequest(String text) {
this.text = text;
}
}
}

View File

@ -0,0 +1,63 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader = "javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion = "${loader_version_range}" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license = "${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId = "${mod_id}" #mandatory
# The version number of the mod
version = "${mod_version}" #mandatory
# A display name for the mod
displayName = "${mod_name}" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.minecraftforge.net/en/latest/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="chatit.png" #optional
# A text field displayed in the mod UI
#credits="Thanks for this example mod goes to Java" #optional
# A text field displayed in the mod UI
authors = "${mod_authors}" #optional
# Display Test controls the display for your mod in the server connection screen
# MATCH_VERSION means that your mod will cause a red X if the versions on client and server differ. This is the default behaviour and should be what you choose if you have server and client elements to your mod.
# IGNORE_SERVER_VERSION means that your mod will not cause a red X if it's present on the server but not on the client. This is what you should use if you're a server only mod.
# IGNORE_ALL_VERSION means that your mod will not cause a red X if it's present on the client or the server. This is a special case and should only be used if your mod has no server component.
# NONE means that no display test is set on your mod. You need to do this yourself, see IExtensionPoint.DisplayTest for more information. You can define any scheme you wish with this value.
# IMPORTANT NOTE: this is NOT an instruction as to which environments (CLIENT or DEDICATED SERVER) your mod loads on. Your mod should load (and maybe do nothing!) whereever it finds itself.
#displayTest="MATCH_VERSION" # MATCH_VERSION is the default if nothing is specified (#optional)
# The description text for the mod (multi line!) (#mandatory)
description = '''${mod_description}'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies."${mod_id}"]] #optional
# the modid of the dependency
modId = "forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory = true #mandatory
# The version range of the dependency
versionRange = "${forge_version_range}" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the dependency is not mandatory
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering = "NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side = "BOTH"# Here's another dependency
[[dependencies."${mod_id}"]]
modId = "minecraft"
mandatory = true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange = "${minecraft_version_range}"
ordering = "NONE"
side = "BOTH"

View File

@ -0,0 +1,6 @@
{
"pack": {
"description": "chatit resources",
"pack_format": 15
}
}