Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minecraft 1.18 support #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 171 additions & 0 deletions bridge-1.18/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
buildscript {
repositories {
maven { url = 'https://maven.minecraftforge.net' }
jcenter()
mavenCentral()
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
classpath "gradle.plugin.com.matthewprenger:CurseGradle:1.4.0"
}
}
apply plugin: 'net.minecraftforge.gradle'
apply plugin: "com.matthewprenger.cursegradle"
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.

version = "1.18.2-${project.mod_version}"
group = "ru.glitchless.telegrambridge" // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'telegrambridge'

java.toolchain.languageVersion = JavaLanguageVersion.of(17)

minecraft {
// The mappings can be changed at any time, and must be in the following format.
// snapshot_YYYYMMDD Snapshot are built nightly.
// stable_# Stables are built at the discretion of the MCP team.
// Use non-default mappings at your own risk. they may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'official', version: '1.18.2'
// makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.

// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg')

// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')

// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'

mods {
examplemod {
source sourceSets.main
}
}
}

server {
workingDirectory project.file('run')

// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'

mods {
examplemod {
source sourceSets.main
}
}
}

data {
workingDirectory project.file('run')

// Recommended logging data for a userdev environment
property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

// Recommended logging level for the console
property 'forge.logging.console.level', 'debug'

args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/')

mods {
examplemod {
source sourceSets.main
}
}
}
}
}

processResources {
// this will ensure that this task is redone when the versions change.
inputs.property "version", project.mod_version

filesMatching("*/mods.toml") {
expand "version": project.mod_version
}
}

configurations {
embed
compile.extendsFrom(embed)
}

dependencies {
// Specify the version of Minecraft to use, If this is any group other then 'net.minecraft' it is assumed
// that the dep is a ForgeGradle 'patcher' dependency. And it's patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.18.2-40.1.68'

// You may put jars on which you depend on in ./libs or you may define them like so..
// compile "some.group:artifact:version:classifier"
// compile "some.group:artifact:version"

// Real examples
// compile 'com.mod-buildcraft:buildcraft:6.0.8:dev' // adds buildcraft to the dev env
// compile 'com.googlecode.efficient-java-matrix-library:ejml:0.24' // adds ejml to the dev env

// The 'provided' configuration is for optional dependencies that exist at compile-time but might not at runtime.
// provided 'com.mod-buildcraft:buildcraft:6.0.8:dev'

// These dependencies get remapped to your current MCP mappings
// deobf 'com.mod-buildcraft:buildcraft:6.0.8:dev'

// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
embed project(":core")
compileOnly project(":core")
}

