Dev/remove standalone #86

Closed
ShaneBeee wants to merge 11 commits from dev/remove-standalone into main
pull from: dev/remove-standalone
25 changed files with 116 additions and 6826 deletions
Showing only changes of commit a77c22bb25 - Show all commits

No files matched your search

+5 -19
View File
@@ -6,7 +6,7 @@ plugins {
} }
group 'com.shanebeestudios' group 'com.shanebeestudios'
version '1.2.9' version '1.0.0'
compileJava { compileJava {
sourceCompatibility = '17' sourceCompatibility = '17'
@@ -25,13 +25,9 @@ repositories {
} }
dependencies { dependencies {
implementation 'com.github.steveice10:mcprotocollib:1.20.4-2-SNAPSHOT' // McProtocol
implementation 'net.kyori:adventure-text-serializer-gson:4.16.0' implementation('com.github.steveice10:mcprotocollib:1.20.4-2-SNAPSHOT')
implementation 'commons-cli:commons-cli:1.5.0' implementation('net.kyori:adventure-text-serializer-gson:4.16.0')
implementation 'com.diogonunes:JColor:5.2.0'
implementation 'dnsjava:dnsjava:3.4.3'
implementation 'org.slf4j:slf4j-nop:1.7.32'
implementation 'org.jline:jline:3.25.0'
// Paper // Paper
compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT") compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT")
@@ -44,19 +40,9 @@ processResources {
filter ReplaceTokens, tokens: ["version": project.version] filter ReplaceTokens, tokens: ["version": project.version]
} }
jar {
manifest {
attributes 'Main-Class': 'com.shanebeestudios.mcbots.standalone.Main', 'Manifest-Version': project.version
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
from {
configurations.runtimeClasspath.filter { it.exists() }.collect { it.isDirectory() ? it : zipTree(it) }
}
}
shadowJar { shadowJar {
dependsOn(jar)
archiveClassifier = null archiveClassifier = null
minimize()
relocate("dev.jorel.commandapi", "com.shanebeestudios.mcbots.api.commandapi") relocate("dev.jorel.commandapi", "com.shanebeestudios.mcbots.api.commandapi")
} }
@@ -1,63 +0,0 @@
package com.shanebeestudios.mcbots.api;
import com.github.steveice10.mc.protocol.MinecraftConstants;
import com.github.steveice10.mc.protocol.MinecraftProtocol;
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.github.steveice10.mc.protocol.data.status.handler.ServerInfoHandler;
import com.github.steveice10.mc.protocol.data.status.handler.ServerPingTimeHandler;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.tcp.TcpClientSession;
import java.net.InetSocketAddress;
public class ServerInfo {
private final Session client;
private ServerStatusInfo serverStatusInfo;
private long ping;
private boolean done;
public ServerInfo(InetSocketAddress address) {
MinecraftProtocol protocol = new MinecraftProtocol();
this.client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, null);
this.client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (ServerInfoHandler) (session, info) -> {
this.serverStatusInfo = info;
});
this.client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (ServerPingTimeHandler) (session, pingTime) -> {
this.ping = pingTime;
});
this.client.addListener(new SessionAdapter() {
@Override
public void disconnected(DisconnectedEvent event) {
done = true;
}
});
}
public void requestInfo() {
this.client.connect();
//wait to disconnect
while (!this.done) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public ServerStatusInfo getStatusInfo() {
return this.serverStatusInfo;
}
public long getPing() {
return this.ping;
}
}
@@ -11,26 +11,22 @@ import com.github.steveice10.packetlib.ProxyInfo;
import com.github.steveice10.packetlib.Session; import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.packet.Packet; import com.github.steveice10.packetlib.packet.Packet;
import com.github.steveice10.packetlib.tcp.TcpClientSession; import com.github.steveice10.packetlib.tcp.TcpClientSession;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import com.shanebeestudios.mcbots.api.listener.MessageListener;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.time.Instant; import java.time.Instant;
import java.util.BitSet; import java.util.BitSet;
import java.util.Collections; import java.util.Collections;
@SuppressWarnings("unused")
public class Bot { public class Bot {
private final MinecraftProtocol protocol; private final MinecraftProtocol protocol;
private final BotManager botManager; private final BotManager botManager;
private final String nickname; private final String nickname;
private final Session client; private final Session client;
private boolean hasMainListener;
private double lastX, lastY, lastZ = -1; private double lastX, lastY, lastZ = -1;
private boolean connected; private boolean connected;
private boolean manualDisconnecting = false; private boolean manualDisconnecting = false;
private BaseSessionListener sessionListener;
public Bot(BotManager botManager, String nickname, InetSocketAddress address, ProxyInfo proxy) { public Bot(BotManager botManager, String nickname, InetSocketAddress address, ProxyInfo proxy) {
this.botManager = botManager; this.botManager = botManager;
@@ -54,18 +50,12 @@ public class Bot {
this.client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService); this.client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
} }
public void setupSessionListener(BaseSessionListener listener) {
this.sessionListener = listener.init(this);
}
/** /**
* Connect the bot to the server * Connect the bot to the server
*/ */
public void connect() { public void connect() {
new Thread(() -> { new Thread(() -> {
if (!this.botManager.isMinimal() && this.sessionListener != null) { this.client.addListener(new PacketListener(this));
this.client.addListener(this.sessionListener);
}
this.client.connect(); this.client.connect();
}).start(); }).start();
} }
@@ -94,10 +84,6 @@ public class Bot {
return this.manualDisconnecting; return this.manualDisconnecting;
} }
public boolean hasMainListener() {
return this.hasMainListener;
}
public void sendChat(String text) { public void sendChat(String text) {
// timeStamp will provide when this message was sent by the user. If this value was not set or was set to 0, // timeStamp will provide when this message was sent by the user. If this value was not set or was set to 0,
// The server console will print out that the message was "expired". To avoid this, set timeStamp as now. // The server console will print out that the message was "expired". To avoid this, set timeStamp as now.
@@ -115,12 +101,6 @@ public class Bot {
this.client.send(packet); this.client.send(packet);
} }
public void registerMainListener() {
this.hasMainListener = true;
if (this.botManager.isMinimal()) return;
this.client.addListener(new MessageListener(this));
}
public void fallDown() { public void fallDown() {
if (this.connected && this.lastY > 0) { if (this.connected && this.lastY > 0) {
move(0, -0.5, 0); move(0, -0.5, 0);
@@ -1,105 +0,0 @@
package com.shanebeestudios.mcbots.api.bot;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.packetlib.ProxyInfo;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneSessionListener;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Random;
public class BotLoader {
private final StandaloneBotManager standaloneLoader;
private final int delayMin;
private final int delayMax;
private final Random random;
private int triedToConnect = 0;
private int proxyIndex = 0;
public BotLoader(StandaloneBotManager standaloneLoader) {
this.standaloneLoader = standaloneLoader;
this.delayMin = standaloneLoader.getDelayMin();
this.delayMax = standaloneLoader.getDelayMax();
this.random = new Random();
}
@SuppressWarnings("CallToPrintStackTrace")
public void spin() {
int botCount = this.standaloneLoader.getBotCount();
boolean minimal = this.standaloneLoader.isMinimal();
boolean mostMinimal = this.standaloneLoader.isMostMinimal();
InetSocketAddress inetAddr = this.standaloneLoader.getInetAddr();
NickGenerator nickGenerator = this.standaloneLoader.getNickGenerator();
AuthenticationService authService = this.standaloneLoader.getAuthenticationService();
ProxyGenerator proxyGenerator = this.standaloneLoader.getProxyGenerator();
int proxyCount = proxyGenerator != null ? proxyGenerator.getProxies().size() : 0;
ArrayList<InetSocketAddress> proxies = proxyGenerator != null ? proxyGenerator.getProxies() : null;
new Thread(() -> {
for (int i = 0; i < botCount; i++) {
try {
ProxyInfo proxyInfo = null;
if (proxies != null && !proxies.isEmpty()) {
InetSocketAddress proxySocket = proxies.get(this.proxyIndex);
if (!minimal) {
Logger.info("Using proxy: (" + this.proxyIndex + ")", proxySocket.getHostString() + ":" + proxySocket.getPort());
}
proxyInfo = new ProxyInfo(proxyGenerator.getProxyType(), proxySocket);
//increment or reset current proxy index
if (this.proxyIndex < (proxyCount - 1)) {
this.proxyIndex++;
} else {
this.proxyIndex = 0;
}
}
Bot bot;
if (authService != null) {
bot = new Bot(this.standaloneLoader, authService, inetAddr, proxyInfo);
} else {
bot = new Bot(this.standaloneLoader, nickGenerator.nextNick(), inetAddr, proxyInfo);
}
bot.setupSessionListener(new StandaloneSessionListener());
bot.connect();
if (!mostMinimal) this.standaloneLoader.getBots().add(bot);
this.triedToConnect++;
if (this.standaloneLoader.isMainListenerMissing() && !minimal) {
this.standaloneLoader.setMainListenerMissing(false);
bot.registerMainListener();
}
if (i < botCount - 1) {
long delay = getRandomDelay();
Logger.info("Waiting", delay + "", "ms");
Thread.sleep(delay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public int getTriedToConnect() {
return this.triedToConnect;
}
private long getRandomDelay() {
return this.random.nextInt(this.delayMax - this.delayMin) + this.delayMin;
}
}
@@ -1,39 +1,44 @@
package com.shanebeestudios.mcbots.api; package com.shanebeestudios.mcbots.api.bot;
import com.shanebeestudios.mcbots.api.generator.NickGenerator; import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.timer.GravityTimer; import com.shanebeestudios.mcbots.api.timer.GravityTimer;
import com.shanebeestudios.mcbots.api.util.logging.Logger; import com.shanebeestudios.mcbots.api.util.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot; import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.net.Inet4Address;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.util.ArrayList; import java.util.ArrayList;
/** /**
* Base bot manager * Bot manager for server plugin
*/ */
public abstract class BotManager { @SuppressWarnings("unused")
public class BotManager {
protected int autoRespawnDelay; private final int autoRespawnDelay;
protected boolean minimal = false; private final String nickPath = null;
protected boolean mostMinimal = false; private final String nickPrefix = "";
protected String nickPath = null; private final boolean hasGravity;
protected String nickPrefix = ""; private final ArrayList<String> joinMessages = new ArrayList<>();
protected boolean hasGravity; private final InetSocketAddress inetAddr;
protected ArrayList<String> joinMessages = new ArrayList<>(); private final ArrayList<Bot> bots = new ArrayList<>();
protected InetSocketAddress inetAddr; private final NickGenerator nickGenerator;
protected final ArrayList<Bot> bots = new ArrayList<>(); private final GravityTimer gravityTimer;
protected NickGenerator nickGenerator;
protected final GravityTimer gravityTimer;
public BotManager() { public BotManager() {
this.autoRespawnDelay = 3000;
this.inetAddr = createInetAddress(getServerAddress(), Bukkit.getPort());
this.nickGenerator = new NickGenerator("plugins/McBots/nicks.txt", this.nickPrefix, true);
this.hasGravity = true;
this.gravityTimer = new GravityTimer(this); this.gravityTimer = new GravityTimer(this);
this.gravityTimer.startTimer();
} }
// Methods // Methods
protected InetSocketAddress createInetAddress(String address, int port) { private InetSocketAddress createInetAddress(String address, int port) {
try { try {
InetAddress inetAddress = InetAddress.getByName(address); InetAddress inetAddress = InetAddress.getByName(address);
return new InetSocketAddress(inetAddress.getHostAddress(), port); return new InetSocketAddress(inetAddress.getHostAddress(), port);
@@ -42,14 +47,6 @@ public abstract class BotManager {
} }
} }
public boolean isMinimal() {
return this.minimal;
}
public boolean isMostMinimal() {
return this.mostMinimal;
}
public int getAutoRespawnDelay() { public int getAutoRespawnDelay() {
return this.autoRespawnDelay; return this.autoRespawnDelay;
} }
@@ -74,6 +71,10 @@ public abstract class BotManager {
return this.inetAddr; return this.inetAddr;
} }
public GravityTimer getGravityTimer() {
return this.gravityTimer;
}
/** /**
* Get all loaded bots * Get all loaded bots
* *
@@ -92,14 +93,6 @@ public abstract class BotManager {
return this.nickGenerator; return this.nickGenerator;
} }
public void logBotCreated(String name) {
Logger.info("Bot '" + name + "' created");
}
public void logBotDisconnected(String name) {
Logger.info("Bot '" + name + "' disconnected");
}
/** /**
* Remove a bot * Remove a bot
* *
@@ -137,4 +130,38 @@ public abstract class BotManager {
return null; return null;
} }
/**
* Create a bot
*
* @param name Name of bot or null to create random named bot
* Name must be between 1 and 16 characters
* @return Bot if was created, else null
*/
@Nullable
public Bot createBot(@Nullable String name) {
if (name != null && name.length() > 16) return null;
String botname = name != null ? name : getNickGenerator().nextNick();
Bot bot = new Bot(this, botname, getInetAddr(), null);
this.bots.add(bot);
bot.connect();
return bot;
}
private String getServerAddress() {
try {
return Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public void logBotCreated(String name) {
Logger.info("Bot '&b" + name + "&7' created");
}
public void logBotDisconnected(String name) {
Logger.info("Bot '&b" + name + "&7' disconnected");
}
} }
@@ -1,4 +1,4 @@
package com.shanebeestudios.mcbots.plugin.bot; package com.shanebeestudios.mcbots.api.bot;
import com.github.steveice10.mc.protocol.data.game.ClientCommand; import com.github.steveice10.mc.protocol.data.game.ClientCommand;
import com.github.steveice10.mc.protocol.data.game.level.notify.GameEvent; import com.github.steveice10.mc.protocol.data.game.level.notify.GameEvent;
@@ -11,16 +11,30 @@ import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundCl
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket; import com.github.steveice10.mc.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import com.github.steveice10.packetlib.Session; import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.packet.Packet; import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import java.util.ArrayList;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@SuppressWarnings("DuplicatedCode") @SuppressWarnings("DuplicatedCode")
public class PluginSessionListener extends BaseSessionListener { public class PacketListener extends SessionAdapter {
protected Bot bot;
protected Session client;
protected BotManager botManager;
protected ArrayList<String> joinMessages;
protected int autoRespawnDelay;
public PacketListener(Bot bot) {
this.bot = bot;
this.client = bot.getClient();
this.botManager = bot.getBotManager();
this.joinMessages = this.botManager.getJoinMessages();
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
}
@Override
public void packetReceived(Session session, Packet packet) { public void packetReceived(Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket gameEventPacket) { if (packet instanceof ClientboundGameEventPacket gameEventPacket) {
if (gameEventPacket.getNotification() == GameEvent.ENABLE_RESPAWN_SCREEN) { if (gameEventPacket.getNotification() == GameEvent.ENABLE_RESPAWN_SCREEN) {
@@ -57,14 +71,13 @@ public class PluginSessionListener extends BaseSessionListener {
new TimerTask() { new TimerTask() {
@Override @Override
public void run() { public void run() {
PluginSessionListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN)); PacketListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
} }
}, this.autoRespawnDelay); }, this.autoRespawnDelay);
} }
} }
} }
@Override
public void disconnected(DisconnectedEvent event) { public void disconnected(DisconnectedEvent event) {
this.bot.setConnected(false); this.bot.setConnected(false);
this.botManager.logBotDisconnected(this.bot.getNickname()); this.botManager.logBotDisconnected(this.bot.getNickname());
@@ -1,6 +1,6 @@
package com.shanebeestudios.mcbots.api.generator; package com.shanebeestudios.mcbots.api.generator;
import com.shanebeestudios.mcbots.api.util.logging.Logger; import com.shanebeestudios.mcbots.api.util.Logger;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader; import java.io.BufferedReader;
@@ -1,99 +0,0 @@
package com.shanebeestudios.mcbots.api.generator;
import com.github.steveice10.packetlib.ProxyInfo;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class ProxyGenerator {
private ProxyInfo.Type proxyType;
private final String proxyPath;
private final ArrayList<InetSocketAddress> proxies = new ArrayList<>();
public ProxyGenerator(String proxyType, String proxyPath) {
this.proxyPath = proxyPath;
//get proxy type
try {
this.proxyType = ProxyInfo.Type.valueOf(proxyType);
} catch (IllegalArgumentException e) {
Logger.error("Invalid proxy type, use SOCKS4 or SOCKS5.");
System.exit(1);
}
readProxyFileList();
}
private void readProxyFileList() {
try {
try {
//try to read specified path as URL
URL url = new URL(this.proxyPath);
BufferedReader read = new BufferedReader(
new InputStreamReader(url.openStream()));
Logger.info("Reading proxies from URL");
String line;
while ((line = read.readLine()) != null) {
try {
String[] parts = line.trim().split(":");
if (parts.length == 2) {
int port = Integer.parseInt(parts[1]);
this.proxies.add(new InetSocketAddress(parts[0], port));
}
} catch (Exception ignored) {
}
}
read.close();
} catch (MalformedURLException e) {
Logger.info("Specified proxy file is not a URL, trying to read file");
Scanner scanner = new Scanner(new File(this.proxyPath));
while (scanner.hasNextLine()) {
try {
String[] parts = scanner.nextLine().trim().split(":");
if (parts.length == 2) {
int port = Integer.parseInt(parts[1]);
proxies.add(new InetSocketAddress(parts[0], port));
}
} catch (Exception ignored) {
}
}
scanner.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (FileNotFoundException e) {
Logger.error("Invalid proxy list file path.");
System.exit(1);
}
int size = this.proxies.size();
if (size > 0) {
Logger.info("Loaded " + size + " valid proxies");
} else {
Logger.error("No valid proxies loaded");
System.exit(1);
}
}
public ProxyInfo.Type getProxyType() {
return this.proxyType;
}
public ArrayList<InetSocketAddress> getProxies() {
return this.proxies;
}
}
@@ -1,27 +0,0 @@
package com.shanebeestudios.mcbots.api.listener;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.bot.Bot;
import java.util.ArrayList;
public class BaseSessionListener extends SessionAdapter {
protected Bot bot;
protected Session client;
protected BotManager botManager;
protected ArrayList<String> joinMessages;
protected int autoRespawnDelay;
public BaseSessionListener init(Bot bot) {
this.bot = bot;
this.client = bot.getClient();
this.botManager = bot.getBotManager();
this.joinMessages = this.botManager.getJoinMessages();
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
return this;
}
}
@@ -1,62 +0,0 @@
package com.shanebeestudios.mcbots.api.listener;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundPlayerChatPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundSystemChatPacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.util.Utils;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
public class MessageListener extends SessionAdapter {
private final boolean coloredChat;
public MessageListener(Bot bot) {
this.coloredChat = !(bot.getBotManager() instanceof StandaloneBotManager botManager) || botManager.isColoredChat();
Logger.info("MessageListener registered for: " + bot.getNickname());
}
@Override
public void packetReceived(Session session, Packet packet) {
// From 1.19.1 (as well as 1.19), the class ClientboundChatPacket was removed.
// Instead, they use ClientboundPlayerChatPacket and ClientboundSystemChatPacket for taking care of chat packets.
Component message = null;
Component sender;
boolean chatPrintedOut = false;
if (packet instanceof ClientboundPlayerChatPacket playerChatPacket) {
message = playerChatPacket.getUnsignedContent();
sender = playerChatPacket.getName();
// Sometimes the message's body gets null.
// For example, some commands like /say makes the message content as null.
// However, the message exists as in getMessagePlain(), thus can retrieve message using the method.
if (message == null) {
Logger.chat(Utils.getFullText((TextComponent) sender, Component.text(playerChatPacket.getContent()), this.coloredChat));
} else {
Logger.chat(Utils.getFullText((TextComponent) sender, (TextComponent) message, this.coloredChat));
}
chatPrintedOut = true;
} else if (packet instanceof ClientboundSystemChatPacket systemChatPacket) { // When this was SystemChat packet.
if (systemChatPacket.isOverlay()) return; // Actionbar
message = systemChatPacket.getContent();
}
// For output of commands, this is the case where this program prints out the message to user.
if (message instanceof TextComponent textComponent && !chatPrintedOut) {
Logger.chat(Utils.getFullText(textComponent, this.coloredChat));
}
if (message instanceof TranslatableComponent translatableComponent) {
Logger.chat("[T]", Utils.translate(translatableComponent));
}
}
}
@@ -1,7 +1,7 @@
package com.shanebeestudios.mcbots.api.timer; package com.shanebeestudios.mcbots.api.timer;
import com.shanebeestudios.mcbots.api.bot.Bot; import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.BotManager; import com.shanebeestudios.mcbots.api.bot.BotManager;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@@ -1,18 +1,18 @@
package com.shanebeestudios.mcbots.api.util.logging; package com.shanebeestudios.mcbots.api.util;
import com.shanebeestudios.mcbots.plugin.McBotPlugin;
import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import java.util.logging.Logger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public class PluginLogger extends BaseLogger { @SuppressWarnings("unused")
public class Logger {
private static final String PREFIX = "&7[&bMc&3Bot&7]"; private static final String PREFIX = "&7[&bMc&3Bot&7]";
private static final String PREFIX_ERROR = "&7[&bMc&3Bot &cERROR&7]"; private static final String PREFIX_ERROR = "&7[&bMc&3Bot &cERROR&7]";
private static final String PREFIX_WARN = "&7[&bMc&3Bot &eWARN&7]";
private static final Pattern HEX_PATTERN = Pattern.compile("<#([A-Fa-f\\d]){6}>"); private static final Pattern HEX_PATTERN = Pattern.compile("<#([A-Fa-f\\d]){6}>");
@SuppressWarnings("deprecation") // Paper deprecation @SuppressWarnings("deprecation") // Paper deprecation
@@ -32,61 +32,37 @@ public class PluginLogger extends BaseLogger {
sender.sendMessage(getColString(PREFIX + " &7" + String.format(format, objects))); sender.sendMessage(getColString(PREFIX + " &7" + String.format(format, objects)));
} }
private final Logger bukkitLogger; public static void log(String prefix, String message) {
public PluginLogger(McBotPlugin plugin) {
this.bukkitLogger = plugin.getLogger();
}
@Override
public void log(String prefix, String message) {
String string = getColString(prefix + " " + message); String string = getColString(prefix + " " + message);
Bukkit.getConsoleSender().sendMessage(string); Bukkit.getConsoleSender().sendMessage(string);
} }
@Override public static void error(String error) {
public void error(String error) {
log(PREFIX_ERROR, "&c" + error); log(PREFIX_ERROR, "&c" + error);
} }
@SuppressWarnings("CallToPrintStackTrace") @SuppressWarnings("CallToPrintStackTrace")
@Override public static void error(Exception e) {
public void error(Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
@Override public static void info(String format, Object... objects) {
public void info(String format, Object... objects) {
log(PREFIX, "&7" + String.format(format, objects)); log(PREFIX, "&7" + String.format(format, objects));
} }
@Override public static void info(String... message) {
public void info(String... message) {
log(PREFIX, "&7" + String.join(" ", message)); log(PREFIX, "&7" + String.join(" ", message));
} }
@Override public static void info() {
public void info() {
log(PREFIX, ""); log(PREFIX, "");
} }
@Override public static void warn(String... warning) {
public void warn(String... warning) { log(PREFIX_WARN, String.join(" ", warning));
this.bukkitLogger.warning(String.join(" ", warning));
} }
@Override public static void critical(Exception e) {
public void warn() {
this.bukkitLogger.warning("");
}
@Override
public void chat(String... chat) {
log("[CHAT]", String.join(" ", chat));
}
@Override
public void critical(Exception e) {
error(e); error(e);
} }
@@ -1,166 +1,16 @@
package com.shanebeestudios.mcbots.api.util; package com.shanebeestudios.mcbots.api.util;
import com.diogonunes.jcolor.Attribute;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.TranslationArgument;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser; import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException; import org.json.simple.parser.ParseException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.diogonunes.jcolor.Ansi.colorize;
@SuppressWarnings("deprecation")
public class Utils { public class Utils {
private static JsonObject MINECRAFT_LANG;
public static String getFullText(TextComponent message, boolean colored) {
if (!message.children().isEmpty()) {
StringBuilder text = new StringBuilder();
text.append(parseColor(message, colored));
for (Component child : message.children()) {
if (child instanceof TextComponent textComponent) {
text.append(getFullText(textComponent, colored));
} else if (child instanceof TranslatableComponent translatableComponent) {
text.append(translate(translatableComponent));
}
}
return text.toString();
} else {
return parseColor(message, colored);
}
}
/**
* A static function that gets full text from text components.
* From 1.19.1 the protocol does not include sender's information in the message.
* Thus, we need to merge two TextComponent (sender and message) and generate a text that consists of sent message.
* This means using old getFullText will just send the message. Which does NOT contain username who sent this message
*
* @param sender The TextComponent for sender.
* @param message The TextComponent for message.
* @param colored Whether if this output was colored or not.
* @return Returns String in "Username : Message" format.
*/
public static String getFullText(@Nullable TextComponent sender, TextComponent message, boolean colored) {
if (colored) {
Style messageStyle = message.style();
StringBuilder outString = new StringBuilder();
if (sender != null) {
Style senderStyle = sender.style();
TextColor color = senderStyle.color();
if (color != null) { // Generate sender text with color.
outString.append(colorizeText(sender.content(), color));
} else {
outString.append(sender.content());
}
outString.append(" : "); // Add delimiter as : between sender and message.
}
TextColor color = messageStyle.color();
if (color != null && sender != null) { // Generate message text with color.
outString.append(colorizeText(sender.content(), color));
} else {
outString.append(message.content());
}
return outString.toString();
} else {
if (sender == null) return message.content();
else return sender.content() + " : " + message.content();
}
}
private static String parseColor(TextComponent message, boolean colored) {
String out = message.content();
if (colored) {
TextColor color = message.style().color();
if (color != null) {
List<Attribute> formats = new ArrayList<>(getFormats(message.style().decorations()));
formats.add(Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
out = colorize(out, formats.toArray(new Attribute[0]));
}
}
return out;
}
private static String colorizeText(String text, TextColor color) {
return colorize(text, Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
}
public static List<Attribute> getFormats(Map<TextDecoration, TextDecoration.State> decorations) {
List<Attribute> list = new ArrayList<>();
decorations.forEach((format, state) -> {
if (state.equals(TextDecoration.State.TRUE)) {
switch (format) {
case ITALIC:
list.add(Attribute.ITALIC());
break;
case UNDERLINED:
list.add(Attribute.UNDERLINE());
break;
case STRIKETHROUGH:
list.add(Attribute.STRIKETHROUGH());
break;
}
}
});
return list;
}
public static String translate(TranslatableComponent message) {
if (MINECRAFT_LANG == null) {
try {
InputStream resource = Utils.class.getResourceAsStream("/files/lang.json");
if (resource == null) return null;
MINECRAFT_LANG = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject();
} catch (Exception e) {
Logger.critical(e);
}
}
String key = message.key();
String base = key;
JsonElement value = MINECRAFT_LANG.get(key);
if (value != null) {
base = value.getAsString();
}
ArrayList<String> placeholders = new ArrayList<>();
if (!message.arguments().isEmpty()) {
for (TranslationArgument arg : message.arguments()) {
if (arg.asComponent() instanceof TranslatableComponent translatableComponent) {
placeholders.add(translate(translatableComponent));
} else if (arg.asComponent() instanceof TextComponent textComponent) {
placeholders.add(getFullText(textComponent, false));
}
}
return String.format(base, placeholders.toArray());
} else {
return base;
}
}
/** /**
* Get a UUID from a player name * Get a UUID from a player name
* *
@@ -1,25 +0,0 @@
package com.shanebeestudios.mcbots.api.util.logging;
public abstract class BaseLogger {
public abstract void log(String prefix, String message);
public abstract void error(String error);
public abstract void error(Exception e);
public abstract void info(String format, Object... objects);
public abstract void info(String... message);
public abstract void info();
public abstract void warn(String... warning);
public abstract void warn();
public abstract void chat(String... chat);
public abstract void critical(Exception e);
}
@@ -1,50 +0,0 @@
package com.shanebeestudios.mcbots.api.util.logging;
import com.shanebeestudios.mcbots.plugin.McBotPlugin;
@SuppressWarnings("unused")
public class Logger {
private static BaseLogger INSTANCE = new StandaloneLogger();
public static void setupBukkitLogging(McBotPlugin plugin) {
INSTANCE = new PluginLogger(plugin);
}
public static void error(String error) {
INSTANCE.error(error);
}
public static void error(Exception e) {
INSTANCE.error(e);
}
public static void info(String format, Object... objects) {
INSTANCE.info(format, objects);
}
public static void info(String... message) {
INSTANCE.info(message);
}
public static void info() {
INSTANCE.info();
}
public static void warn(String... warning) {
INSTANCE.warn(warning);
}
public static void warn() {
INSTANCE.warn();
}
public static void chat(String... chat) {
INSTANCE.chat(chat);
}
public static void critical(Exception e) {
INSTANCE.critical(e);
}
}
@@ -1,55 +0,0 @@
package com.shanebeestudios.mcbots.api.util.logging;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StandaloneLogger extends BaseLogger {
private static final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
public void log(String prefix, String message) {
System.out.println("\r[" + formatter.format(new Date()) + " " + prefix + "] " + message);
//System.out.print(StandaloneLoader.getInstance().getPrompt() + "> ");
}
public void error(String error) {
log("ERROR", error);
}
@SuppressWarnings("CallToPrintStackTrace")
public void error(Exception e) {
log("ERROR", "");
e.printStackTrace();
}
@Override
public void info(String format, Object... objects) {
log("INFO", String.format(format, objects));
}
public void info(String... message) {
log("INFO", String.join(" ", message));
}
public void info() {
log("INFO", "");
}
public void warn(String... warning) {
log("WARN", String.join(" ", warning));
}
public void warn() {
log("WARN", "");
}
public void chat(String... chat) {
log("CHAT", String.join(" ", chat));
}
public void critical(Exception e) {
error(e);
System.exit(1);
}
}
@@ -1,9 +1,8 @@
package com.shanebeestudios.mcbots.plugin.command; package com.shanebeestudios.mcbots.plugin;
import com.shanebeestudios.mcbots.api.util.logging.PluginLogger;
import com.shanebeestudios.mcbots.api.bot.Bot; import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.plugin.McBotPlugin; import com.shanebeestudios.mcbots.api.bot.BotManager;
import com.shanebeestudios.mcbots.plugin.bot.PluginBotManager; import com.shanebeestudios.mcbots.api.util.Logger;
import dev.jorel.commandapi.CommandTree; import dev.jorel.commandapi.CommandTree;
import dev.jorel.commandapi.arguments.EntitySelectorArgument; import dev.jorel.commandapi.arguments.EntitySelectorArgument;
import dev.jorel.commandapi.arguments.GreedyStringArgument; import dev.jorel.commandapi.arguments.GreedyStringArgument;
@@ -19,7 +18,7 @@ import java.util.Collection;
public class Command { public class Command {
private final McBotPlugin plugin; private final McBotPlugin plugin;
private final PluginBotManager botManager; private final BotManager botManager;
private final BukkitScheduler scheduler; private final BukkitScheduler scheduler;
public Command(McBotPlugin plugin) { public Command(McBotPlugin plugin) {
@@ -40,9 +39,9 @@ public class Command {
String name = (String) args.get("name"); String name = (String) args.get("name");
Bot bot = this.botManager.createBot(name); Bot bot = this.botManager.createBot(name);
if (bot != null) { if (bot != null) {
PluginLogger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'"); Logger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else { } else {
PluginLogger.logToSender(sender, "&cFailed to create bot '&b" + name + "&7'"); Logger.logToSender(sender, "&cFailed to create bot '&b" + name + "&7'");
} }
}))) })))
.then(new LiteralArgument("random") .then(new LiteralArgument("random")
@@ -57,9 +56,9 @@ public class Command {
this.scheduler.runTaskLater(this.plugin, () -> { this.scheduler.runTaskLater(this.plugin, () -> {
Bot bot = this.botManager.createBot(null); Bot bot = this.botManager.createBot(null);
if (bot != null) { if (bot != null) {
PluginLogger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'"); Logger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else { } else {
PluginLogger.logToSender(sender, "&cFailed to create random bot!"); Logger.logToSender(sender, "&cFailed to create random bot!");
} }
}, delay * i); }, delay * i);
} }
@@ -75,7 +74,7 @@ public class Command {
Bot bot = this.botManager.findBotByName(player.getName()); Bot bot = this.botManager.findBotByName(player.getName());
if (bot != null) { if (bot != null) {
this.botManager.disconnectBot(bot); this.botManager.disconnectBot(bot);
PluginLogger.logToSender(sender, "Removed bot &7'" + bot.getNickname() + "&7'"); Logger.logToSender(sender, "Removed bot &7'" + bot.getNickname() + "&7'");
} }
}); });
}))) })))
@@ -1,8 +1,7 @@
package com.shanebeestudios.mcbots.plugin; package com.shanebeestudios.mcbots.plugin;
import com.shanebeestudios.mcbots.api.util.logging.Logger; import com.shanebeestudios.mcbots.api.bot.BotManager;
import com.shanebeestudios.mcbots.plugin.bot.PluginBotManager; import com.shanebeestudios.mcbots.api.util.Logger;
import com.shanebeestudios.mcbots.plugin.command.Command;
import dev.jorel.commandapi.CommandAPI; import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig; import dev.jorel.commandapi.CommandAPIBukkitConfig;
import dev.jorel.commandapi.exceptions.UnsupportedVersionException; import dev.jorel.commandapi.exceptions.UnsupportedVersionException;
@@ -15,7 +14,7 @@ public class McBotPlugin extends JavaPlugin {
private static McBotPlugin instance; private static McBotPlugin instance;
private boolean commandApiCanLoad; private boolean commandApiCanLoad;
private PluginBotManager pluginBotManager; private BotManager botManager;
@Override @Override
public void onLoad() { public void onLoad() {
@@ -36,7 +35,6 @@ public class McBotPlugin extends JavaPlugin {
public void onEnable() { public void onEnable() {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
PluginManager pluginManager = Bukkit.getPluginManager(); PluginManager pluginManager = Bukkit.getPluginManager();
Logger.setupBukkitLogging(this);
if (Bukkit.getOnlineMode()) { if (Bukkit.getOnlineMode()) {
Logger.error("***********************************************"); Logger.error("***********************************************");
Logger.error("* *"); Logger.error("* *");
@@ -74,7 +72,7 @@ public class McBotPlugin extends JavaPlugin {
} }
private void setupBotLogic() { private void setupBotLogic() {
this.pluginBotManager = new PluginBotManager(); this.botManager = new BotManager();
} }
private void setupCommand() { private void setupCommand() {
@@ -88,8 +86,8 @@ public class McBotPlugin extends JavaPlugin {
return instance; return instance;
} }
public PluginBotManager getPluginBotManager() { public BotManager getPluginBotManager() {
return this.pluginBotManager; return this.botManager;
} }
} }
@@ -1,63 +0,0 @@
package com.shanebeestudios.mcbots.plugin.bot;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable;
import java.net.Inet4Address;
import java.net.UnknownHostException;
/**
* Bot manager for server plugin
*/
public class PluginBotManager extends BotManager {
public PluginBotManager() {
this.autoRespawnDelay = 3000;
this.inetAddr = createInetAddress(getServerAddress(), Bukkit.getPort());
this.nickGenerator = new NickGenerator("plugins/McBots/nicks.txt", this.nickPrefix, true);
this.hasGravity = true;
this.gravityTimer.startTimer();
}
/**
* Create a bot
*
* @param name Name of bot or null to create random named bot
* Name must be between 1 and 16 characters
* @return Bot if was created, else null
*/
@Nullable
public Bot createBot(@Nullable String name) {
if (name != null && name.length() > 16) return null;
String botname = name != null ? name : getNickGenerator().nextNick();
Bot bot = new Bot(this, botname, getInetAddr(), null);
this.bots.add(bot);
bot.setupSessionListener(new PluginSessionListener());
bot.connect();
return bot;
}
private String getServerAddress() {
try {
return Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
@Override
public void logBotCreated(String name) {
Logger.info("Bot '&b" + name + "&7' created");
}
@Override
public void logBotDisconnected(String name) {
Logger.info("Bot '&b" + name + "&7' disconnected");
}
}
@@ -1,43 +0,0 @@
package com.shanebeestudios.mcbots.standalone;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
public class Main {
public static void main(String[] args) {
Options options = new Options();
options.addOption("c", "count", true, "bot count");
Option addressOption = new Option("s", "server", true, "server IP[:port]");
addressOption.setRequired(true);
options.addOption(addressOption);
Option delayOption = new Option("d", "delay", true, "connection delay (ms) <min> <max>");
delayOption.setArgs(2);
options.addOption(delayOption);
options.addOption("r", "real", false, "generate real looking nicknames");
options.addOption("n", "nocolor", false, "dont color & format incoming chat messages");
options.addOption("p", "prefix", true, "bot nick prefix");
options.addOption("m", "minimal", false, "minimal run without any listeners");
options.addOption("x", "most-minimal", false, "minimal run without any control, just connect the bots");
options.addOption("j", "join-msg", true, "join messages / commands, separated by &&");
options.addOption("l", "proxy-list", true, "Path or URL to proxy list file with proxy:port on every line");
options.addOption("t", "proxy-type", true, "Proxy type: SOCKS4 or SOCKS5");
options.addOption(null, "nicks", true, "Path to nicks file with nick on every line");
options.addOption("g", "gravity", false, "Try to simulate gravity by falling down");
options.addOption("o", "online", false, "Use online mode (premium) account");
options.addOption("ar", "auto-respawn", true, "Set autorespawn delay (-1 to disable)");
new StandaloneBotManager(options, args);
}
}
@@ -1,161 +0,0 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ConsoleReader {
private final StandaloneBotManager standaloneLoader;
public ConsoleReader(StandaloneBotManager standaloneLoader) {
this.standaloneLoader = standaloneLoader;
}
@SuppressWarnings("BusyWait")
public void start() {
Terminal terminal;
try {
terminal = TerminalBuilder.builder().build();
} catch (IOException e) {
throw new RuntimeException(e);
}
LineReader lineReader = LineReaderBuilder.builder()
.terminal(terminal)
.parser(new org.jline.reader.impl.DefaultParser())
.build();
while (true) {
HashSet<Bot> controlledBots = this.standaloneLoader.getControlledBots();
ArrayList<Bot> bots = this.standaloneLoader.getBots();
String line;
try {
line = lineReader.readLine();
} catch (UserInterruptException e) {
System.exit(0);
break;
}
if (line.isEmpty()) {
System.out.print(this.standaloneLoader.getPrompt() + "> ");
continue;
}
if (line.startsWith("!") || line.startsWith(".")) {
String command = line.substring(1);
String[] split = command.split(" ");
String commandName = split[0];
// Bot control selection
if (commandName.equalsIgnoreCase("control") || commandName.equalsIgnoreCase("ctrl")) {
if (split.length >= 2) {
controlledBots.clear();
int newBotCount = 0;
// Search for all bot names, from index 1 - skip command name
for (int i = 1; i < split.length; i++) {
String searchedName = split[i];
Bot bot = this.standaloneLoader.findBotByName(searchedName);
if (bot != null) {
controlledBots.add(bot);
newBotCount++;
} else {
Logger.warn("Bot not found: " + searchedName);
}
}
if (newBotCount > 0) {
// Join bot nicknames
String botNames = controlledBots
.stream()
.map(Bot::getNickname)
.collect(Collectors.joining(", "));
if (newBotCount == 1) {
Logger.info("Now controlling 1 bot: " + botNames);
} else {
Logger.info("Now controlling " + newBotCount + " bots: " + botNames);
}
} else {
Logger.warn("No bots found.");
}
} else {
// If no bot names are supplied, remove all bots
controlledBots.clear();
Logger.info("No bots selected - now controlling all bots.");
}
}
// List command
else if (commandName.equalsIgnoreCase("list") || commandName.equalsIgnoreCase("ls")) {
Logger.info("There are " + bots.size() + " bots connected:");
for (Bot bot : bots) {
Logger.info(bot.getNickname(), bot.hasMainListener() ? "[MainListener]" : "");
}
}
// Leave command
else if (commandName.equalsIgnoreCase("leave") || commandName.equalsIgnoreCase("exit")) {
int limit = -1;
if (split.length >= 2) {
try {
limit = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
limit = 0;
Logger.warn("Invalid limit.");
}
}
int i = 0;
if (!controlledBots.isEmpty()) {
Logger.info("Disconnecting controlled bots.");
for (Bot bot : controlledBots) {
if (i++ == limit) {
break;
}
bot.disconnect();
}
} else {
Logger.info("Disconnecting all bots.");
for (Bot bot : bots) {
if (i++ == limit) {
break;
}
bot.disconnect();
}
}
} else {
Logger.warn("Invalid command");
}
} else if (!controlledBots.isEmpty()) {
controlledBots.forEach(bot -> bot.sendChat(line));
} else {
bots.forEach(bot -> bot.sendChat(line));
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
@@ -1,79 +0,0 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.auth.exception.request.AuthPendingException;
import com.github.steveice10.mc.auth.exception.request.RequestException;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.mc.auth.service.MsaAuthenticationService;
import com.github.steveice10.mc.auth.util.HTTP;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class OnlineService {
private final String clientId = "8bef943e-5a63-429e-a93a-96391d2e32a9";
private final StandaloneBotManager botManager;
public OnlineService(StandaloneBotManager botManager) {
this.botManager = botManager;
}
public AuthenticationService getOnlineAuthenticationService() {
Logger.warn("Online mode enabled. The bot count will be set to 1.");
this.botManager.setBotCount(1);
// Create request parameters map
Map<String, String> params = new HashMap<>();
params.put("client_id", clientId);
params.put("scope", "XboxLive.signin");
// Send request to Microsoft OAuth api
// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code
URI endpointURI = URI.create("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode");
MsaAuthenticationService.MsCodeResponse response;
try {
response = HTTP.makeRequestForm(
Proxy.NO_PROXY, endpointURI, params, MsaAuthenticationService.MsCodeResponse.class
);
} catch (RequestException e) {
throw new RuntimeException(e);
}
try {
Logger.info("Please go to " + response.verification_uri.toURL() + " to authenticate your account - Code: " + response.user_code);
} catch (MalformedURLException e) {
Logger.error("Error while trying to get the url of the authentication page");
}
AuthenticationService authService = new MsaAuthenticationService(clientId, response.device_code);
// Wait for user to login on microsoft page
int retryMax = 20;
while (true) {
try {
authService.login();
break;
} catch (Exception e) {
if (e instanceof AuthPendingException) {
Logger.info("Authentication is pending, waiting for user to authenticate...");
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
if (retryMax == 0)
throw new RuntimeException(e);
retryMax--;
} else {
throw new RuntimeException(e);
}
}
}
return authService;
}
}
@@ -1,268 +0,0 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.ServerInfo;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
import com.shanebeestudios.mcbots.api.util.Pair;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.bot.BotLoader;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.jetbrains.annotations.Nullable;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import java.net.InetSocketAddress;
import java.util.HashSet;
public class StandaloneBotManager extends BotManager {
protected int botCount;
private final int delayMin;
private final int delayMax;
private final boolean coloredChat;
private final boolean online;
private ProxyGenerator proxyGenerator;
private final HashSet<Bot> controlledBots = new HashSet<>();
private final AuthenticationService authenticationService;
private final BotLoader botLoader;
private boolean isMainListenerMissing = true;
public StandaloneBotManager(Options options, String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("mcbots", e.getMessage(), options, "\nhttps://github.com/ShaneBeee/mc-bots", true);
System.exit(1);
}
this.autoRespawnDelay = Integer.parseInt(cmd.getOptionValue("ar", "100"));
boolean hasProxy = cmd.hasOption('t') && cmd.hasOption('l');
if (hasProxy) {
String proxyType = cmd.getOptionValue('t').toUpperCase();
String proxyPath = cmd.getOptionValue("l");
this.proxyGenerator = new ProxyGenerator(proxyType, proxyPath);
}
this.botCount = Integer.parseInt(cmd.getOptionValue('c', "1"));
this.minimal = cmd.hasOption('m');
if (cmd.hasOption('x')) {
this.minimal = this.mostMinimal = true;
}
if (cmd.hasOption('d')) {
String[] delays = cmd.getOptionValues('d');
Pair<Integer, Integer> delay = parseDelays(delays);
this.delayMin = delay.getFirst();
this.delayMax = delay.getSecond();
} else {
this.delayMin = 4000;
this.delayMax = 5000;
}
String address = cmd.getOptionValue('s');
Pair<String, Integer> addressPort = parseAddress(address);
this.inetAddr = createInetAddress(addressPort.getFirst(), addressPort.getSecond());
this.coloredChat = !cmd.hasOption('n');
if (cmd.hasOption('j')) {
// Split messages by &&, trim and append to arraylist
String[] messages = cmd.getOptionValue('j').split("&&");
for (String msg : messages) {
this.joinMessages.add(msg.trim());
}
}
boolean useRealNick = cmd.hasOption('r');
this.nickPath = cmd.getOptionValue("nicks", null);
this.nickPrefix = cmd.getOptionValue('p', "");
this.nickGenerator = new NickGenerator(this.nickPath, this.nickPrefix, useRealNick);
this.online = cmd.hasOption("o");
this.hasGravity = cmd.hasOption("g");
getAndPrintServerInfo(getInetAddr());
if (isOnline()) {
OnlineService onlineService = new OnlineService(this);
this.authenticationService = onlineService.getOnlineAuthenticationService();
} else {
this.authenticationService = null;
}
// Load bots
this.botLoader = new BotLoader(this);
this.botLoader.spin();
if (hasGravity()) {
this.gravityTimer.startTimer();
}
// Load console reader
ConsoleReader consoleReader = new ConsoleReader(this);
consoleReader.start();
}
private Pair<String, Integer> parseAddress(String address) {
int port = 25565;
if (address.contains(":")) {
String[] split = address.split(":", 2);
address = split[0];
port = Integer.parseInt(split[1]);
} else {
Record[] records;
try {
records = new Lookup("_minecraft._tcp." + address, Type.SRV).run();
} catch (TextParseException e) {
throw new RuntimeException(e);
}
if (records != null) {
for (Record record : records) {
SRVRecord srv = (SRVRecord) record;
address = srv.getTarget().toString().replaceFirst("\\.$", "");
port = srv.getPort();
}
}
}
return new Pair<>(address, port);
}
private Pair<Integer, Integer> parseDelays(String[] delays) {
int delayMin = Integer.parseInt(delays[0]);
int delayMax = delayMin + 1;
if (delays.length == 2) {
delayMax = Integer.parseInt(delays[1]);
}
if (delayMax <= delayMin) {
throw new IllegalArgumentException("delay max must not be equal or lower than delay min");
}
return new Pair<>(delayMin, delayMax);
}
private void getAndPrintServerInfo(InetSocketAddress inetAddr) {
//print info
Logger.info("Server Address:", inetAddr.getHostString());
Logger.info("Server Port: " + inetAddr.getPort());
Logger.info("Bot count: " + getBotCount());
//get and print server info
ServerInfo serverInfo = new ServerInfo(inetAddr);
serverInfo.requestInfo();
ServerStatusInfo statusInfo = serverInfo.getStatusInfo();
if (statusInfo != null) {
Logger.info(
"Server version: "
+ statusInfo.getVersionInfo().getVersionName()
+ " (" + statusInfo.getVersionInfo().getProtocolVersion()
+ ")"
);
Logger.info("Player Count: " + statusInfo.getPlayerInfo().getOnlinePlayers()
+ " / " + statusInfo.getPlayerInfo().getMaxPlayers());
Logger.info();
} else {
Logger.warn("There was an error retrieving server status information. The server may be offline or running on a different version.");
}
}
public void renewMainListener() {
this.bots.get(0).registerMainListener();
}
@Override
public void removeBot(Bot bot) {
super.removeBot(bot);
controlledBots.remove(bot);
if (bot.hasMainListener()) {
Logger.info("Bot with MainListener removed");
this.isMainListenerMissing = true;
}
if (!this.bots.isEmpty()) {
if (this.isMainListenerMissing && !isMinimal()) {
Logger.info("Renewing MainListener");
renewMainListener();
this.isMainListenerMissing = false;
}
} else {
if (this.botLoader.getTriedToConnect() == getBotCount()) {
Logger.error("All bots disconnected, exiting");
System.exit(0);
}
}
}
public String getPrompt() {
int count = this.getControlledBots().size();
if (count == 0) {
return "ALL";
} else if (count == 1) {
//If controlling only one bot, return its nickname
return getControlledBots().iterator().next().getNickname();
} else {
return count + " BOTS";
}
}
public int getBotCount() {
return this.botCount;
}
public void setBotCount(int botCount) {
this.botCount = botCount;
}
public int getDelayMin() {
return this.delayMin;
}
public int getDelayMax() {
return this.delayMax;
}
public boolean isColoredChat() {
return this.coloredChat;
}
public boolean isOnline() {
return this.online;
}
@Nullable
public ProxyGenerator getProxyGenerator() {
return this.proxyGenerator;
}
public HashSet<Bot> getControlledBots() {
return this.controlledBots;
}
public AuthenticationService getAuthenticationService() {
return this.authenticationService;
}
public boolean isMainListenerMissing() {
return this.isMainListenerMissing;
}
public void setMainListenerMissing(boolean missing) {
this.isMainListenerMissing = missing;
}
}
@@ -1,101 +0,0 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.protocol.data.UnexpectedEncryptionException;
import com.github.steveice10.mc.protocol.data.game.ClientCommand;
import com.github.steveice10.mc.protocol.data.game.level.notify.GameEvent;
import com.github.steveice10.mc.protocol.data.game.level.notify.RespawnScreenValue;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundLoginPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerCombatKillPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundClientCommandPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import com.shanebeestudios.mcbots.api.util.Utils;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings({"CallToPrintStackTrace", "DuplicatedCode"})
public class StandaloneSessionListener extends BaseSessionListener {
@Override
public void packetReceived(Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket gameEventPacket) {
if (gameEventPacket.getNotification() == GameEvent.ENABLE_RESPAWN_SCREEN) {
RespawnScreenValue value = (RespawnScreenValue) gameEventPacket.getValue();
if (value == RespawnScreenValue.IMMEDIATE_RESPAWN) {
this.autoRespawnDelay = 0;
} else {
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
}
}
} else if (packet instanceof ClientboundLoginPacket loginPacket) {
if (!loginPacket.isEnableRespawnScreen()) {
this.autoRespawnDelay = 0;
}
this.bot.setConnected(true);
Logger.info(this.bot.getNickname() + " connected");
if (!this.joinMessages.isEmpty()) {
for (String msg : this.joinMessages) {
this.bot.sendChat(msg);
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
}
} else if (packet instanceof ClientboundPlayerPositionPacket positionPacket) {
this.bot.setLastPosition(positionPacket.getX(), positionPacket.getY(), positionPacket.getZ());
this.client.send(new ServerboundAcceptTeleportationPacket(positionPacket.getTeleportId()));
} else if (packet instanceof ClientboundPlayerCombatKillPacket) {
if (this.autoRespawnDelay >= 0) {
Logger.info("Bot " + this.bot.getNickname() + " died. Respawning in " + this.autoRespawnDelay + " ms.");
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
StandaloneSessionListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
}
}, this.autoRespawnDelay);
}
}
}
@Override
public void disconnected(DisconnectedEvent event) {
this.bot.setConnected(false);
this.botManager.logBotDisconnected(this.bot.getNickname());
// Do not write disconnect reason if disconnected by command
if (!this.bot.isManualDisconnecting()) {
Component reason = event.getReason();
if (reason != null) {
String reasonText = Utils.getFullText((TextComponent) reason, true);
Logger.info("Reason: " + reasonText);
}
Throwable cause = event.getCause();
if (cause != null) {
cause.printStackTrace();
if (cause instanceof UnexpectedEncryptionException) {
Logger.warn("Server is running in online (premium) mode. Please use the -o option to use online mode bot.");
System.exit(1);
}
}
Logger.info();
}
this.botManager.removeBot(this.bot);
Thread.currentThread().interrupt();
}
}
File diff suppressed because it is too large. Load diff