Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 129
src/client/java/com/kodari/randomdm/RandomDmClient.java
package com.kodari.randomdm;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import com.mojang.brigadier.Command;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.arguments.StringArgumentType;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.fabricmc.fabric.api.client.command.v2.ClientCommands;
import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.network.chat.Component;
public class RandomDmClient implements ClientModInitializer {
@Override
public void onInitializeClient() {
ClientCommandRegistrationCallback.EVENT.register((dispatcher, buildContext) ->
dispatcher.register(ClientCommands.literal("msg")
.then(ClientCommands.literal("random")
.then(ClientCommands.argument("message", StringArgumentType.greedyString())
.executes(context -> sendRandomMessage(context))))
)
);
}
private static int sendRandomMessage(CommandContext<FabricClientCommandSource> context) {
FabricClientCommandSource source = context.getSource();
ClientPacketListener connection = getConnection(source);
if (connection == null) {
return 0;
}
List<String> targets = connection.getOnlinePlayers().stream()
.map(PlayerInfo -> PlayerInfo.getProfile().name())
.filter(name -> !name.equals(connection.getLocalGameProfile().name()))
.toList();
if (targets.isEmpty()) {
source.sendFeedback(Component.literal("No other online players are available."));
return 0;
}
String target = targets.get(ThreadLocalRandom.current().nextInt(targets.size()));
String message = StringArgumentType.getString(context, "message");
connection.sendCommand("msg " + target + " " + message);
source.sendFeedback(Component.literal("Sent a message to " + target + "."));
return Command.SINGLE_SUCCESS;
}
private static ClientPacketListener getConnection(FabricClientCommandSource source) {
ClientPacketListener connection = source.getClient().getConnection();
if (connection == null) {
source.sendFeedback(Component.literal("You must be connected to a server."));
}
return connection;
}
}