// Example for how to get properties into the manifest for reading by the runtime..
jar {
manifest {
attributes([
"Specification-Title" : "telegrambridge",
"Specification-Vendor" : "lionzxy",
"Specification-Version" : "1", // We are version 1 of ourselves
"Implementation-Title" : project.name,
"Implementation-Version" : "${project.mod_version}",
"Implementation-Vendor" : "lionzxy",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
from configurations.embed.collect {
exclude '.classpath'
exclude '.project'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/LICENSE'
exclude 'module-info.class'
exclude 'META-INF/NOTICE'
it.isDirectory() ? it : zipTree(it)
}
}

artifacts {
archives jar
}

curseforge {
apiKey = "${CurseForgeApiToken}"
project {
id = '357271'
changelog = "${last_changelog}"
releaseType = "${mod_state}"
addGameVersion '1.18'
mainArtifact(jar) {
displayName = "TelegramBridge $project.version"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package ru.glitchless.telegrambridge;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.server.ServerStartingEvent;
import net.minecraftforge.event.server.ServerStoppedEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.VersionChecker;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.glitchless.telegrambridge.config.ForgeConfig;
import ru.glitchless.telegrambridge.core.config.TelegramBridgeConfig;
import ru.glitchless.telegrambridge.core.telegramapi.TelegramContext;
import ru.glitchless.telegrambridge.core.telegramapi.TelegramLoop;
import ru.glitchless.telegrambridge.handlers.PlayerList;
import ru.glitchless.telegrambridge.handlers.ToMinecraftResender;
import ru.glitchless.telegrambridge.handlers.ToTelegramEvent;

@Mod(TelegramBridgeMod.MODID)
public class TelegramBridgeMod {
public static final String MODID = "telegrambridge";
public static final String NAME = "Telegram Bridge";
public static final String VERSION = "1.0";
public static final String UPDATE_URL = "https://www.curseforge.com/minecraft/mc-mods/telegram-bridge";

private static final Logger logger = LogManager.getLogger();
private static TelegramContext context;
private static TelegramLoop telegramLoop;

public TelegramBridgeMod() {
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);

ForgeConfig.initConfig(MODID);

MinecraftForge.EVENT_BUS.register(this);
}

public static TelegramContext getContext() {
return context;
}


public void setup(final FMLCommonSetupEvent event) {
context = new TelegramContext(logger);
telegramLoop = new TelegramLoop(context);

context.addListener(new ToMinecraftResender());
context.addListener(new PlayerList());
}

@SubscribeEvent
public void serverStarting(ServerStartingEvent event) {
telegramLoop.start();
if (!TelegramBridgeConfig.relay_level.server_start) {
return;
}
ToTelegramEvent.broadcastToChats(TelegramBridgeConfig.text.server_start);
checkUpdate();
}

private void checkUpdate() {
if (VersionChecker.getResult(ModList.get().getModFileById(MODID).getMods().get(0)).status()
== VersionChecker.Status.OUTDATED) {
ToTelegramEvent.broadcastToChats("There's a new update for the mod! Download it [here](" + UPDATE_URL + ")!");
}
}

@SubscribeEvent
public void serverStopping(ServerStoppedEvent event) {
if (!TelegramBridgeConfig.relay_level.server_stop) {
return;
}
ToTelegramEvent.broadcastToChats(TelegramBridgeConfig.text.server_stop);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package ru.glitchless.telegrambridge.config;

import com.electronwill.nightconfig.core.file.CommentedFileConfig;
import com.electronwill.nightconfig.core.io.WritingMode;
import net.minecraftforge.common.ForgeConfigSpec;
import net.minecraftforge.fml.loading.FMLPaths;
import ru.glitchless.telegrambridge.core.config.AbstractConfig;
import ru.glitchless.telegrambridge.core.config.ConfigPath;
import ru.glitchless.telegrambridge.core.config.ConfigWorkaround;
import ru.glitchless.telegrambridge.core.config.TelegramBridgeConfig;

import javax.annotation.Nullable;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static ru.glitchless.telegrambridge.core.utils.ArrayUtils.isNullOrContainsNull;

public class ForgeConfig implements AbstractConfig {
private final Map<ConfigPath, ForgeConfigSpec.ConfigValue<?>> specs = new HashMap<>();
private final ForgeConfigSpec.Builder builder;

private ForgeConfig(final ForgeConfigSpec.Builder builder) {
this.builder = builder;
}

public static void initConfig(String modid) {
final ForgeConfigSpec.Builder configBuilder = new ForgeConfigSpec.Builder();
final AbstractConfig abstractConfig = new ForgeConfig(configBuilder);
ConfigWorkaround.init(abstractConfig, TelegramBridgeConfig.class);
final ForgeConfigSpec forgeConfigSpec = configBuilder.build();
final Path configPath = FMLPaths.CONFIGDIR.get().resolve(modid + ".toml");

final CommentedFileConfig configData = CommentedFileConfig.builder(configPath)
.sync()
.autosave()
.writingMode(WritingMode.REPLACE)
.build();

configData.load();
forgeConfigSpec.setConfig(configData);
ConfigWorkaround.onReload();
}

@Override
public Object getValue(ConfigPath path) {
final ForgeConfigSpec.ConfigValue<?> configValue = specs.get(path);
if (configValue == null) {
return null;
}
return configValue.get();
}

@Override
public void setList(ConfigPath path, List<?> value, String... comment) {
int level = pushTo(path.getParent());
if (!isNullOrContainsNull(comment)) {
builder.comment(comment);
}
final ForgeConfigSpec.ConfigValue<?> configValue = builder.define(path.getName(), value, Objects::nonNull);
specs.put(path, configValue);
builder.pop(level);
}

@Override
public void setValue(ConfigPath path, Object value, String... comment) {
int level = pushTo(path.getParent());
if (!isNullOrContainsNull(comment)) {
builder.comment(comment);
}
final ForgeConfigSpec.ConfigValue<?> configValue = builder.define(path.getName(), value);
specs.put(path, configValue);

builder.pop(level);
}

private int pushTo(@Nullable ConfigPath path) {
if (path == null) {
return 0;
}
int level = pushTo(path.getParent());
builder.push(path.getName());
return level + 1;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package ru.glitchless.telegrambridge.handlers;

import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.server.ServerLifecycleHooks;
import ru.glitchless.telegrambridge.TelegramBridgeMod;
import ru.glitchless.telegrambridge.core.config.TelegramBridgeConfig;
import ru.glitchless.telegrambridge.core.handlers.IMessageReceiver;
import ru.glitchless.telegrambridge.core.telegramapi.model.MessageObject;

import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PlayerList implements IMessageReceiver {
@Override
public boolean onTelegramObjectMessage(@Nonnull MessageObject messageObject) {
String messageText = messageObject.getText();

if (messageText == null || messageText.length() == 0) {
return false;
}

if (!messageText.startsWith("/players")) {
return false;
}

String chatId = messageObject.getChat().getId().toString();
final List<String> players = getPlayerList();
if (players.isEmpty()) {
TelegramBridgeMod.getContext().sendMessage(chatId, TelegramBridgeConfig.text.player_empty);
return true;
}

final StringBuilder sb = new StringBuilder();
for (int i = 0; i < players.size(); i++) {
sb.append(i + 1).append(". ").append(players.get(i).replace("_", "\\_")).append('\n');
}
final String message = TelegramBridgeConfig.text.player_list
.replace("${endline}", "\n").replace("${playerlist}", sb.toString())
.replace("${playercount}", String.valueOf(players.size()));
TelegramBridgeMod.getContext().sendMessage(chatId, message);
return true;
}

private List<String> getPlayerList() {
MinecraftServer server = ServerLifecycleHooks.getCurrentServer();
if (server == null) {
return Collections.emptyList();
}
final List<String> playerList = new ArrayList<String>();
for (ServerPlayer player : server.getPlayerList().getPlayers()) {
playerList.add(player.getGameProfile().getName());
}

return playerList;
}
}
Loading