├── .github ├── banner.png └── workflows │ ├── build.yml │ └── publish.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src └── main │ ├── resources │ ├── assets │ │ └── f2d │ │ │ └── icon.png │ ├── f2d.mixins.json │ └── fabric.mod.json │ ├── kotlin │ └── su │ │ └── rogi │ │ └── fabric2discord │ │ ├── config │ │ ├── components │ │ │ ├── ChannelCategory.kt │ │ │ ├── MessageStructure.kt │ │ │ ├── MessageField.kt │ │ │ ├── ImageStructure.kt │ │ │ └── MessageBase.kt │ │ ├── SettingsConfig.kt │ │ ├── MessagesConfig.kt │ │ ├── groups │ │ │ ├── StatusSettingsGroup.kt │ │ │ ├── ChatMessagesGroup.kt │ │ │ ├── ServerMessagesGroup.kt │ │ │ ├── IdSettingsGroup.kt │ │ │ └── PlayerMessagesGroup.kt │ │ ├── Configs.kt │ │ └── Config.kt │ │ ├── mixin │ │ ├── PlayerManagerMixinKotlin.kt │ │ ├── PlayerAdvancementTrackerMixinKotlin.kt │ │ ├── ServerPlayerEntityMixinKotlin.kt │ │ ├── ServerPlayNetworkHandlerMixinKotlin.kt │ │ └── MinecraftServerMixinKotlin.kt │ │ ├── utils │ │ ├── PlaceholderUtils.kt │ │ └── MessageUtils.kt │ │ ├── Commands.kt │ │ ├── Fabric2Discord.kt │ │ └── kord │ │ └── KordClient.kt │ └── java │ └── su │ └── rogi │ └── fabric2discord │ └── mixins │ ├── PlayerManagerMixin.java │ ├── ServerPlayNetworkHandlerMixin.java │ ├── MinecraftServerMixin.java │ ├── ServerPlayerEntityMixin.java │ └── PlayerAdvancementTrackerMixin.java ├── .gitignore ├── gradle.properties ├── settings.gradle.kts ├── README.md ├── gradlew.bat ├── LICENSE └── gradlew /.github/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/27rogi/Fabric2Discord/HEAD/.github/banner.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/27rogi/Fabric2Discord/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/main/resources/assets/f2d/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/27rogi/Fabric2Discord/HEAD/src/main/resources/assets/f2d/icon.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/components/ChannelCategory.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.components 2 | 3 | enum class ChannelCategory { 4 | TELEPORTS, 5 | DEATHS, 6 | ADVANCEMENTS, 7 | CONNECTIONS, 8 | SERVER_STATUS, 9 | GAME_CHAT, 10 | SERVER_CHAT, 11 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # gradle 2 | 3 | .gradle/ 4 | build/ 5 | out/ 6 | 7 | # idea 8 | 9 | .idea/ 10 | *.iml 11 | *.ipr 12 | *.iws 13 | 14 | # eclipse 15 | 16 | *.launch 17 | 18 | # vscode 19 | 20 | .settings/ 21 | .vscode/ 22 | bin/ 23 | .classpath 24 | .project 25 | 26 | # macos 27 | 28 | *.DS_STORE 29 | 30 | # fabric 31 | 32 | run/ -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/components/MessageStructure.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.components 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | 5 | @ConfigSerializable 6 | class MessageStructure ( 7 | var body: String? = null, 8 | var header: String? = null, 9 | var footer: String? = null 10 | ) -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/components/MessageField.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.components 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | 5 | @ConfigSerializable 6 | open class MessageField { 7 | open var name: String = "name" 8 | open var value: String = "value" 9 | open var inline: Boolean? = false 10 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/components/ImageStructure.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.components 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | 5 | @ConfigSerializable 6 | class ImageStructure ( 7 | var thumbnail: String? = null, 8 | var image: String? = null, 9 | var header: String? = null, 10 | var footer: String? = null 11 | ) -------------------------------------------------------------------------------- /src/main/resources/f2d.mixins.json: -------------------------------------------------------------------------------- 1 | { 2 | "required": true, 3 | "minVersion": "0.8", 4 | "package": "su.rogi.fabric2discord.mixins", 5 | "compatibilityLevel": "JAVA_21", 6 | "mixins": [ 7 | ], 8 | "client": [ 9 | ], 10 | "server": [ 11 | "MinecraftServerMixin", 12 | "PlayerAdvancementTrackerMixin", 13 | "PlayerManagerMixin", 14 | "ServerPlayerEntityMixin", 15 | "ServerPlayNetworkHandlerMixin" 16 | ], 17 | "injectors": { 18 | "defaultRequire": 1 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/SettingsConfig.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | import su.rogi.fabric2discord.config.groups.IdSettingsGroup 5 | import su.rogi.fabric2discord.config.groups.StatusSettingsGroup 6 | 7 | @ConfigSerializable 8 | class SettingsConfig { 9 | var token: String = "" 10 | 11 | var ids = IdSettingsGroup() 12 | var status = StatusSettingsGroup() 13 | 14 | var configVersion = 3 15 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/MessagesConfig.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | import su.rogi.fabric2discord.config.groups.ChatMessagesGroup 5 | import su.rogi.fabric2discord.config.groups.PlayerMessagesGroup 6 | import su.rogi.fabric2discord.config.groups.ServerMessagesGroup 7 | 8 | @ConfigSerializable 9 | class MessagesConfig { 10 | var server = ServerMessagesGroup() 11 | var chat = ChatMessagesGroup() 12 | var player = PlayerMessagesGroup() 13 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/groups/StatusSettingsGroup.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.groups 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | 5 | @ConfigSerializable 6 | class StatusSettingsGroup { 7 | var enabled: Boolean = true 8 | 9 | var type: String = "DO_NOT_DISTURB" 10 | 11 | var action: String = "PLAYING" 12 | 13 | var url: String = "minecraft.net" 14 | 15 | var interval: Int = 1 16 | 17 | var variants: Array = arrayOf("Fabric", "with %server:online% dudes", "in %world:name%") 18 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Done to increase the memory available to gradle. 2 | org.gradle.jvmargs=-Xmx4G 3 | org.gradle.parallel=true 4 | kotlin.code.style=official 5 | maven_group=su.rogi 6 | archives_base_name=fabric2discord 7 | 8 | # Fabric Properties 9 | # check these on https://fabricmc.net/develop 10 | minecraft_version=1.21 11 | yarn_mappings=1.21+build.7 12 | loader_version=0.15.11 13 | loom_version=1.7-SNAPSHOT 14 | 15 | # Mod Properties 16 | mod_version=3.1.1 17 | minecraft_version_group=1.21 18 | 19 | # Dependencies 20 | fabric_api_version=0.100.4+1.21 21 | fabric_kotlin_version=1.11.0+kotlin.2.0.0 22 | placeholder_api_version=2.4.0+1.21 23 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "Fabric2Discord" 2 | pluginManagement { 3 | repositories { 4 | maven("https://maven.fabricmc.net/") { 5 | name = "Fabric" 6 | } 7 | mavenCentral() 8 | gradlePluginPortal() 9 | } 10 | 11 | val loom_version: String by settings 12 | val fabric_kotlin_version: String by settings 13 | plugins { 14 | id("fabric-loom") version loom_version 15 | id("org.jetbrains.kotlin.jvm") version 16 | fabric_kotlin_version 17 | .split("+kotlin.")[1] // Grabs the sentence after `+kotlin.` 18 | .split("+")[0] // Ensures sentences like `+build.1` are ignored 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/Configs.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config 2 | 3 | import java.nio.file.Path 4 | 5 | object Configs { 6 | lateinit var SETTINGS: Config 7 | lateinit var MESSAGES: Config 8 | 9 | fun register() { 10 | SETTINGS = Config(SettingsConfig::class.java, Path.of("f2d", "settings.conf")) 11 | MESSAGES = Config(MessagesConfig::class.java, Path.of("f2d", "messages.conf")) 12 | 13 | if (SETTINGS.entries.configVersion != 3) { 14 | throw Error(""" 15 | Your configuration (v${SETTINGS.entries.configVersion}) is not compatible with this mod version (v3)! 16 | Visit https://github.com/rogi27/Fabric2Discord/wiki/Configuration for more information. 17 | """.trimIndent()) 18 | } 19 | } 20 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/mixin/PlayerManagerMixinKotlin.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixin 2 | 3 | import net.minecraft.server.network.ServerPlayerEntity 4 | import su.rogi.fabric2discord.config.Configs 5 | import su.rogi.fabric2discord.config.components.ChannelCategory 6 | import su.rogi.fabric2discord.utils.MessageUtils 7 | 8 | object PlayerManagerMixinKotlin { 9 | fun onPlayerConnect(player: ServerPlayerEntity) { 10 | if (!Configs.MESSAGES.entries.player.joined.enabled) return 11 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.CONNECTIONS)) { 12 | Configs.MESSAGES.entries.player.joined.let { 13 | suppressNotifications = it.silent 14 | embeds = mutableListOf(it.getEmbed(player = player)) 15 | } 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/resources/fabric.mod.json: -------------------------------------------------------------------------------- 1 | { 2 | "schemaVersion": 1, 3 | "id": "f2d", 4 | "version": "${version}", 5 | "name": "Fabric2Discord", 6 | "description": "Link your Fabric server and Discord with ease!", 7 | "authors": [ 8 | "27rogi" 9 | ], 10 | "contact": { 11 | "homepage": "https://fabricmc.net/", 12 | "sources": "https://github.com/FabricMC/fabric-example-mod" 13 | }, 14 | "license": "CC0-1.0", 15 | "icon": "assets/f2d/icon.png", 16 | "environment": "server", 17 | "entrypoints": { 18 | "main": [ 19 | { 20 | "adapter": "kotlin", 21 | "value": "su.rogi.fabric2discord.Fabric2Discord" 22 | } 23 | ] 24 | }, 25 | "mixins": [ 26 | "f2d.mixins.json" 27 | ], 28 | "depends": { 29 | "fabricloader": ">=0.8.7", 30 | "fabric-language-kotlin": ">=1.8.0+kotlin.1.7.0" 31 | } 32 | } -------------------------------------------------------------------------------- /src/main/java/su/rogi/fabric2discord/mixins/PlayerManagerMixin.java: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixins; 2 | 3 | import net.minecraft.network.ClientConnection; 4 | import net.minecraft.server.PlayerManager; 5 | import net.minecraft.server.network.ConnectedClientData; 6 | import net.minecraft.server.network.ServerPlayerEntity; 7 | import org.spongepowered.asm.mixin.Mixin; 8 | import org.spongepowered.asm.mixin.injection.At; 9 | import org.spongepowered.asm.mixin.injection.Inject; 10 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 11 | import su.rogi.fabric2discord.mixin.PlayerManagerMixinKotlin; 12 | 13 | @Mixin(PlayerManager.class) 14 | public abstract class PlayerManagerMixin { 15 | @Inject(method = "onPlayerConnect", at = @At("HEAD")) 16 | private void onPlayerConnect(ClientConnection connection, ServerPlayerEntity player, ConnectedClientData clientData, CallbackInfo ci) { 17 | PlayerManagerMixinKotlin.INSTANCE.onPlayerConnect(player); 18 | } 19 | } -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: 🏗️ Make Developer Build 2 | on: 3 | pull_request: 4 | push: 5 | paths: 6 | - '**.java' 7 | - '**.kt' 8 | - '**.properties' 9 | - '**.json' 10 | - '**.gradle' 11 | - '**.gradlew' 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: 📂 Checkout repo 18 | uses: actions/checkout@v4 19 | - name: 📂 Validate gradle wrapper 20 | uses: gradle/wrapper-validation-action@v1 21 | - name: 🔽 Install JDK 17 22 | uses: actions/setup-java@v4 23 | with: 24 | java-version: 17 25 | distribution: 'zulu' 26 | - name: 📂 Make gradle wrapper executable 27 | run: chmod +x ./gradlew 28 | - name: 🏗️ Build with Gradle 29 | uses: gradle/gradle-build-action@v3 30 | with: 31 | gradle-version: current 32 | arguments: build --stacktrace 33 | - name: ⬆️ Upload artifacts 34 | uses: actions/upload-artifact@v4 35 | with: 36 | name: dev-build 37 | path: build/libs/ 38 | -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/groups/ChatMessagesGroup.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.groups 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | import org.spongepowered.configurate.objectmapping.meta.Comment 5 | import su.rogi.fabric2discord.config.components.ImageStructure 6 | import su.rogi.fabric2discord.config.components.MessageBase 7 | import su.rogi.fabric2discord.config.components.MessageStructure 8 | 9 | @ConfigSerializable 10 | class ChatMessagesGroup { 11 | @Comment("Supported placeholders: %discord_nickname% (fallback to username if not present), %discord_username%") 12 | var format = "[F2D] %discord_nickname%: " 13 | var formattedAttachment = "[%attachment_name%]" 14 | 15 | var message = MessageBase().apply { 16 | timestamp = true 17 | text = MessageStructure( 18 | body = "%message%", 19 | header = "%player:name%", 20 | ) 21 | images = ImageStructure( 22 | header = "https://minotar.net/armor/bust/%player:name%/100.png", 23 | ) 24 | color = "#01cdfe" 25 | } 26 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/groups/ServerMessagesGroup.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.groups 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | import su.rogi.fabric2discord.config.components.ImageStructure 5 | import su.rogi.fabric2discord.config.components.MessageBase 6 | import su.rogi.fabric2discord.config.components.MessageStructure 7 | 8 | @ConfigSerializable 9 | class ServerMessagesGroup { 10 | var started = MessageBase().apply { 11 | enabled = true 12 | timestamp = true 13 | text = MessageStructure( 14 | body = "It's %world:time% (day %world:day%) in the world.", 15 | header = ":white_check_mark: Server started!", 16 | ) 17 | images = ImageStructure( 18 | image = "https://source.unsplash.com/600x400/?purple,nature", 19 | ) 20 | color = "#4ae485" 21 | } 22 | 23 | var stopped = MessageBase().apply { 24 | enabled = true 25 | timestamp = true 26 | text = MessageStructure( 27 | body = ":stop_sign: Server stopped!", 28 | footer = "You can wait a little for it to start again!", 29 | ) 30 | images = ImageStructure( 31 | image = "https://source.unsplash.com/600x400/?stop", 32 | ) 33 | color = "#FF2337" 34 | } 35 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/utils/PlaceholderUtils.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.utils 2 | 3 | import eu.pb4.placeholders.api.PlaceholderResult 4 | import eu.pb4.placeholders.api.Placeholders 5 | import net.minecraft.util.Identifier 6 | 7 | object PlaceholderUtils { 8 | fun registerPlaceholders() { 9 | Placeholders.register(Identifier.of("player", "uuid")) { handler, _ -> 10 | if (handler.hasPlayer()) { 11 | return@register PlaceholderResult.value(handler.player!!.uuidAsString) 12 | } else { 13 | return@register PlaceholderResult.invalid("No player!") 14 | } 15 | } 16 | Placeholders.register(Identifier.of("player", "world")) { handler, _ -> 17 | if (handler.hasPlayer()) { 18 | return@register PlaceholderResult.value(handler.player!!.world.registryKey.value.toString()) 19 | } else { 20 | return@register PlaceholderResult.invalid("No player!") 21 | } 22 | } 23 | Placeholders.register(Identifier.of("player", "world_name")) { handler, _ -> 24 | if (handler.hasPlayer()) { 25 | return@register PlaceholderResult.value(handler.player!!.world.registryKey.value.path) 26 | } else { 27 | return@register PlaceholderResult.invalid("No player!") 28 | } 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: 🍀 Publish Release 2 | on: 3 | release: 4 | types: [prereleased, released] 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: 📂 Checkout repo 11 | uses: actions/checkout@v2 12 | - name: 📂 Validate gradle wrapper 13 | uses: gradle/wrapper-validation-action@v1 14 | - name: 🔽 Install JDK 17 15 | uses: actions/setup-java@v1 16 | with: 17 | java-version: 17 18 | - name: 📂 Make gradle wrapper executable 19 | run: chmod +x ./gradlew 20 | - name: 🏗️ Build with Gradle 21 | uses: gradle/gradle-build-action@v2 22 | with: 23 | gradle-version: current 24 | arguments: build --stacktrace 25 | - name: 🍀 Publish 26 | uses: Kir-Antipov/mc-publish@v3.3.0 27 | with: 28 | modrinth-id: EyyEnN7W 29 | modrinth-featured: true 30 | modrinth-token: ${{ secrets.MODRINTH_TOKEN }} 31 | curseforge-id: 633292 32 | curseforge-token: ${{ secrets.CURSE_TOKEN }} 33 | files: build/libs/!(*-@(dev|sources|bundle|all)).jar 34 | version: ${{ github.ref_name }} 35 | version-resolver: releases 36 | loaders: | 37 | fabric 38 | quilt 39 | java: | 40 | 17 41 | retry-attempts: 2 42 | retry-delay: 10000 43 | fail-mode: fail -------------------------------------------------------------------------------- /src/main/java/su/rogi/fabric2discord/mixins/ServerPlayNetworkHandlerMixin.java: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixins; 2 | 3 | import net.minecraft.network.DisconnectionInfo; 4 | import net.minecraft.network.message.SignedMessage; 5 | import net.minecraft.server.network.ServerPlayerEntity; 6 | import org.spongepowered.asm.mixin.Mixin; 7 | import org.spongepowered.asm.mixin.Shadow; 8 | import org.spongepowered.asm.mixin.injection.At; 9 | import org.spongepowered.asm.mixin.injection.Inject; 10 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 11 | import su.rogi.fabric2discord.mixin.ServerPlayNetworkHandlerMixinKotlin; 12 | 13 | @Mixin(net.minecraft.server.network.ServerPlayNetworkHandler.class) 14 | public abstract class ServerPlayNetworkHandlerMixin { 15 | @Shadow 16 | public ServerPlayerEntity player; 17 | 18 | @Inject(method = "handleDecoratedMessage", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;getPlayerManager()Lnet/minecraft/server/PlayerManager;")) 19 | private void onPlayerMessageEvent(SignedMessage signedMessage, CallbackInfo ci) { 20 | ServerPlayNetworkHandlerMixinKotlin.INSTANCE.onPlayerMessageEvent(player, signedMessage); 21 | } 22 | 23 | @Inject(method = "onDisconnected", at = @At("HEAD")) 24 | private void remove(DisconnectionInfo info, CallbackInfo ci) { 25 | ServerPlayNetworkHandlerMixinKotlin.INSTANCE.remove(player, info.reason()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/su/rogi/fabric2discord/mixins/MinecraftServerMixin.java: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixins; 2 | 3 | import net.minecraft.server.MinecraftServer; 4 | import net.minecraft.server.PlayerManager; 5 | import org.spongepowered.asm.mixin.Mixin; 6 | import org.spongepowered.asm.mixin.Shadow; 7 | import org.spongepowered.asm.mixin.Unique; 8 | import org.spongepowered.asm.mixin.injection.At; 9 | import org.spongepowered.asm.mixin.injection.Inject; 10 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 11 | import su.rogi.fabric2discord.mixin.MinecraftServerMixinKotlin; 12 | 13 | import java.util.Timer; 14 | 15 | @Mixin(MinecraftServer.class) 16 | public abstract class MinecraftServerMixin { 17 | @Unique 18 | Timer timer = new Timer(); 19 | 20 | @Shadow 21 | private PlayerManager playerManager; 22 | 23 | @Inject(at = @At(value = "INVOKE", target = "Lnet/minecraft/server/MinecraftServer;createMetadata()Lnet/minecraft/server/ServerMetadata;", ordinal = 0), method = "runServer") 24 | private void afterSetupServer(CallbackInfo info) { 25 | MinecraftServerMixinKotlin.INSTANCE.afterSetupServer(playerManager, timer); 26 | } 27 | 28 | @Inject(at = @At(value = "INVOKE", shift = At.Shift.BEFORE, target = "Lnet/minecraft/server/ServerNetworkIo;stop()V", ordinal = 0), method = "shutdown") 29 | private void afterShutdownServer(CallbackInfo info) { 30 | MinecraftServerMixinKotlin.INSTANCE.afterShutdownServer(timer); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/Commands.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord 2 | 3 | import com.mojang.brigadier.context.CommandContext 4 | import com.mojang.brigadier.exceptions.CommandSyntaxException 5 | import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback 6 | import net.minecraft.server.command.CommandManager 7 | import net.minecraft.server.command.ServerCommandSource 8 | import net.minecraft.text.Style 9 | import net.minecraft.text.Text 10 | import net.minecraft.text.TextColor 11 | import su.rogi.fabric2discord.config.Configs 12 | 13 | object Commands { 14 | fun register() { 15 | CommandRegistrationCallback.EVENT.register(CommandRegistrationCallback { dispatcher, _, _ -> 16 | dispatcher.register(CommandManager.literal("f2d") 17 | .requires { server -> server.hasPermissionLevel(4) } 18 | .then(CommandManager.literal("reload") 19 | .executes(Commands::reload) 20 | )) 21 | }) 22 | } 23 | 24 | @Throws(CommandSyntaxException::class) 25 | fun reload(context: CommandContext): Int { 26 | Configs.SETTINGS.load() 27 | Configs.MESSAGES.load() 28 | context.source.sendFeedback( 29 | { Text 30 | .of("Configuration files reloaded") 31 | .copy() 32 | .setStyle(Style.EMPTY.withColor(TextColor.fromRgb(0x19422814))) 33 | }, 34 | false 35 | ) 36 | return 1 37 | } 38 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/mixin/PlayerAdvancementTrackerMixinKotlin.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixin 2 | 3 | import net.minecraft.advancement.Advancement 4 | import net.minecraft.server.network.ServerPlayerEntity 5 | import su.rogi.fabric2discord.config.Configs 6 | import su.rogi.fabric2discord.config.components.ChannelCategory 7 | import su.rogi.fabric2discord.utils.MessageUtils 8 | 9 | object PlayerAdvancementTrackerMixinKotlin { 10 | fun grantCriterion(owner: ServerPlayerEntity, advancement: Advancement, isGameruleEnabled: Boolean) { 11 | if (!Configs.MESSAGES.entries.player.gotAdvancement.enabled) return 12 | if (!isGameruleEnabled && !Configs.MESSAGES.entries.player.gotAdvancement.ignoresGamerule) return 13 | 14 | val replacements = hashMapOf() 15 | if (advancement.display.isPresent and advancement.parent.isPresent) { 16 | val display = advancement.display.get() 17 | replacements["advancement_name"] = display.title.string 18 | replacements["advancement_description"] = display.description.string 19 | replacements["advancement_id"] = advancement.parent.get().path 20 | } 21 | 22 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.ADVANCEMENTS)) { 23 | Configs.MESSAGES.entries.player.gotAdvancement.let { 24 | suppressNotifications = it.silent 25 | embeds = mutableListOf(it.getEmbed(replacements, owner)) 26 | } 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /src/main/java/su/rogi/fabric2discord/mixins/ServerPlayerEntityMixin.java: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixins; 2 | 3 | import com.mojang.authlib.GameProfile; 4 | import net.minecraft.entity.damage.DamageSource; 5 | import net.minecraft.entity.player.PlayerEntity; 6 | import net.minecraft.server.network.ServerPlayerEntity; 7 | import net.minecraft.server.world.ServerWorld; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.injection.At; 10 | import org.spongepowered.asm.mixin.injection.Inject; 11 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; 12 | import su.rogi.fabric2discord.mixin.ServerPlayerEntityMixinKotlin; 13 | 14 | import java.util.Objects; 15 | 16 | @Mixin(ServerPlayerEntity.class) 17 | public abstract class ServerPlayerEntityMixin extends PlayerEntity { 18 | public ServerPlayerEntityMixin(ServerWorld world, GameProfile profile) { 19 | super(world, world.getSpawnPos(), world.getSpawnAngle(), profile); 20 | } 21 | 22 | @Inject(method = "onDeath(Lnet/minecraft/entity/damage/DamageSource;)V", at = @At("HEAD")) 23 | private void onDeath(DamageSource source, CallbackInfo ci) { 24 | ServerPlayerEntityMixinKotlin.INSTANCE.onDeath(Objects.requireNonNull(this.getCommandSource().getPlayer()), source, getDamageTracker()); 25 | } 26 | 27 | @Inject(method = "worldChanged", at = @At("TAIL")) 28 | private void worldChanged(ServerWorld origin, CallbackInfo ci) { 29 | ServerPlayerEntityMixinKotlin.INSTANCE.worldChanged(Objects.requireNonNull(this.getCommandSource().getPlayer()), origin); 30 | } 31 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/Fabric2Discord.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord 2 | 3 | import kotlinx.coroutines.CoroutineScope 4 | import kotlinx.coroutines.Dispatchers 5 | import net.fabricmc.api.EnvType 6 | import net.fabricmc.api.ModInitializer 7 | import net.fabricmc.loader.api.FabricLoader 8 | import net.fabricmc.loader.api.metadata.ModMetadata 9 | import net.minecraft.server.MinecraftServer 10 | import org.apache.logging.log4j.LogManager 11 | import org.apache.logging.log4j.Logger 12 | import su.rogi.fabric2discord.config.Configs 13 | import su.rogi.fabric2discord.kord.KordClient 14 | import su.rogi.fabric2discord.utils.PlaceholderUtils 15 | 16 | class Fabric2Discord : ModInitializer { 17 | 18 | override fun onInitialize() { 19 | logger.info("Fabric2Discord ${metadata.version} by ${metadata.authors.joinToString(",") { it.name }}") 20 | if (FabricLoader.getInstance().environmentType == EnvType.CLIENT) { 21 | logger.warn("This mod was developed for server-side use and may cause unexpected behaviour on client.") 22 | } 23 | 24 | PlaceholderUtils.registerPlaceholders() 25 | Configs.register() 26 | Commands.register() 27 | KordClient.create() 28 | KordClient.registerWebhook() 29 | } 30 | 31 | companion object { 32 | var minecraftServer: MinecraftServer? = null 33 | val scope = CoroutineScope(Dispatchers.IO) 34 | val metadata: ModMetadata = FabricLoader.getInstance().getModContainer("f2d").get().metadata 35 | val logger: Logger = LogManager.getLogger(metadata.name) 36 | } 37 | } -------------------------------------------------------------------------------- /src/main/java/su/rogi/fabric2discord/mixins/PlayerAdvancementTrackerMixin.java: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixins; 2 | 3 | import net.minecraft.advancement.Advancement; 4 | import net.minecraft.advancement.AdvancementEntry; 5 | import net.minecraft.advancement.PlayerAdvancementTracker; 6 | import net.minecraft.server.network.ServerPlayerEntity; 7 | import net.minecraft.world.GameRules; 8 | import org.spongepowered.asm.mixin.Mixin; 9 | import org.spongepowered.asm.mixin.Shadow; 10 | import org.spongepowered.asm.mixin.injection.At; 11 | import org.spongepowered.asm.mixin.injection.Inject; 12 | import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; 13 | import su.rogi.fabric2discord.mixin.PlayerAdvancementTrackerMixinKotlin; 14 | 15 | @Mixin(PlayerAdvancementTracker.class) 16 | public abstract class PlayerAdvancementTrackerMixin { 17 | @Shadow 18 | private ServerPlayerEntity owner; 19 | 20 | @Inject(method = "grantCriterion", at = @At(value = "INVOKE", shift = At.Shift.AFTER, target = "Lnet/minecraft/advancement/AdvancementRewards;apply(Lnet/minecraft/server/network/ServerPlayerEntity;)V")) 21 | private void grantCriterion(AdvancementEntry advancementEntry, String criterionName, CallbackInfoReturnable cir) { 22 | Advancement advancement = advancementEntry.value(); 23 | if (advancement.display().isPresent() && advancement.display().get().shouldAnnounceToChat()) { 24 | PlayerAdvancementTrackerMixinKotlin.INSTANCE.grantCriterion(owner, advancement, this.owner.getServerWorld().getGameRules().getBoolean(GameRules.ANNOUNCE_ADVANCEMENTS)); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/groups/IdSettingsGroup.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.groups 2 | 3 | import dev.kord.common.entity.Snowflake 4 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 5 | import org.spongepowered.configurate.objectmapping.meta.Comment 6 | import su.rogi.fabric2discord.config.components.ChannelCategory 7 | 8 | @ConfigSerializable 9 | class IdSettingsGroup { 10 | @Comment( 11 | "List of channels with broadcast categories\n" + 12 | "Available categories: TELEPORTS, DEATHS, ADVANCEMENTS, CONNECTIONS, SERVER_STATUS, GAME_CHAT, SERVER_CHAT\n" + 13 | "Example: 1058047687309664276: [CHAT, SERVER_STATUS]" 14 | ) 15 | var channels: HashMap> = hashMapOf() 16 | 17 | var webhooks: Array? = arrayOf() 18 | 19 | fun getByCategories(categories: List): List? { 20 | if (channels.isEmpty()) return null 21 | val filtered = channels.filter { 22 | val intersect = categories intersect it.value.toSet() 23 | return@filter intersect.isNotEmpty() 24 | } 25 | if (filtered.isEmpty()) return null 26 | return filtered.keys.map { Snowflake(it) } 27 | } 28 | 29 | fun getByCategory(category: ChannelCategory): List? { 30 | if (channels.isEmpty()) return null 31 | val filtered = channels.filter { it.value.contains(category) } 32 | if (filtered.isEmpty()) return null 33 | return filtered.keys.map { Snowflake(it) } 34 | } 35 | 36 | fun getWebhooks(): List? { 37 | return webhooks?.map { Snowflake(it) } 38 | } 39 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | # Fabric2Discord 5 | ### Link your Fabric server and Discord with ease! 6 |
7 | 8 | # 🍀 Version 3.0.0 9 | Project has been fully rewritten and major parts are changed which results in broken compatability for older configs. Wiki articles may have old information about configuration, this will be fixed soon. 10 | 11 | # 📂 Version Support 12 | Due to lack of free time and skills the support is limited to latest 2 major releases with latest minor version being supported. 13 | 14 | | Support | Minecraft | 15 | |--------------------|-------------| 16 | | ✅ Active, Primary | 1.20.4 | 17 | | ✅ Active, Backport | 1.19.4 | 18 | | ❌ Outdated | 1.20-1.20.3 | 19 | | ❌ Discontinued | 1.18.2 | 20 | 21 | # ✨ Features 22 | - [x] Based on **Kotlin** and **kord** 23 | - [x] Ability to choose messages per channel 24 | - [x] Ability to change bot status 25 | - [x] Customizable messages 26 | - [x] [Supports advanced formatting](https://github.com/Patbox/TextPlaceholderAPI) 27 | - [x] Embed support 28 | - [x] Webhook support 29 | 30 | # 📖 Getting Started 31 | I wrote few helpful articles about this mod, so if you need help you can visit [wiki](https://github.com/rogi27/Fabric2Discord/wiki#-getting-started=). 32 | 33 | # 💖 Used Libraries 34 | - Fabric Command API 35 | - Fabric Kotlin 36 | - [TextPlaceholderAPI](https://github.com/Patbox/TextPlaceholderAPI) by [Patbox](https://github.com/Patbox) 37 | - [Configurate](https://github.com/SpongePowered/Configurate) by [Lortseam](https://gitlab.com/Lortseam) 38 | - [kord](https://github.com/kordlib/kord) 39 | - emoji-java 40 | 41 | # 🖍️ Future plans 42 | - [ ] 🏃‍♂️ Execution of commands via chat 43 | - [ ] Rework tags system to be more flexible 44 | - [ ] Fully handle server shutdown 45 | - [ ] Server console 46 | - [ ] Account linking -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/mixin/ServerPlayerEntityMixinKotlin.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixin 2 | 3 | import net.minecraft.entity.damage.DamageSource 4 | import net.minecraft.entity.damage.DamageTracker 5 | import net.minecraft.server.network.ServerPlayerEntity 6 | import net.minecraft.server.world.ServerWorld 7 | import su.rogi.fabric2discord.config.Configs 8 | import su.rogi.fabric2discord.config.components.ChannelCategory 9 | import su.rogi.fabric2discord.utils.MessageUtils 10 | 11 | object ServerPlayerEntityMixinKotlin { 12 | fun onDeath(player: ServerPlayerEntity, source: DamageSource, tracker: DamageTracker) { 13 | if (!Configs.MESSAGES.entries.player.died.enabled) return 14 | 15 | val replacements = hashMapOf() 16 | replacements["death_message"] = tracker.deathMessage.string 17 | replacements["death_by"] = source.name 18 | 19 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.DEATHS)) { 20 | Configs.MESSAGES.entries.player.died.let { 21 | suppressNotifications = it.silent 22 | embeds = mutableListOf(it.getEmbed(replacements, player)) 23 | } 24 | } 25 | } 26 | 27 | fun worldChanged(player: ServerPlayerEntity, origin: ServerWorld) { 28 | if (!Configs.MESSAGES.entries.player.teleported.enabled) return 29 | 30 | val replacements = hashMapOf() 31 | replacements["world_origin"] = origin.registryKey.value.toString() 32 | replacements["world_origin_id"] = origin.registryKey.value.path 33 | 34 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.TELEPORTS)) { 35 | Configs.MESSAGES.entries.player.teleported.let { 36 | suppressNotifications = it.silent 37 | embeds = mutableListOf(it.getEmbed(replacements, player)) 38 | } 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/Config.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config 2 | 3 | import net.fabricmc.loader.api.FabricLoader 4 | import org.spongepowered.configurate.CommentedConfigurationNode 5 | import org.spongepowered.configurate.hocon.HoconConfigurationLoader 6 | import su.rogi.fabric2discord.Fabric2Discord 7 | import java.nio.file.Path 8 | import kotlin.system.exitProcess 9 | 10 | open class Config( 11 | private val type: Class, 12 | private val path: Path, 13 | private val header: String? = null 14 | ) { 15 | private var loader: HoconConfigurationLoader = HoconConfigurationLoader.builder() 16 | .path(FabricLoader.getInstance().configDir.resolve(path)) 17 | .defaultOptions { it.header(header) } 18 | .build() 19 | private var node: CommentedConfigurationNode = loader.load() 20 | var entries: V = checkNotNull(node[type]) { 21 | "Unable to get configuration node for $type" 22 | } 23 | 24 | init { 25 | save() 26 | } 27 | 28 | fun load(): Config { 29 | try { 30 | node = loader.load() 31 | entries = node[type]!! 32 | } catch (e: Exception) { 33 | Fabric2Discord.logger.error("An error occurred while loading configuration for ${this::class.java.name}: ${e.message}") 34 | if (e.cause != null) { 35 | e.cause!!.printStackTrace() 36 | } 37 | exitProcess(1) 38 | } 39 | return this 40 | } 41 | 42 | fun save(): Config { 43 | try { 44 | node[type] = entries 45 | loader.save(node) 46 | } catch (e: Exception) { 47 | Fabric2Discord.logger.error("An error occurred while saving configuration for ${this::class.java.name}: ${e.message}") 48 | if (e.cause != null) { 49 | e.cause!!.printStackTrace() 50 | } 51 | exitProcess(1) 52 | } 53 | return this 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/mixin/ServerPlayNetworkHandlerMixinKotlin.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixin 2 | 3 | import net.minecraft.network.message.SignedMessage 4 | import net.minecraft.server.network.ServerPlayerEntity 5 | import net.minecraft.text.Text 6 | import su.rogi.fabric2discord.Fabric2Discord 7 | import su.rogi.fabric2discord.config.Configs 8 | import su.rogi.fabric2discord.config.components.ChannelCategory 9 | import su.rogi.fabric2discord.kord.KordClient 10 | import su.rogi.fabric2discord.utils.MessageUtils 11 | 12 | object ServerPlayNetworkHandlerMixinKotlin { 13 | fun onPlayerMessageEvent(player: ServerPlayerEntity, signedMessage: SignedMessage) { 14 | if (!Configs.MESSAGES.entries.chat.message.enabled) return 15 | 16 | val embed = Configs.MESSAGES.entries.chat.message.getEmbed(hashMapOf(Pair("message", signedMessage.content.string)), player) 17 | if (Configs.SETTINGS.entries.ids.getWebhooks() != null) { 18 | if (embed.author == null) { 19 | Fabric2Discord.logger.warn("Unable to send message via webhook because field [text.header/images.header] of embed (messages.chat.message) is missing!") 20 | return 21 | } 22 | KordClient.executeWebhook( 23 | embed.author!!.name!!, 24 | embed.author!!.icon!!, 25 | embed.description!!, 26 | ) 27 | return 28 | } 29 | 30 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.GAME_CHAT)) { 31 | embeds = mutableListOf(embed) 32 | } 33 | } 34 | 35 | fun remove(player: ServerPlayerEntity, reason: Text) { 36 | if (!Configs.MESSAGES.entries.player.left.enabled) return 37 | 38 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.CONNECTIONS)) { 39 | Configs.MESSAGES.entries.player.left.let { 40 | suppressNotifications = it.silent 41 | embeds = mutableListOf(it.getEmbed(hashMapOf(Pair("leave_reason", reason.string)), player)) 42 | } 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/groups/PlayerMessagesGroup.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.groups 2 | 3 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 4 | import su.rogi.fabric2discord.config.components.ImageStructure 5 | import su.rogi.fabric2discord.config.components.MessageBase 6 | import su.rogi.fabric2discord.config.components.MessageStructure 7 | 8 | @ConfigSerializable 9 | class PlayerMessagesGroup { 10 | var joined = MessageBase().apply { 11 | text = MessageStructure( 12 | header = "%player:name% has joined", 13 | ) 14 | images = ImageStructure( 15 | header = "https://minotar.net/cube/%player:name%/100.png", 16 | ) 17 | color = "#4ae485" 18 | } 19 | 20 | var left = MessageBase().apply { 21 | text = MessageStructure( 22 | header = "%player:name% has left", 23 | footer = "Time played: %player:playtime%" 24 | ) 25 | images = ImageStructure( 26 | header = "https://minotar.net/cube/%player:name%/100.png", 27 | ) 28 | color = "#FF2337" 29 | } 30 | 31 | // TODO: find a better workaround to include special properties 32 | @ConfigSerializable 33 | class AdvancementMessageBase : MessageBase() { 34 | var ignoresGamerule: Boolean = true 35 | } 36 | 37 | var gotAdvancement = AdvancementMessageBase().apply { 38 | text = MessageStructure( 39 | header = "%player:name% got %advancement_name%", 40 | body = "%advancement_description%" 41 | ) 42 | color = "#ffff66" 43 | } 44 | 45 | var died = MessageBase().apply { 46 | timestamp = true 47 | text = MessageStructure( 48 | body = ":skull: got killed by %death_by%", 49 | footer = "%death_message%" 50 | ) 51 | images = ImageStructure( 52 | image = "https://minotar.net/cube/%player:name%/100.png", 53 | thumbnail = "https://minotar.net/cube/%player:uuid%/32.png" 54 | ) 55 | color = "#696969" 56 | } 57 | 58 | var teleported = MessageBase().apply { 59 | timestamp = true 60 | text = MessageStructure( 61 | body = "%player:name% has teleported to %player:world%", 62 | footer = "Previous location is %world_origin%" 63 | ) 64 | images = ImageStructure( 65 | thumbnail = "https://minotar.net/cube/%player:uuid%/32.png" 66 | ) 67 | color = "#b967ff" 68 | } 69 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/config/components/MessageBase.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.config.components 2 | 3 | import dev.kord.rest.builder.message.EmbedBuilder 4 | import kotlinx.datetime.Clock 5 | import net.minecraft.server.MinecraftServer 6 | import net.minecraft.server.network.ServerPlayerEntity 7 | import org.spongepowered.configurate.objectmapping.ConfigSerializable 8 | import su.rogi.fabric2discord.utils.MessageUtils 9 | import su.rogi.fabric2discord.utils.MessageUtils.format 10 | 11 | @ConfigSerializable 12 | open class MessageBase { 13 | open var enabled: Boolean = true 14 | open var silent: Boolean = false 15 | open var timestamp: Boolean = false 16 | open var fields: Array = arrayOf() 17 | 18 | var url: String? = null 19 | var color: String? = null 20 | var text: MessageStructure = MessageStructure() 21 | var images: ImageStructure? = null 22 | 23 | fun getEmbed( 24 | tags: HashMap? = null, 25 | player: ServerPlayerEntity? = null, 26 | server: MinecraftServer? = null 27 | ): EmbedBuilder { 28 | return EmbedBuilder().apply { 29 | if (this@MessageBase.color != null) { 30 | this.color = MessageUtils.toColor(this@MessageBase.color!!) 31 | } 32 | this.timestamp = if (this@MessageBase.timestamp) Clock.System.now() else null 33 | if (this@MessageBase.text.header !== null) { 34 | author { 35 | name = format(this@MessageBase.text.header, tags, server, player)?.string 36 | icon = format(this@MessageBase.images?.header, tags, server, player)?.string 37 | url = format(this@MessageBase.url, tags, server, player)?.string 38 | } 39 | } else this.url = this@MessageBase.url 40 | this.description = format(text.body, tags, server, player)?.string 41 | if (this@MessageBase.fields.isNotEmpty()) { 42 | for (field in this@MessageBase.fields) { 43 | this.field { 44 | this.name = checkNotNull(format(field.name, tags, server, player)?.string) 45 | this.value = checkNotNull(format(field.value, tags, server, player)?.string) 46 | this.inline = field.inline 47 | } 48 | } 49 | } 50 | if (this@MessageBase.text.footer != null) { 51 | this@apply.footer { 52 | this.text = format(this@MessageBase.text.footer, tags, server, player)?.string!! 53 | this.icon = format(this@MessageBase.images?.footer, tags, server, player)?.string 54 | } 55 | } 56 | this.image = this@MessageBase.images?.image 57 | if (this@MessageBase.images?.thumbnail != null) { 58 | this.thumbnail { 59 | this@thumbnail.url = format(this@MessageBase.images?.thumbnail!!, tags, server, player)?.string!! 60 | } 61 | } 62 | } 63 | } 64 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 48 | echo. 49 | echo Please set the JAVA_HOME variable in your environment to match the 50 | echo location of your Java installation. 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 62 | echo. 63 | echo Please set the JAVA_HOME variable in your environment to match the 64 | echo location of your Java installation. 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/mixin/MinecraftServerMixinKotlin.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.mixin 2 | 3 | import dev.kord.common.entity.PresenceStatus 4 | import kotlinx.coroutines.runBlocking 5 | import net.minecraft.server.PlayerManager 6 | import su.rogi.fabric2discord.Fabric2Discord 7 | import su.rogi.fabric2discord.config.Configs 8 | import su.rogi.fabric2discord.config.components.ChannelCategory 9 | import su.rogi.fabric2discord.kord.KordClient 10 | import su.rogi.fabric2discord.utils.MessageUtils 11 | import java.util.* 12 | import java.util.concurrent.TimeUnit 13 | 14 | object MinecraftServerMixinKotlin { 15 | fun afterSetupServer(playerManager: PlayerManager, timer: Timer) { 16 | Fabric2Discord.minecraftServer = playerManager.server 17 | 18 | if (Configs.MESSAGES.entries.server.started.enabled) { 19 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.SERVER_STATUS)) { 20 | Configs.MESSAGES.entries.server.started.let { 21 | suppressNotifications = it.silent 22 | embeds = mutableListOf(it.getEmbed(null, server = Fabric2Discord.minecraftServer)) 23 | } 24 | } 25 | } 26 | 27 | Fabric2Discord.logger.info("Enabled sync between game chat and Discord!") 28 | 29 | if (!Configs.SETTINGS.entries.status.enabled) return 30 | timer.schedule(object : TimerTask() { 31 | override fun run() { 32 | val presence = 33 | MessageUtils.format(Configs.SETTINGS.entries.status.variants.random(), server = Fabric2Discord.minecraftServer)?.string 34 | ?: return 35 | runBlocking { KordClient.kord.editPresence { 36 | when (Configs.SETTINGS.entries.status.type) { 37 | "IDLE" -> this.status = PresenceStatus.Idle 38 | "DO_NOT_DISTURB" -> this.status = PresenceStatus.DoNotDisturb 39 | "INVISIBLE" -> this.status = PresenceStatus.Invisible 40 | "OFFLINE" -> this.status = PresenceStatus.Offline 41 | else -> this.status = PresenceStatus.Online 42 | } 43 | when (Configs.SETTINGS.entries.status.action) { 44 | "LISTENING" -> this.listening(presence) 45 | "COMPETING" -> this.competing(presence) 46 | "STREAMING" -> this.streaming(presence, Configs.SETTINGS.entries.status.url) 47 | else -> this.playing(presence) 48 | } 49 | } } 50 | Fabric2Discord.logger.debug("Presence was updated to \"$presence\"") 51 | } 52 | }, TimeUnit.SECONDS.toMillis(1), TimeUnit.MINUTES.toMillis(Configs.SETTINGS.entries.status.interval.toLong())) 53 | } 54 | 55 | fun afterShutdownServer(timer: Timer) { 56 | MessageUtils.sendDiscordMessage(Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.SERVER_STATUS)) { 57 | Configs.MESSAGES.entries.server.stopped.let { 58 | suppressNotifications = it.silent 59 | embeds = mutableListOf(it.getEmbed(null, server = Fabric2Discord.minecraftServer)) 60 | } 61 | } 62 | if (Configs.SETTINGS.entries.status.enabled) timer.cancel() 63 | Fabric2Discord.logger.info("Shutting down kord and listeners...") 64 | KordClient.stop() 65 | } 66 | 67 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/utils/MessageUtils.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.utils 2 | 3 | import com.vdurmont.emoji.EmojiParser 4 | import dev.kord.common.Color 5 | import dev.kord.common.entity.Snowflake 6 | import dev.kord.core.behavior.channel.createMessage 7 | import dev.kord.core.entity.Member 8 | import dev.kord.core.entity.channel.TextChannel 9 | import dev.kord.rest.builder.message.create.UserMessageCreateBuilder 10 | import dev.kord.rest.builder.message.create.WebhookMessageCreateBuilder 11 | import eu.pb4.placeholders.api.PlaceholderContext 12 | import eu.pb4.placeholders.api.Placeholders.parseText 13 | import eu.pb4.placeholders.api.parsers.TagParser 14 | import kotlinx.coroutines.launch 15 | import net.minecraft.server.MinecraftServer 16 | import net.minecraft.server.PlayerManager 17 | import net.minecraft.server.network.ServerPlayerEntity 18 | import net.minecraft.text.Text 19 | import su.rogi.fabric2discord.Fabric2Discord 20 | import su.rogi.fabric2discord.config.Configs 21 | import su.rogi.fabric2discord.kord.KordClient 22 | 23 | object MessageUtils { 24 | fun sendDiscordMessage(channels: List?, builder: UserMessageCreateBuilder.() -> Unit) { 25 | if (channels.isNullOrEmpty()) return 26 | Fabric2Discord.scope.launch { 27 | for (channel in channels) { 28 | KordClient.kord.getChannelOf(channel)!!.createMessage { 29 | builder() 30 | } 31 | } 32 | } 33 | } 34 | 35 | fun sendMinecraftMessage(playerManager: PlayerManager, member: Member, message: () -> Text) { 36 | val replacements = hashMapOf( 37 | Pair("discord_username", member.username), 38 | Pair("discord_nickname", member.effectiveName), 39 | // TODO: implement colorful names for chat depending on role or profile customization 40 | // Pair("discord_color", member.accentColor) 41 | ) 42 | val formattedMessage = checkNotNull(format( 43 | Configs.MESSAGES.entries.chat.format, 44 | tags = replacements, 45 | server = playerManager.server 46 | )).copy().append(message.invoke()) 47 | 48 | playerManager.broadcast(formattedMessage, false) 49 | } 50 | 51 | fun WebhookMessageCreateBuilder.createWebhookMessage(username: String, avatar: String, message: String) { 52 | this.username = username 53 | this.avatarUrl = avatar 54 | this.content = message 55 | } 56 | 57 | fun format(message: String?, tags: HashMap? = null, server: MinecraftServer? = null, player: ServerPlayerEntity? = null): Text? { 58 | if (message == null) return null 59 | val finalMessage = EmojiParser.parseToUnicode(replacer(message, tags)) 60 | if (server != null && player != null) 61 | return parseText(TagParser.DEFAULT.parseNode(finalMessage), PlaceholderContext.of(player.gameProfile, server)) 62 | if (server != null) 63 | return parseText(TagParser.DEFAULT.parseNode(finalMessage), PlaceholderContext.of(server)) 64 | if (player != null) 65 | return parseText(TagParser.DEFAULT.parseNode(finalMessage), PlaceholderContext.of(player)) 66 | return TagParser.DEFAULT.parseNode(finalMessage).toText() 67 | } 68 | 69 | private fun replacer(message: String, replacements: HashMap? = null): String { 70 | if (replacements == null) return message 71 | var newMessage = message 72 | replacements.forEach { (key, value) -> newMessage = newMessage.replace("%${key}%", value) } 73 | return newMessage 74 | } 75 | 76 | fun toColor(hex: String): Color { 77 | val finalHex = hex.replace("#", "") 78 | return Color(Integer.valueOf(finalHex, 16)) 79 | } 80 | 81 | fun convertDiscordTags(text: String): String { 82 | return text 83 | .replace(getMarkdownRegex("||", "\\|\\|"), "$2") 84 | .replace(getMarkdownRegex("**", "\\*\\*"), "$2") 85 | .replace(getMarkdownRegex("__", "__"), "$2") 86 | .replace(getMarkdownRegex("~~", "~~"), "$2") 87 | .replace(getMarkdownRegex("*", "\\*"), "$2") 88 | } 89 | 90 | /* 91 | * Parts of the code from StyledChat by Patbox 92 | * https://github.com/Patbox/StyledChat/blob/e8e792f7ff29b93efab2595fd094415226c8f3d4/src/main/java/eu/pb4/styledchat/StyledChatUtils.java 93 | */ 94 | private fun getMarkdownRegex(base: String, sides: String): Regex { 95 | return Regex("($sides)(?[^$base]+)($sides)") 96 | } 97 | } -------------------------------------------------------------------------------- /src/main/kotlin/su/rogi/fabric2discord/kord/KordClient.kt: -------------------------------------------------------------------------------- 1 | package su.rogi.fabric2discord.kord 2 | 3 | import dev.kord.core.Kord 4 | import dev.kord.core.behavior.channel.createWebhook 5 | import dev.kord.core.behavior.execute 6 | import dev.kord.core.entity.channel.TextChannel 7 | import dev.kord.core.event.gateway.ReadyEvent 8 | import dev.kord.core.event.message.MessageCreateEvent 9 | import dev.kord.core.exception.KordInitializationException 10 | import dev.kord.core.on 11 | import dev.kord.gateway.Intent 12 | import dev.kord.gateway.PrivilegedIntent 13 | import eu.pb4.placeholders.api.parsers.TagParser 14 | import kotlinx.coroutines.* 15 | import su.rogi.fabric2discord.Fabric2Discord 16 | import su.rogi.fabric2discord.config.Configs 17 | import su.rogi.fabric2discord.config.components.ChannelCategory 18 | import su.rogi.fabric2discord.utils.MessageUtils 19 | import su.rogi.fabric2discord.utils.MessageUtils.createWebhookMessage 20 | import kotlin.system.exitProcess 21 | 22 | object KordClient { 23 | 24 | lateinit var kord: Kord 25 | private lateinit var kordListener: Job 26 | 27 | fun create() { 28 | runBlocking { 29 | try { 30 | kord = Kord(Configs.SETTINGS.entries.token) 31 | } catch (err: KordInitializationException) { 32 | Fabric2Discord.logger.error(""" 33 | Unable to start the bot, make sure you are using valid token! 34 | 35 | You can visit documentation to get help: 36 | https://github.com/27rogi/Fabric2Discord/wiki/Getting-Started 37 | 38 | If error still appears please create an issue here: 39 | https://github.com/27rogi/Fabric2Discord/issues 40 | 41 | Error: {} 42 | """.trimIndent(), err.stackTraceToString()) 43 | exitProcess(1) 44 | } 45 | } 46 | @OptIn(DelicateCoroutinesApi::class) 47 | kordListener = GlobalScope.launch { 48 | kord.on { 49 | Fabric2Discord.logger.info("Connected as {}", self.username) 50 | } 51 | kord.on { 52 | if (Fabric2Discord.minecraftServer == null) { 53 | Fabric2Discord.logger.warn("Unable to send chat message because server is not loaded yet!") 54 | return@on 55 | } 56 | if (Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.SERVER_CHAT)?.contains(message.channelId) != true) return@on 57 | if ((message.author == null || message.author!!.isBot) || message.webhookId != null) return@on 58 | if (this.guildId == null) return@on Fabric2Discord.logger.error("Unable to get guildId for incoming message!") 59 | if (message.content.isNotEmpty()) { 60 | MessageUtils.sendMinecraftMessage(Fabric2Discord.minecraftServer!!.playerManager, message.author!!.asMember(this.guildId!!)) { 61 | TagParser.DEFAULT_SAFE.parseNode(MessageUtils.convertDiscordTags(message.content)).toText() 62 | } 63 | } 64 | if (message.attachments.isNotEmpty()) { 65 | MessageUtils.sendMinecraftMessage(Fabric2Discord.minecraftServer!!.playerManager, message.author!!.asMember(this.guildId!!)) { 66 | TagParser.DEFAULT.parseNode(message.attachments.joinToString { attachment -> 67 | Configs.MESSAGES.entries.chat.formattedAttachment.replace("%attachment_url%", attachment.url).replace( 68 | "%attachment_name%", 69 | if (attachment.filename.length > 14) 70 | "${attachment.filename.substring(0, 14)}..." 71 | else 72 | attachment.filename 73 | ) 74 | }).toText() 75 | } 76 | } 77 | } 78 | kord.login { 79 | intents += Intent.GuildMessages 80 | intents += Intent.GuildWebhooks 81 | intents += Intent.GuildIntegrations 82 | @OptIn(PrivilegedIntent::class) 83 | intents += Intent.GuildPresences 84 | @OptIn(PrivilegedIntent::class) 85 | intents += Intent.MessageContent 86 | } 87 | } 88 | } 89 | 90 | fun registerWebhook() { 91 | if (Configs.SETTINGS.entries.ids.webhooks == null) { 92 | Fabric2Discord.logger.info("Webhooks are disabled because entry is null") 93 | return 94 | } 95 | if (Configs.SETTINGS.entries.ids.webhooks!!.isEmpty()) { 96 | val chats = Configs.SETTINGS.entries.ids.getByCategory(ChannelCategory.GAME_CHAT) 97 | if (chats.isNullOrEmpty()) { 98 | Fabric2Discord.logger.info("Unable to create webhooks because there are no channels with `GAME_CHAT` category") 99 | return 100 | } 101 | for (chat in chats) { 102 | runBlocking { 103 | val webhook = kord.getChannelOf(chat)?.createWebhook("F2DHook") 104 | if (webhook == null) { 105 | Fabric2Discord.logger.warn("Invalid channel id for $chat") 106 | return@runBlocking 107 | } 108 | Configs.SETTINGS.entries.ids.webhooks = Configs.SETTINGS.entries.ids.webhooks!!.plus(webhook.id.value.toLong()) 109 | Configs.SETTINGS.save().load() 110 | } 111 | } 112 | return 113 | } 114 | } 115 | 116 | fun executeWebhook(username: String, avatar: String, message: String) { 117 | if (message.isEmpty()) { 118 | Fabric2Discord.logger.info("cannot send empty message from $username") 119 | return 120 | } 121 | if (Configs.SETTINGS.entries.ids.getWebhooks().isNullOrEmpty()) { 122 | Fabric2Discord.logger.warn("Unable to execute webhooks because they are empty or null") 123 | return 124 | } 125 | Fabric2Discord.scope.launch { 126 | for (webhookId in Configs.SETTINGS.entries.ids.getWebhooks()!!) { 127 | val webhook = kord.getWebhook(webhookId) 128 | webhook.execute(webhook.token!!, null) { createWebhookMessage(username, avatar, message) } 129 | } 130 | } 131 | } 132 | 133 | fun stop() { 134 | // TODO: fix throwable JobCancellationException 135 | kordListener.cancel() 136 | runBlocking { kord.logout() } 137 | } 138 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | --------------------------------------------------------------------------------