mc-bots - big ol re-write
This commit is contained in:
1 parent
78cf07636d
commit
db634d6ae7
25 files changed
+1498
-1101
No files matched your search
+6
-5
@@ -5,8 +5,8 @@ plugins {
|
||||
group 'me.creepermaxcz.mc-bots'
|
||||
version '1.2.9'
|
||||
|
||||
sourceCompatibility = 1.8
|
||||
targetCompatibility = 1.8
|
||||
sourceCompatibility = 17
|
||||
targetCompatibility = 17
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
@@ -16,17 +16,18 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.github.steveice10:mcprotocollib:1.20.2-1'
|
||||
implementation 'com.github.steveice10:mcprotocollib:1.20.4-2-SNAPSHOT'
|
||||
implementation 'net.kyori:adventure-text-serializer-gson:4.16.0'
|
||||
implementation 'commons-cli:commons-cli:1.5.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.22.0'
|
||||
implementation 'org.jline:jline:3.25.0'
|
||||
}
|
||||
|
||||
jar {
|
||||
manifest {
|
||||
attributes 'Main-Class': 'me.creepermaxcz.mcbots.Main'
|
||||
attributes 'Main-Class': 'com.shanebeestudios.mcbots.standalone.Main', 'Manifest-Version': this.version
|
||||
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
|
||||
}
|
||||
from {
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
Manifest-Version: 1.0
|
||||
Main-Class: me.creepermaxcz.mcbots.Main
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.shanebeestudios.mcbots.api;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
public abstract class Info {
|
||||
|
||||
protected int autoRespawnDelay;
|
||||
protected boolean minimal;
|
||||
protected boolean mostMinimal = false;
|
||||
protected boolean useRealNicknames;
|
||||
protected String nickPath;
|
||||
protected String nickPrefix;
|
||||
protected String address;
|
||||
protected int port;
|
||||
protected boolean hasGravity;
|
||||
protected ArrayList<String> joinMessages = new ArrayList<>();
|
||||
|
||||
public Info() {
|
||||
}
|
||||
|
||||
public boolean isMinimal() {
|
||||
return this.minimal;
|
||||
}
|
||||
|
||||
public boolean isMostMinimal() {
|
||||
return this.mostMinimal;
|
||||
}
|
||||
|
||||
public int getAutoRespawnDelay() {
|
||||
return this.autoRespawnDelay;
|
||||
}
|
||||
|
||||
public boolean isUseRealNicknames() {
|
||||
return this.useRealNicknames;
|
||||
}
|
||||
|
||||
public String getNickPath() {
|
||||
return this.nickPath;
|
||||
}
|
||||
|
||||
public String getNickPrefix() {
|
||||
return this.nickPrefix;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return this.address;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return this.port;
|
||||
}
|
||||
|
||||
public boolean hasGravity() {
|
||||
return this.hasGravity;
|
||||
}
|
||||
|
||||
public ArrayList<String> getJoinMessages() {
|
||||
return this.joinMessages;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.shanebeestudios.mcbots.api;
|
||||
|
||||
import com.shanebeestudios.mcbots.api.timer.GravityTimer;
|
||||
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public abstract class Loader {
|
||||
|
||||
// Fields
|
||||
private final Info info;
|
||||
private final InetSocketAddress inetAddr;
|
||||
protected final ArrayList<Bot> bots = new ArrayList<>();
|
||||
protected NickGenerator nickGenerator;
|
||||
protected final GravityTimer gravityTimer;
|
||||
|
||||
public Loader(Info info) {
|
||||
this.info = info;
|
||||
this.inetAddr = createInetAddress();
|
||||
this.nickGenerator = new NickGenerator(info.getNickPath(), info.getNickPrefix(), info.isUseRealNicknames());
|
||||
this.gravityTimer = new GravityTimer(this);
|
||||
}
|
||||
|
||||
// Methods
|
||||
protected InetSocketAddress createInetAddress() {
|
||||
try {
|
||||
InetAddress inetAddress = InetAddress.getByName(this.info.getAddress());
|
||||
return new InetSocketAddress(inetAddress.getHostAddress(), this.info.getPort());
|
||||
} catch (UnknownHostException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public Info getInfoBase() {
|
||||
return this.info;
|
||||
}
|
||||
|
||||
public InetSocketAddress getInetAddr() {
|
||||
return this.inetAddr;
|
||||
}
|
||||
|
||||
public ArrayList<Bot> getBots() {
|
||||
return this.bots;
|
||||
}
|
||||
|
||||
public NickGenerator getNickGenerator() {
|
||||
return this.nickGenerator;
|
||||
}
|
||||
|
||||
public abstract void removeBot(Bot bot);
|
||||
|
||||
}
|
||||
+11
-14
@@ -1,4 +1,4 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
package com.shanebeestudios.mcbots.api;
|
||||
|
||||
|
||||
import com.github.steveice10.mc.protocol.MinecraftConstants;
|
||||
@@ -21,19 +21,18 @@ public class ServerInfo {
|
||||
private boolean done;
|
||||
|
||||
public ServerInfo(InetSocketAddress address) {
|
||||
|
||||
MinecraftProtocol protocol = new MinecraftProtocol();
|
||||
client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, null);
|
||||
this.client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, null);
|
||||
|
||||
client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (ServerInfoHandler) (session, info) -> {
|
||||
this.client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (ServerInfoHandler) (session, info) -> {
|
||||
this.serverStatusInfo = info;
|
||||
});
|
||||
|
||||
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (ServerPingTimeHandler) (session, pingTime) -> {
|
||||
this.client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (ServerPingTimeHandler) (session, pingTime) -> {
|
||||
this.ping = pingTime;
|
||||
});
|
||||
|
||||
client.addListener(new SessionAdapter() {
|
||||
this.client.addListener(new SessionAdapter() {
|
||||
@Override
|
||||
public void disconnected(DisconnectedEvent event) {
|
||||
done = true;
|
||||
@@ -41,12 +40,11 @@ public class ServerInfo {
|
||||
});
|
||||
}
|
||||
|
||||
public void requestInfo()
|
||||
{
|
||||
client.connect();
|
||||
public void requestInfo() {
|
||||
this.client.connect();
|
||||
|
||||
//wait to disconnect
|
||||
while (!done) {
|
||||
while (!this.done) {
|
||||
try {
|
||||
Thread.sleep(5);
|
||||
} catch (InterruptedException e) {
|
||||
@@ -55,12 +53,11 @@ public class ServerInfo {
|
||||
}
|
||||
}
|
||||
|
||||
public ServerStatusInfo getStatusInfo()
|
||||
{
|
||||
return serverStatusInfo;
|
||||
public ServerStatusInfo getStatusInfo() {
|
||||
return this.serverStatusInfo;
|
||||
}
|
||||
|
||||
public long getPing() {
|
||||
return ping;
|
||||
return this.ping;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package com.shanebeestudios.mcbots.api.generator;
|
||||
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@SuppressWarnings("FieldCanBeLocal")
|
||||
public class NickGenerator {
|
||||
|
||||
private static final int DEFAULT_NICK_LENGTH = 16; // Minecraft names can only be this long
|
||||
private final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
private int linesSize;
|
||||
private List<String> lines;
|
||||
private int nickLength = DEFAULT_NICK_LENGTH;
|
||||
private boolean real;
|
||||
private String prefix = "";
|
||||
|
||||
public NickGenerator(@Nullable String path, String prefix, boolean useRealNicknames) {
|
||||
if (path != null) {
|
||||
Logger.info("Loading nicknames from specified file");
|
||||
int nicksCount = loadFromFile(path);
|
||||
|
||||
if (nicksCount == 0) {
|
||||
Logger.error("No valid nicknames loaded");
|
||||
System.exit(1);
|
||||
}
|
||||
} else {
|
||||
if (useRealNicknames && this.lines == null) loadLines();
|
||||
this.real = useRealNicknames;
|
||||
}
|
||||
this.nickLength = DEFAULT_NICK_LENGTH - prefix.length();
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
private int loadFromFile(String filePath) {
|
||||
this.lines = new ArrayList<>();
|
||||
try {
|
||||
Scanner scanner = new Scanner(new File(filePath));
|
||||
while (scanner.hasNextLine()) {
|
||||
try {
|
||||
String line = scanner.nextLine().trim();
|
||||
|
||||
//add only valid nicknames
|
||||
if (line.matches("^[a-zA-Z0-9_]{3,16}$")) {
|
||||
this.lines.add(line);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
scanner.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
Logger.error("Invalid nicknames list file path");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
this.linesSize = this.lines.size();
|
||||
Logger.info("Loaded " + this.linesSize + " valid nicknames");
|
||||
this.real = true;
|
||||
|
||||
return this.linesSize;
|
||||
}
|
||||
|
||||
private void loadLines() {
|
||||
try (InputStream resource = getClass().getResourceAsStream("/files/nicks.txt")) {
|
||||
assert resource != null;
|
||||
lines = new BufferedReader(
|
||||
new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()
|
||||
);
|
||||
linesSize = lines.size();
|
||||
} catch (Exception e) {
|
||||
Logger.error(e);
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private String generateRandom(int len) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < len; i++) {
|
||||
result.append(CHARS.charAt(random.nextInt(CHARS.length())));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public String nextReal() {
|
||||
String nick = this.prefix + this.lines.get(this.random.nextInt(this.linesSize));
|
||||
return nick.length() <= 16 ? nick : nick.substring(0, 15);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate next nick
|
||||
*
|
||||
* @return generated nick
|
||||
*/
|
||||
public String nextNick() {
|
||||
return this.real ? nextReal() : (this.prefix + generateRandom(this.nickLength));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.shanebeestudios.mcbots.api.generator;
|
||||
|
||||
import com.github.steveice10.packetlib.ProxyInfo;
|
||||
import com.shanebeestudios.mcbots.api.util.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.shanebeestudios.mcbots.api.timer;
|
||||
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
import com.shanebeestudios.mcbots.api.Loader;
|
||||
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
public class GravityTimer {
|
||||
|
||||
private final Timer timer = new Timer();
|
||||
private final Loader loader;
|
||||
|
||||
public GravityTimer(Loader loader) {
|
||||
this.loader = loader;
|
||||
}
|
||||
|
||||
public void startTimer() {
|
||||
this.timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
GravityTimer.this.loader.getBots().forEach(Bot::fallDown);
|
||||
}
|
||||
}, 1000L, 50L);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.shanebeestudios.mcbots.api.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class Logger {
|
||||
|
||||
private static final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
|
||||
|
||||
public static void log(String prefix, String message) {
|
||||
System.out.println("\r[" + formatter.format(new Date()) + " " + prefix + "] " + message);
|
||||
//System.out.print(StandaloneLoader.getInstance().getPrompt() + "> ");
|
||||
}
|
||||
|
||||
public static void error(String error) {
|
||||
log("ERROR", error);
|
||||
}
|
||||
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public static void error(Exception e) {
|
||||
log("ERROR", "");
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
public static void info(String... message) {
|
||||
log("INFO", String.join(" ", message));
|
||||
}
|
||||
|
||||
public static void info() {
|
||||
log("INFO", "");
|
||||
}
|
||||
|
||||
public static void warn(String... warning) {
|
||||
log("WARN", String.join(" ", warning));
|
||||
}
|
||||
|
||||
public static void warn() {
|
||||
log("WARN", "");
|
||||
}
|
||||
|
||||
public static void chat(String... chat) {
|
||||
log("CHAT", String.join(" ", chat));
|
||||
}
|
||||
|
||||
public static void critical(Exception e) {
|
||||
error(e);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.shanebeestudios.mcbots.api.util;
|
||||
|
||||
public class Pair<F,S> {
|
||||
|
||||
private final F first;
|
||||
private final S second;
|
||||
|
||||
public Pair(F first, S second) {
|
||||
this.first = first;
|
||||
this.second = second;
|
||||
}
|
||||
|
||||
public F getFirst() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public S getSecond() {
|
||||
return second;
|
||||
}
|
||||
|
||||
}
|
||||
+19
-17
@@ -1,4 +1,4 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
package com.shanebeestudios.mcbots.api.util;
|
||||
|
||||
import com.diogonunes.jcolor.Attribute;
|
||||
import com.google.gson.JsonElement;
|
||||
@@ -7,6 +7,7 @@ import com.google.gson.JsonParser;
|
||||
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;
|
||||
@@ -25,7 +26,7 @@ public class Utils {
|
||||
private static JsonObject lang;
|
||||
|
||||
public static String getFullText(TextComponent message, boolean colored) {
|
||||
if (message.children().size() > 0) {
|
||||
if (!message.children().isEmpty()) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
text.append(parseColor(message, colored));
|
||||
for (Component child : message.children()) {
|
||||
@@ -60,16 +61,18 @@ public class Utils {
|
||||
|
||||
if (sender != null) {
|
||||
Style senderStyle = sender.style();
|
||||
if (senderStyle.color() != null) { // Generate sender text with color.
|
||||
outString.append(colorizeText(sender.content(), senderStyle.color()));
|
||||
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.
|
||||
}
|
||||
|
||||
if (messageStyle.color() != null && sender != null) { // Generate message text with color.
|
||||
outString.append(colorizeText(sender.content(), messageStyle.color()));
|
||||
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());
|
||||
}
|
||||
@@ -86,9 +89,9 @@ public class Utils {
|
||||
private static String parseColor(TextComponent message, boolean colored) {
|
||||
String out = message.content();
|
||||
if (colored) {
|
||||
if (message.style().color() != null) {
|
||||
List<Attribute> formats = new ArrayList<>(getFormats(message.style().decorations()));
|
||||
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]));
|
||||
}
|
||||
@@ -124,12 +127,12 @@ public class Utils {
|
||||
if (lang == null) {
|
||||
try {
|
||||
InputStream resource = Utils.class.getResourceAsStream("/files/lang.json");
|
||||
if (resource == null) return null;
|
||||
lang = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject();
|
||||
} catch (Exception e) {
|
||||
Log.crit(e);
|
||||
Logger.critical(e);
|
||||
}
|
||||
}
|
||||
//Log.info(message.toString());
|
||||
|
||||
String key = message.key();
|
||||
String base = key;
|
||||
@@ -141,15 +144,14 @@ public class Utils {
|
||||
|
||||
ArrayList<String> placeholders = new ArrayList<>();
|
||||
|
||||
if (message.args().size() > 0) {
|
||||
for (Component component : message.args()) {
|
||||
if (component instanceof TranslatableComponent) {
|
||||
placeholders.add(translate((TranslatableComponent) component));
|
||||
} else if (component instanceof TextComponent) {
|
||||
placeholders.add(getFullText((TextComponent) component, false));
|
||||
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));
|
||||
}
|
||||
}
|
||||
//Log.info(Arrays.toString(placeholders.toArray()));
|
||||
return String.format(base, placeholders.toArray());
|
||||
} else {
|
||||
return base;
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.shanebeestudios.mcbots.bot;
|
||||
|
||||
import com.github.steveice10.mc.auth.service.AuthenticationService;
|
||||
import com.github.steveice10.mc.auth.service.SessionService;
|
||||
import com.github.steveice10.mc.protocol.MinecraftConstants;
|
||||
import com.github.steveice10.mc.protocol.MinecraftProtocol;
|
||||
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundChatCommandPacket;
|
||||
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundChatPacket;
|
||||
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.player.ServerboundMovePlayerPosPacket;
|
||||
import com.github.steveice10.packetlib.ProxyInfo;
|
||||
import com.github.steveice10.packetlib.Session;
|
||||
import com.github.steveice10.packetlib.packet.Packet;
|
||||
import com.github.steveice10.packetlib.tcp.TcpClientSession;
|
||||
import com.shanebeestudios.mcbots.api.Loader;
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
import com.shanebeestudios.mcbots.listener.ClientListener;
|
||||
import com.shanebeestudios.mcbots.listener.MessageListener;
|
||||
import com.shanebeestudios.mcbots.standalone.StandaloneLoader;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Instant;
|
||||
import java.util.BitSet;
|
||||
import java.util.Collections;
|
||||
|
||||
public class Bot {
|
||||
|
||||
private final MinecraftProtocol protocol;
|
||||
private final Loader loader;
|
||||
private final String nickname;
|
||||
private final Session client;
|
||||
private boolean hasMainListener;
|
||||
private double lastX, lastY, lastZ = -1;
|
||||
private boolean connected;
|
||||
private boolean manualDisconnecting = false;
|
||||
|
||||
public Bot(StandaloneLoader loader, String nickname, InetSocketAddress address, ProxyInfo proxy) {
|
||||
this.loader = loader;
|
||||
this.nickname = nickname;
|
||||
|
||||
Logger.info("Creating bot", nickname);
|
||||
this.protocol = new MinecraftProtocol(nickname);
|
||||
this.client = new TcpClientSession(address.getHostString(), address.getPort(), this.protocol, proxy);
|
||||
}
|
||||
|
||||
public Bot(StandaloneLoader loader, AuthenticationService authService, InetSocketAddress address, ProxyInfo proxy) {
|
||||
this.loader = loader;
|
||||
this.nickname = authService.getUsername();
|
||||
|
||||
Logger.info("Creating bot", nickname);
|
||||
this.protocol = new MinecraftProtocol(authService.getSelectedProfile(), authService.getAccessToken());
|
||||
|
||||
this.client = new TcpClientSession(address.getHostString(), address.getPort(), this.protocol, proxy);
|
||||
|
||||
SessionService sessionService = new SessionService();
|
||||
this.client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect the bot to the server
|
||||
*/
|
||||
public void connect() {
|
||||
new Thread(() -> {
|
||||
if (!this.loader.getInfoBase().isMinimal()) {
|
||||
this.client.addListener(new ClientListener(this));
|
||||
}
|
||||
this.client.connect();
|
||||
}).start();;
|
||||
}
|
||||
|
||||
public Loader getLoader() {
|
||||
return this.loader;
|
||||
}
|
||||
|
||||
public Session getClient() {
|
||||
return this.client;
|
||||
}
|
||||
|
||||
public String getNickname() {
|
||||
return this.nickname;
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return this.connected;
|
||||
}
|
||||
|
||||
public void setConnected(boolean connected) {
|
||||
this.connected = connected;
|
||||
}
|
||||
|
||||
public boolean isManualDisconnecting() {
|
||||
return this.manualDisconnecting;
|
||||
}
|
||||
|
||||
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,
|
||||
// The server console will print out that the message was "expired". To avoid this, set timeStamp as now.
|
||||
long timeStamp = Instant.now().toEpochMilli();
|
||||
BitSet bitSet = new BitSet();
|
||||
|
||||
Packet packet;
|
||||
if (text.startsWith("/")) {
|
||||
// Send command
|
||||
packet = new ServerboundChatCommandPacket(text.substring(1), timeStamp, 0L, Collections.emptyList(), 0, bitSet);
|
||||
} else {
|
||||
// Send chat message
|
||||
// From 1.19.1 or 1.19, the ServerboundChatPacket needs timestamp, salt and signed signature to generate packet.
|
||||
// tmpSignature will provide an empty byte array that can pretend it as signature.
|
||||
// salt is set 0 since this is offline server and nobody will check it.
|
||||
packet = new ServerboundChatPacket(text, timeStamp, 0L, null, 0, bitSet);
|
||||
}
|
||||
this.client.send(packet);
|
||||
}
|
||||
|
||||
public boolean hasMainListener() {
|
||||
return this.hasMainListener;
|
||||
}
|
||||
|
||||
public void registerMainListener() {
|
||||
this.hasMainListener = true;
|
||||
if (this.loader.getInfoBase().isMinimal()) return;
|
||||
this.client.addListener(new MessageListener(this));
|
||||
}
|
||||
|
||||
public void fallDown() {
|
||||
if (this.connected && this.lastY > 0) {
|
||||
move(0, -0.5, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public void setLastPosition(double x, double y, double z) {
|
||||
this.lastX = x;
|
||||
this.lastY = y;
|
||||
this.lastZ = z;
|
||||
}
|
||||
|
||||
public void move(double x, double y, double z) {
|
||||
this.lastX += x;
|
||||
this.lastY += y;
|
||||
this.lastZ += z;
|
||||
moveTo(this.lastX, this.lastY, this.lastZ);
|
||||
}
|
||||
|
||||
public void moveTo(double x, double y, double z) {
|
||||
this.client.send(new ServerboundMovePlayerPosPacket(true, x, y, z));
|
||||
}
|
||||
|
||||
public void disconnect() {
|
||||
this.manualDisconnecting = true;
|
||||
this.client.disconnect("Leaving");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.shanebeestudios.mcbots.bot;
|
||||
|
||||
import com.github.steveice10.mc.auth.service.AuthenticationService;
|
||||
import com.github.steveice10.packetlib.ProxyInfo;
|
||||
import com.shanebeestudios.mcbots.standalone.StandaloneLoader;
|
||||
import com.shanebeestudios.mcbots.standalone.StandaloneInfo;
|
||||
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
|
||||
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Random;
|
||||
|
||||
public class BotLoader {
|
||||
|
||||
private final StandaloneLoader standaloneLoader;
|
||||
private final StandaloneInfo standaloneInfo;
|
||||
private final int delayMin;
|
||||
private final int delayMax;
|
||||
private final Random random;
|
||||
private int triedToConnect = 0;
|
||||
private int proxyIndex = 0;
|
||||
|
||||
public BotLoader(StandaloneLoader standaloneLoader) {
|
||||
this.standaloneLoader = standaloneLoader;
|
||||
this.standaloneInfo = standaloneLoader.getMainInfo();
|
||||
this.delayMin = this.standaloneInfo.getDelayMin();
|
||||
this.delayMax = this.standaloneInfo.getDelayMax();
|
||||
this.random = new Random();
|
||||
}
|
||||
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public void spin() {
|
||||
int botCount = this.standaloneInfo.getBotCount();
|
||||
boolean minimal = this.standaloneInfo.isMinimal();
|
||||
boolean mostMinimal = this.standaloneInfo.isMostMinimal();
|
||||
InetSocketAddress inetAddr = this.standaloneLoader.getInetAddr();
|
||||
NickGenerator nickGenerator = this.standaloneLoader.getNickGenerator();
|
||||
AuthenticationService authService = this.standaloneLoader.getAuthenticationService();
|
||||
|
||||
ProxyGenerator proxyGenerator = this.standaloneInfo.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.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package com.shanebeestudios.mcbots.listener;
|
||||
|
||||
import com.github.steveice10.mc.protocol.data.UnexpectedEncryptionException;
|
||||
import com.github.steveice10.mc.protocol.data.game.ClientCommand;
|
||||
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.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.event.session.SessionAdapter;
|
||||
import com.github.steveice10.packetlib.packet.Packet;
|
||||
import com.shanebeestudios.mcbots.api.Loader;
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@SuppressWarnings("CallToPrintStackTrace")
|
||||
public class ClientListener extends SessionAdapter {
|
||||
|
||||
private final Bot bot;
|
||||
private final Session client;
|
||||
private final Loader loader;
|
||||
private final ArrayList<String> joinMessages;
|
||||
private final int autoRespawnDelay;
|
||||
|
||||
public ClientListener(Bot bot) {
|
||||
this.bot = bot;
|
||||
this.client = bot.getClient();
|
||||
this.loader = bot.getLoader();
|
||||
this.joinMessages = this.loader.getInfoBase().getJoinMessages();
|
||||
this.autoRespawnDelay = this.loader.getInfoBase().getAutoRespawnDelay();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetReceived(Session session, Packet packet) {
|
||||
if (packet instanceof ClientboundLoginPacket) {
|
||||
this.bot.setConnected(true);
|
||||
Logger.info(this.bot.getNickname() + " connected");
|
||||
|
||||
if (!this.joinMessages.isEmpty()) {
|
||||
for (String msg : 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() {
|
||||
ClientListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
|
||||
}
|
||||
}, this.autoRespawnDelay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnected(DisconnectedEvent event) {
|
||||
this.bot.setConnected(false);
|
||||
Logger.info(this.bot.getNickname() + " disconnected");
|
||||
|
||||
// Do not write disconnect reason if disconnected by command
|
||||
if (!this.bot.isManualDisconnecting()) {
|
||||
// Fix broken reason string by finding the content with regex
|
||||
Pattern pattern = Pattern.compile("content=\"(.*?)\"");
|
||||
Matcher matcher = pattern.matcher(String.valueOf(event.getReason()));
|
||||
|
||||
StringBuilder reason = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
reason.append(matcher.group(1));
|
||||
}
|
||||
|
||||
Logger.info(" -> " + reason);
|
||||
|
||||
if (event.getCause() != null) {
|
||||
event.getCause().printStackTrace();
|
||||
|
||||
if (event.getCause() 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.loader.removeBot(this.bot);
|
||||
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.shanebeestudios.mcbots.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.ConnectedEvent;
|
||||
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
|
||||
import com.github.steveice10.packetlib.event.session.DisconnectingEvent;
|
||||
import com.github.steveice10.packetlib.event.session.PacketErrorEvent;
|
||||
import com.github.steveice10.packetlib.event.session.PacketSendingEvent;
|
||||
import com.github.steveice10.packetlib.event.session.SessionListener;
|
||||
import com.github.steveice10.packetlib.packet.Packet;
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
import com.shanebeestudios.mcbots.standalone.StandaloneInfo;
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
import com.shanebeestudios.mcbots.api.util.Utils;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.TranslatableComponent;
|
||||
|
||||
public class MessageListener implements SessionListener {
|
||||
|
||||
private final boolean coloredChat;
|
||||
|
||||
public MessageListener(Bot bot) {
|
||||
this.coloredChat = !(bot.getLoader().getInfoBase() instanceof StandaloneInfo standaloneInfo) || standaloneInfo.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));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetSending(PacketSendingEvent event) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetSent(Session session, Packet packet) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetError(PacketErrorEvent event) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connected(ConnectedEvent event) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnecting(DisconnectingEvent event) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnected(DisconnectedEvent event) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package com.shanebeestudios.mcbots.standalone;
|
||||
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
import com.shanebeestudios.mcbots.api.util.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 StandaloneLoader standaloneLoader;
|
||||
|
||||
public ConsoleReader(StandaloneLoader 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.shanebeestudios.mcbots.standalone;
|
||||
|
||||
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)");
|
||||
|
||||
StandaloneInfo standaloneInfo = new StandaloneInfo(options, args);
|
||||
new StandaloneLoader(standaloneInfo);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.shanebeestudios.mcbots.standalone;
|
||||
|
||||
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.Logger;
|
||||
|
||||
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 StandaloneInfo standaloneInfo;
|
||||
|
||||
public OnlineService(StandaloneInfo standaloneInfo) {
|
||||
this.standaloneInfo = standaloneInfo;
|
||||
}
|
||||
|
||||
public AuthenticationService getOnlineAuthenticationService() {
|
||||
Logger.warn("Online mode enabled. The bot count will be set to 1.");
|
||||
this.standaloneInfo.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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package com.shanebeestudios.mcbots.standalone;
|
||||
|
||||
import com.shanebeestudios.mcbots.api.Info;
|
||||
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
|
||||
import com.shanebeestudios.mcbots.api.util.Pair;
|
||||
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;
|
||||
|
||||
public class StandaloneInfo extends Info {
|
||||
|
||||
private int botCount;
|
||||
private final int delayMin;
|
||||
private final int delayMax;
|
||||
private final boolean coloredChat;
|
||||
private final boolean online;
|
||||
|
||||
private ProxyGenerator proxyGenerator;
|
||||
|
||||
public StandaloneInfo(Options options, String[] args) {
|
||||
super();
|
||||
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/crpmax/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.address = addressPort.getFirst();
|
||||
this.port = 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());
|
||||
}
|
||||
}
|
||||
|
||||
this.useRealNicknames = cmd.hasOption('r');
|
||||
this.nickPath = cmd.getOptionValue("nicks", null);
|
||||
this.nickPrefix = cmd.getOptionValue('p', "");
|
||||
|
||||
this.online = cmd.hasOption("o");
|
||||
this.hasGravity = cmd.hasOption("g");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package com.shanebeestudios.mcbots.standalone;
|
||||
|
||||
import com.github.steveice10.mc.auth.service.AuthenticationService;
|
||||
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
|
||||
import com.shanebeestudios.mcbots.api.ServerInfo;
|
||||
import com.shanebeestudios.mcbots.api.Loader;
|
||||
import com.shanebeestudios.mcbots.bot.Bot;
|
||||
import com.shanebeestudios.mcbots.bot.BotLoader;
|
||||
import com.shanebeestudios.mcbots.api.util.Logger;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.util.HashSet;
|
||||
|
||||
public class StandaloneLoader extends Loader {
|
||||
|
||||
private final StandaloneInfo standaloneInfo;
|
||||
private final HashSet<Bot> controlledBots = new HashSet<>();
|
||||
|
||||
|
||||
private final AuthenticationService authenticationService;
|
||||
private final BotLoader botLoader;
|
||||
|
||||
private boolean isMainListenerMissing = true;
|
||||
|
||||
public StandaloneLoader(StandaloneInfo standaloneInfo) {
|
||||
super(standaloneInfo);
|
||||
this.standaloneInfo = standaloneInfo;
|
||||
|
||||
getAndPrintServerInfo(getInetAddr());
|
||||
|
||||
if (standaloneInfo.isOnline()) {
|
||||
OnlineService onlineService = new OnlineService(standaloneInfo);
|
||||
this.authenticationService = onlineService.getOnlineAuthenticationService();
|
||||
} else {
|
||||
this.authenticationService = null;
|
||||
}
|
||||
|
||||
// Load bots
|
||||
this.botLoader = new BotLoader(this);
|
||||
this.botLoader.spin();
|
||||
if (standaloneInfo.hasGravity()) {
|
||||
this.gravityTimer.startTimer();
|
||||
}
|
||||
|
||||
// Load console reader
|
||||
ConsoleReader consoleReader = new ConsoleReader(this);
|
||||
consoleReader.start();
|
||||
}
|
||||
|
||||
private void getAndPrintServerInfo(InetSocketAddress inetAddr) {
|
||||
//print info
|
||||
Logger.info("Server Address:", inetAddr.getHostString());
|
||||
Logger.info("Server Port: " + inetAddr.getPort());
|
||||
Logger.info("Bot count: " + standaloneInfo.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();
|
||||
}
|
||||
|
||||
public void removeBot(Bot bot) {
|
||||
this.bots.remove(bot);
|
||||
controlledBots.remove(bot);
|
||||
if (bot.hasMainListener()) {
|
||||
Logger.info("Bot with MainListener removed");
|
||||
this.isMainListenerMissing = true;
|
||||
}
|
||||
if (!this.bots.isEmpty()) {
|
||||
if (this.isMainListenerMissing && !this.standaloneInfo.isMinimal()) {
|
||||
Logger.info("Renewing MainListener");
|
||||
renewMainListener();
|
||||
this.isMainListenerMissing = false;
|
||||
}
|
||||
} else {
|
||||
if (this.botLoader.getTriedToConnect() == this.standaloneInfo.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 Bot findBotByName(String text) {
|
||||
for (Bot bot : this.getBots()) {
|
||||
// Starts with and ignore case
|
||||
// https://stackoverflow.com/a/38947571/11787611
|
||||
if (bot.getNickname().regionMatches(true, 0, text, 0, text.length())) {
|
||||
return bot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public StandaloneInfo getMainInfo() {
|
||||
return this.standaloneInfo;
|
||||
}
|
||||
|
||||
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,232 +0,0 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
|
||||
import com.github.steveice10.mc.auth.service.AuthenticationService;
|
||||
import com.github.steveice10.mc.auth.service.SessionService;
|
||||
import com.github.steveice10.mc.protocol.MinecraftConstants;
|
||||
import com.github.steveice10.mc.protocol.MinecraftProtocol;
|
||||
import com.github.steveice10.mc.protocol.data.UnexpectedEncryptionException;
|
||||
import com.github.steveice10.mc.protocol.data.game.ClientCommand;
|
||||
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.serverbound.ServerboundChatCommandPacket;
|
||||
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundChatPacket;
|
||||
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.mc.protocol.packet.ingame.serverbound.player.*;
|
||||
import com.github.steveice10.packetlib.ProxyInfo;
|
||||
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.packet.Packet;
|
||||
import com.github.steveice10.packetlib.tcp.TcpClientSession;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.time.Instant;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class Bot extends Thread {
|
||||
|
||||
MinecraftProtocol protocol = null;
|
||||
|
||||
private String nickname;
|
||||
private ProxyInfo proxy;
|
||||
private InetSocketAddress address;
|
||||
private Session client;
|
||||
private boolean hasMainListener;
|
||||
|
||||
private double lastX, lastY, lastZ = -1;
|
||||
|
||||
private boolean connected;
|
||||
|
||||
private boolean manualDisconnecting = false;
|
||||
|
||||
public Bot(String nickname, InetSocketAddress address, ProxyInfo proxy) {
|
||||
this.nickname = nickname;
|
||||
this.address = address;
|
||||
this.proxy = proxy;
|
||||
|
||||
Log.info("Creating bot", nickname);
|
||||
protocol = new MinecraftProtocol(nickname);
|
||||
client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, proxy);
|
||||
}
|
||||
|
||||
public Bot(AuthenticationService authService, InetSocketAddress address, ProxyInfo proxy) {
|
||||
this.nickname = authService.getUsername();
|
||||
this.address = address;
|
||||
this.proxy = proxy;
|
||||
|
||||
Log.info("Creating bot", nickname);
|
||||
protocol = new MinecraftProtocol(authService.getSelectedProfile(), authService.getAccessToken());
|
||||
|
||||
client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, proxy);
|
||||
|
||||
SessionService sessionService = new SessionService();
|
||||
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
|
||||
if (!Main.isMinimal()) {
|
||||
client.addListener(new SessionAdapter() {
|
||||
|
||||
@Override
|
||||
public void packetReceived(Session session, Packet packet) {
|
||||
if (packet instanceof ClientboundLoginPacket) {
|
||||
connected = true;
|
||||
Log.info(nickname + " connected");
|
||||
|
||||
if (Main.joinMessages.size() > 0) {
|
||||
for (String msg : Main.joinMessages) {
|
||||
sendChat(msg);
|
||||
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (packet instanceof ClientboundPlayerPositionPacket) {
|
||||
ClientboundPlayerPositionPacket p = (ClientboundPlayerPositionPacket) packet;
|
||||
|
||||
lastX = p.getX();
|
||||
lastY = p.getY();
|
||||
lastZ = p.getZ();
|
||||
|
||||
client.send(new ServerboundAcceptTeleportationPacket(p.getTeleportId()));
|
||||
}
|
||||
else if (packet instanceof ClientboundPlayerCombatKillPacket){
|
||||
if (Main.autoRespawnDelay >= 0) {
|
||||
Log.info("Bot " + nickname + " died. Respawning in " + Main.autoRespawnDelay + " ms.");
|
||||
new Timer().schedule(
|
||||
new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
|
||||
}
|
||||
},
|
||||
Main.autoRespawnDelay
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnected(DisconnectedEvent event) {
|
||||
connected = false;
|
||||
Log.info(nickname + " disconnected");
|
||||
|
||||
// Do not write disconnect reason if disconnected by command
|
||||
if (!manualDisconnecting) {
|
||||
// Fix broken reason string by finding the content with regex
|
||||
Pattern pattern = Pattern.compile("content=\"(.*?)\"");
|
||||
Matcher matcher = pattern.matcher(String.valueOf(event.getReason()));
|
||||
|
||||
StringBuilder reason = new StringBuilder();
|
||||
while (matcher.find()) {
|
||||
reason.append(matcher.group(1));
|
||||
}
|
||||
|
||||
Log.info(" -> " + reason.toString());
|
||||
|
||||
if(event.getCause() != null) {
|
||||
event.getCause().printStackTrace();
|
||||
|
||||
if (event.getCause() instanceof UnexpectedEncryptionException) {
|
||||
Log.warn("Server is running in online (premium) mode. Please use the -o option to use online mode bot.");
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
Log.info();
|
||||
}
|
||||
|
||||
Main.removeBot(Bot.this);
|
||||
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
});
|
||||
}
|
||||
client.connect();
|
||||
}
|
||||
|
||||
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,
|
||||
// The server console will print out that the message was "expired". To avoid this, set timeStamp as now.
|
||||
long timeStamp = Instant.now().toEpochMilli();
|
||||
|
||||
// Send command
|
||||
if (text.startsWith("/")) {
|
||||
client.send(new ServerboundChatCommandPacket(
|
||||
text.substring(1),
|
||||
timeStamp,
|
||||
0L,
|
||||
Collections.emptyList(),
|
||||
0,
|
||||
new BitSet()
|
||||
));
|
||||
} else {
|
||||
// Send chat message
|
||||
// From 1.19.1 or 1.19, the ServerboundChatPacket needs timestamp, salt and signed signature to generate packet.
|
||||
// tmpSignature will provide an empty byte array that can pretend it as signature.
|
||||
// salt is set 0 since this is offline server and no body will check it.
|
||||
|
||||
client.send(new ServerboundChatPacket(
|
||||
text,
|
||||
Instant.now().toEpochMilli(),
|
||||
0L,
|
||||
null,
|
||||
0,
|
||||
new BitSet()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public String getNickname() {
|
||||
return nickname;
|
||||
}
|
||||
|
||||
public void registerMainListener() {
|
||||
hasMainListener = true;
|
||||
if (Main.isMinimal()) return;
|
||||
client.addListener(new MainListener(nickname));
|
||||
}
|
||||
|
||||
public boolean hasMainListener() {
|
||||
return hasMainListener;
|
||||
}
|
||||
|
||||
public void fallDown()
|
||||
{
|
||||
if (connected && lastY > 0) {
|
||||
move(0, -0.5, 0);
|
||||
}
|
||||
}
|
||||
|
||||
public void move(double x, double y, double z)
|
||||
{
|
||||
lastX += x;
|
||||
lastY += y;
|
||||
lastZ += z;
|
||||
moveTo(lastX, lastY, lastZ);
|
||||
}
|
||||
|
||||
public void moveTo(double x, double y, double z)
|
||||
{
|
||||
client.send(new ServerboundMovePlayerPosPacket(true, x, y, z));
|
||||
}
|
||||
|
||||
public boolean isConnected() {
|
||||
return connected;
|
||||
}
|
||||
|
||||
public void disconnect()
|
||||
{
|
||||
manualDisconnecting = true;
|
||||
client.disconnect("Leaving");
|
||||
}
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public class Log {
|
||||
|
||||
private static final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
|
||||
|
||||
public static void log(String in) {
|
||||
System.out.println("\r[" + formatter.format(new Date()) + "] " + in);
|
||||
System.out.print(Main.getPrompt() + "> ");
|
||||
}
|
||||
|
||||
public static void error(String in) {
|
||||
log("ERROR | " + in);
|
||||
}
|
||||
|
||||
public static void error(Exception e) {
|
||||
log("ERROR | ");
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
public static void info(String ...in) {
|
||||
log("INFO | " + String.join(" ", in));
|
||||
}
|
||||
public static void info() {
|
||||
log("INFO | ");
|
||||
}
|
||||
|
||||
public static void warn(String ...in) {
|
||||
log("WARN | " + String.join(" ", in));
|
||||
}
|
||||
public static void warn() {
|
||||
log("WARN | ");
|
||||
}
|
||||
|
||||
public static void chat(String ...in) {
|
||||
log("CHAT | " + String.join(" ", in));
|
||||
}
|
||||
|
||||
public static void crit(Exception e) {
|
||||
error(e);
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
@@ -1,585 +0,0 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
|
||||
import com.github.steveice10.mc.auth.exception.request.AuthPendingException;
|
||||
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.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
|
||||
import com.github.steveice10.packetlib.ProxyInfo;
|
||||
import org.apache.commons.cli.*;
|
||||
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 org.xbill.DNS.Lookup;
|
||||
import org.xbill.DNS.Record;
|
||||
import org.xbill.DNS.SRVRecord;
|
||||
import org.xbill.DNS.Type;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
|
||||
public class Main {
|
||||
|
||||
public static boolean coloredChat = true;
|
||||
static ArrayList<Bot> bots = new ArrayList<>();
|
||||
private static int triedToConnect;
|
||||
private static int botCount;
|
||||
private static boolean isMainListenerMissing = true;
|
||||
private static final SecureRandom random = new SecureRandom();
|
||||
private static int delayMin = 4000;
|
||||
private static int delayMax = 5000;
|
||||
private static boolean minimal = false;
|
||||
private static boolean mostMinimal = false;
|
||||
public static ArrayList<String> joinMessages = new ArrayList<>();
|
||||
|
||||
public static String prompt = "?";
|
||||
|
||||
public static int autoRespawnDelay = 100;
|
||||
|
||||
private static boolean useProxies = false;
|
||||
private static final ArrayList<InetSocketAddress> proxies = new ArrayList<>();
|
||||
private static int proxyIndex = 0;
|
||||
private static int proxyCount = 0;
|
||||
private static ProxyInfo.Type proxyType;
|
||||
|
||||
private static final String CLIENT_ID = "8bef943e-5a63-429e-a93a-96391d2e32a9";
|
||||
|
||||
private static Timer timer = new Timer();
|
||||
private static final HashSet<Bot> controlledBots = new HashSet<>();
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
|
||||
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)");
|
||||
|
||||
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/crpmax/mc-bots",true);
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
autoRespawnDelay = Integer.parseInt(cmd.getOptionValue("ar", "100"));
|
||||
|
||||
if (cmd.hasOption('t') && cmd.hasOption('l')) {
|
||||
String typeStr = cmd.getOptionValue('t').toUpperCase();
|
||||
|
||||
//get proxy type
|
||||
try {
|
||||
proxyType = ProxyInfo.Type.valueOf(typeStr);
|
||||
} catch (IllegalArgumentException e) {
|
||||
Log.error("Inavlid proxy type, use SOCKS4 or SOCKS5.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
String proxyPath = cmd.getOptionValue("l");
|
||||
|
||||
//read proxy list file
|
||||
try {
|
||||
|
||||
try {
|
||||
//try to read specified path as URL
|
||||
URL url = new URL(proxyPath);
|
||||
|
||||
BufferedReader read = new BufferedReader(
|
||||
new InputStreamReader(url.openStream()));
|
||||
|
||||
Log.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]);
|
||||
proxies.add(new InetSocketAddress(parts[0], port));
|
||||
proxyCount++;
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) { }
|
||||
}
|
||||
read.close();
|
||||
|
||||
} catch (MalformedURLException e) {
|
||||
Log.info("Specified proxy file is not a URL, trying to read file");
|
||||
|
||||
Scanner scanner = new Scanner(new File(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));
|
||||
proxyCount++;
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) { }
|
||||
}
|
||||
scanner.close();
|
||||
}
|
||||
} catch (FileNotFoundException e) {
|
||||
Log.error("Invalid proxy list file path.");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
if (proxyCount > 0) {
|
||||
useProxies = true;
|
||||
Log.info("Loaded " + proxyCount + " valid proxies");
|
||||
} else {
|
||||
Log.error("No valid proxies loaded");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
botCount = Integer.parseInt(cmd.getOptionValue('c', "1"));
|
||||
|
||||
minimal = cmd.hasOption('m');
|
||||
if (cmd.hasOption('x')) {
|
||||
minimal = mostMinimal = true;
|
||||
}
|
||||
|
||||
|
||||
if (cmd.hasOption('d')) {
|
||||
String[] delays = cmd.getOptionValues('d');
|
||||
delayMin = Integer.parseInt(delays[0]);
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
String address = cmd.getOptionValue('s');
|
||||
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) {
|
||||
joinMessages.add(msg.trim());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int port = 25565;
|
||||
if (address.contains(":")) {
|
||||
String[] split = address.split(":", 2);
|
||||
address = split[0];
|
||||
port = Integer.parseInt(split[1]);
|
||||
} else {
|
||||
Record[] records = new Lookup("_minecraft._tcp." + address, Type.SRV).run();
|
||||
if (records != null) {
|
||||
for (Record record : records) {
|
||||
SRVRecord srv = (SRVRecord) record;
|
||||
address = srv.getTarget().toString().replaceFirst("\\.$", "");
|
||||
port = srv.getPort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean realNicknames = cmd.hasOption('r');
|
||||
|
||||
NickGenerator nickGen = new NickGenerator();
|
||||
|
||||
if (cmd.hasOption("nicks")) {
|
||||
Log.info("Loading nicknames from specified file");
|
||||
int nicksCount = nickGen.loadFromFile(cmd.getOptionValue("nicks"));
|
||||
|
||||
if (nicksCount == 0) {
|
||||
Log.error("No valid nicknames loaded");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
if (nicksCount < botCount) {
|
||||
Log.warn("Nickname count is lower than bot count!");
|
||||
Thread.sleep(3000);
|
||||
}
|
||||
} else {
|
||||
nickGen.setReal(realNicknames);
|
||||
}
|
||||
|
||||
nickGen.setPrefix(cmd.getOptionValue('p', ""));
|
||||
|
||||
InetSocketAddress inetAddr = new InetSocketAddress(
|
||||
InetAddress.getByName(address).getHostAddress(),
|
||||
port
|
||||
);
|
||||
|
||||
//print info
|
||||
Log.info("IP:", inetAddr.getHostString());
|
||||
Log.info("Port: " + inetAddr.getPort());
|
||||
Log.info("Bot count: " + botCount);
|
||||
|
||||
//get and print server info
|
||||
ServerInfo serverInfo = new ServerInfo(inetAddr);
|
||||
serverInfo.requestInfo();
|
||||
ServerStatusInfo statusInfo = serverInfo.getStatusInfo();
|
||||
if (statusInfo != null) {
|
||||
Log.info(
|
||||
"Server version: "
|
||||
+ statusInfo.getVersionInfo().getVersionName()
|
||||
+ " (" + statusInfo.getVersionInfo().getProtocolVersion()
|
||||
+ ")"
|
||||
);
|
||||
Log.info("Player Count: " + statusInfo.getPlayerInfo().getOnlinePlayers()
|
||||
+ " / " + statusInfo.getPlayerInfo().getMaxPlayers());
|
||||
Log.info();
|
||||
} else {
|
||||
Log.warn("There was an error retrieving server status information. The server may be offline or running on a different version.");
|
||||
}
|
||||
|
||||
AuthenticationService authService = null;
|
||||
if (cmd.hasOption("o")) {
|
||||
Log.warn("Online mode enabled. The bot count will be set to 1.");
|
||||
botCount = 1;
|
||||
|
||||
// Create request parameters map
|
||||
Map<String, String> params = new HashMap<>();
|
||||
params.put("client_id", CLIENT_ID);
|
||||
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 = HTTP.makeRequestForm(
|
||||
Proxy.NO_PROXY, endpointURI, params, MsaAuthenticationService.MsCodeResponse.class
|
||||
);
|
||||
try {
|
||||
Log.info("Please go to " + response.verification_uri.toURL() + " to authenticate your account - Code: " + response.user_code);
|
||||
} catch (MalformedURLException e) {
|
||||
Log.error("Error while trying to get the url of the authentication page");
|
||||
}
|
||||
|
||||
authService = new MsaAuthenticationService(CLIENT_ID, 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) {
|
||||
Log.info("Authentication is pending, waiting for user to authenticate...");
|
||||
try {
|
||||
Thread.sleep(5000);
|
||||
} catch (InterruptedException ignored) {
|
||||
}
|
||||
if (retryMax == 0)
|
||||
throw e;
|
||||
retryMax--;
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
AuthenticationService finalAuthService = authService;
|
||||
new Thread(() -> {
|
||||
for (int i = 0; i < botCount; i++) {
|
||||
try {
|
||||
ProxyInfo proxyInfo = null;
|
||||
if (useProxies) {
|
||||
InetSocketAddress proxySocket = proxies.get(proxyIndex);
|
||||
|
||||
if (!minimal) {
|
||||
Log.info(
|
||||
"Using proxy: (" + proxyIndex + ")",
|
||||
proxySocket.getHostString() + ":" + proxySocket.getPort()
|
||||
);
|
||||
}
|
||||
|
||||
proxyInfo = new ProxyInfo(
|
||||
proxyType,
|
||||
proxySocket
|
||||
);
|
||||
|
||||
//increment or reset current proxy index
|
||||
if (proxyIndex < (proxyCount - 1)) {
|
||||
proxyIndex++;
|
||||
} else {
|
||||
proxyIndex = 0;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Bot bot = null;
|
||||
if (finalAuthService != null) {
|
||||
bot = new Bot(
|
||||
finalAuthService,
|
||||
inetAddr,
|
||||
proxyInfo
|
||||
);
|
||||
} else {
|
||||
bot = new Bot(
|
||||
nickGen.nextNick(),
|
||||
inetAddr,
|
||||
proxyInfo
|
||||
);
|
||||
}
|
||||
|
||||
bot.start();
|
||||
|
||||
if (!mostMinimal) bots.add(bot);
|
||||
|
||||
triedToConnect++;
|
||||
|
||||
if (isMainListenerMissing && !isMinimal()) {
|
||||
isMainListenerMissing = false;
|
||||
bot.registerMainListener();
|
||||
}
|
||||
|
||||
if (i < botCount - 1) {
|
||||
long delay = getRandomDelay();
|
||||
Log.info("Waiting", delay + "", "ms");
|
||||
Thread.sleep(delay);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
}).start();
|
||||
|
||||
//gravity timer
|
||||
if (cmd.hasOption("g")) {
|
||||
timer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
bots.forEach(Bot::fallDown);
|
||||
}
|
||||
}, 1000L, 500L);
|
||||
}
|
||||
|
||||
Terminal terminal = TerminalBuilder.builder().build();
|
||||
LineReader lineReader = LineReaderBuilder.builder()
|
||||
.terminal(terminal)
|
||||
.parser(new org.jline.reader.impl.DefaultParser())
|
||||
.build();
|
||||
|
||||
prompt = "ALL";
|
||||
|
||||
while (true) {
|
||||
String line;
|
||||
try {
|
||||
line = lineReader.readLine();
|
||||
} catch (UserInterruptException e) {
|
||||
System.exit(0);
|
||||
break;
|
||||
}
|
||||
if (line.isEmpty()) {
|
||||
System.out.print(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 = findBotByName(searchedName);
|
||||
|
||||
if (bot != null) {
|
||||
controlledBots.add(bot);
|
||||
newBotCount++;
|
||||
} else {
|
||||
Log.warn("Bot not found: " + searchedName);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (newBotCount > 0) {
|
||||
// Join bot nicknames
|
||||
String botNames = controlledBots
|
||||
.stream()
|
||||
.map(Bot::getNickname)
|
||||
.collect(Collectors.joining(", "));
|
||||
|
||||
if (newBotCount == 1) {
|
||||
Log.info("Now controlling 1 bot: " + botNames);
|
||||
} else {
|
||||
Log.info("Now controlling " + newBotCount + " bots: " + botNames);
|
||||
}
|
||||
|
||||
} else {
|
||||
Log.warn("No bots found.");
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
// If no bot names are supplied, remove all bots
|
||||
controlledBots.clear();
|
||||
Log.info("No bots selected - now controlling all bots.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// List command
|
||||
else if (commandName.equalsIgnoreCase("list") || commandName.equalsIgnoreCase("ls")) {
|
||||
Log.info("There are " + bots.size() + " bots connected:");
|
||||
for (Bot bot : bots) {
|
||||
Log.info(bot.getNickname(), bot.hasMainListener() ? "[MainListener]" : "");
|
||||
}
|
||||
} 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;
|
||||
Log.warn("Invalid limit.");
|
||||
}
|
||||
}
|
||||
|
||||
int i = 0;
|
||||
if (!controlledBots.isEmpty()) {
|
||||
Log.info("Disconnecting controlled bots.");
|
||||
for (Bot bot : controlledBots) {
|
||||
if (i++ == limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
bot.disconnect();
|
||||
}
|
||||
} else {
|
||||
Log.info("Disconnecting all bots.");
|
||||
for (Bot bot : bots) {
|
||||
if (i++ == limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
bot.disconnect();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Log.warn("Invalid command");
|
||||
}
|
||||
} else if (controlledBots.size() > 0) {
|
||||
controlledBots.forEach(bot -> bot.sendChat(line));
|
||||
} else {
|
||||
bots.forEach(bot -> bot.sendChat(line));
|
||||
}
|
||||
|
||||
Thread.sleep(50);
|
||||
|
||||
//System.out.print("\r" +prompt + "> ");
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void renewMainListener() {
|
||||
bots.get(0).registerMainListener();
|
||||
}
|
||||
|
||||
public static synchronized void removeBot(Bot bot) {
|
||||
bots.remove(bot);
|
||||
controlledBots.remove(bot);
|
||||
if (bot.hasMainListener()) {
|
||||
Log.info("Bot with MainListener removed");
|
||||
isMainListenerMissing = true;
|
||||
}
|
||||
if (bots.size() > 0) {
|
||||
if (isMainListenerMissing && !isMinimal()) {
|
||||
Log.info("Renewing MainListener");
|
||||
renewMainListener();
|
||||
isMainListenerMissing = false;
|
||||
}
|
||||
} else {
|
||||
if (triedToConnect == botCount) {
|
||||
Log.error("All bots disconnected, exiting");
|
||||
System.exit(0);
|
||||
}
|
||||
}
|
||||
bot = null;
|
||||
}
|
||||
|
||||
public static long getRandomDelay() {
|
||||
return random.nextInt(delayMax - delayMin) + delayMin;
|
||||
}
|
||||
|
||||
public static boolean isMinimal() {
|
||||
return minimal;
|
||||
}
|
||||
|
||||
public static Bot findBotByName(String text) {
|
||||
for (Bot bot : bots) {
|
||||
// Starts with and ignore case
|
||||
// https://stackoverflow.com/a/38947571/11787611
|
||||
if (bot.getNickname().regionMatches(true, 0, text, 0, text.length())) {
|
||||
return bot;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String getPrompt()
|
||||
{
|
||||
int count = controlledBots.size();
|
||||
if (count == 0) {
|
||||
return "ALL";
|
||||
} else if (count == 1)
|
||||
{
|
||||
//If controlling only one bot, return its nickname
|
||||
return controlledBots.iterator().next().getNickname();
|
||||
}
|
||||
else {
|
||||
return count + " BOTS";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
|
||||
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.*;
|
||||
import com.github.steveice10.packetlib.packet.Packet;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.TextComponent;
|
||||
import net.kyori.adventure.text.TranslatableComponent;
|
||||
|
||||
public class MainListener implements SessionListener {
|
||||
|
||||
public MainListener(String nickname) {
|
||||
Log.info("MainListener registered for: " + nickname);
|
||||
}
|
||||
|
||||
@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) {
|
||||
ClientboundPlayerChatPacket clientboundPlayerChatPacket = ((ClientboundPlayerChatPacket) packet);
|
||||
message = clientboundPlayerChatPacket.getUnsignedContent();
|
||||
sender = clientboundPlayerChatPacket.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) {
|
||||
Log.chat(Utils.getFullText((TextComponent) sender, Component.text(clientboundPlayerChatPacket.getContent()), Main.coloredChat));
|
||||
} else {
|
||||
Log.chat(Utils.getFullText((TextComponent) sender, (TextComponent) message, Main.coloredChat));
|
||||
}
|
||||
chatPrintedOut = true;
|
||||
|
||||
} else if (packet instanceof ClientboundSystemChatPacket) { // When this was SystemChat packet.
|
||||
message = ((ClientboundSystemChatPacket) packet).getContent();
|
||||
}
|
||||
|
||||
// For output of commands, this is the case where this program prints out the message to user.
|
||||
if (message instanceof TextComponent && !chatPrintedOut) {
|
||||
TextComponent msg = (TextComponent) message;
|
||||
Log.chat(Utils.getFullText(msg, Main.coloredChat));
|
||||
}
|
||||
|
||||
if (message instanceof TranslatableComponent) {
|
||||
TranslatableComponent msg = (TranslatableComponent) message;
|
||||
Log.chat("[T]", Utils.translate(msg));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetSending(PacketSendingEvent event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetSent(Session session, Packet packet) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void packetError(PacketErrorEvent event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connected(ConnectedEvent event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnecting(DisconnectingEvent event) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void disconnected(DisconnectedEvent event) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package me.creepermaxcz.mcbots;
|
||||
|
||||
import java.io.*;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Scanner;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class NickGenerator {
|
||||
|
||||
private static final int NICK_LEN = 16;
|
||||
private final SecureRandom random = new SecureRandom();
|
||||
|
||||
private final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
private final int charsLen = 62;
|
||||
|
||||
private int linesSize;
|
||||
private List<String> lines;
|
||||
|
||||
private int nickLen = NICK_LEN;
|
||||
|
||||
private boolean real = false;
|
||||
|
||||
private String prefix = "";
|
||||
|
||||
public int loadFromFile(String filePath) {
|
||||
lines = new ArrayList<>();
|
||||
try {
|
||||
Scanner scanner = new Scanner(new File(filePath));
|
||||
while (scanner.hasNextLine()) {
|
||||
try {
|
||||
String line = scanner.nextLine().trim();
|
||||
|
||||
//add only valid nicknames
|
||||
if (line.matches("^[a-zA-Z0-9_]{3,16}$")) {
|
||||
lines.add(line);
|
||||
}
|
||||
}
|
||||
catch (Exception ignored) { }
|
||||
}
|
||||
scanner.close();
|
||||
} catch (FileNotFoundException e) {
|
||||
Log.error("Invalid nicknames list file path");
|
||||
System.exit(1);
|
||||
}
|
||||
|
||||
linesSize = lines.size();
|
||||
Log.info("Loaded " + linesSize + " valid nicknames");
|
||||
real = true;
|
||||
|
||||
return linesSize;
|
||||
}
|
||||
|
||||
private void loadLines() {
|
||||
try (InputStream resource = getClass().getResourceAsStream("/files/nicks.txt")) {
|
||||
lines = new BufferedReader(
|
||||
new InputStreamReader(resource, StandardCharsets.UTF_8)).lines().collect(Collectors.toList()
|
||||
);
|
||||
linesSize = lines.size();
|
||||
} catch (Exception e) {
|
||||
Log.error(e);
|
||||
System.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
public String generateRandom(int len) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int i = 0; i < len; i++) {
|
||||
result.append(CHARS.charAt(random.nextInt(charsLen)));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
public String nextRandom() {
|
||||
return prefix + generateRandom(nickLen);
|
||||
}
|
||||
|
||||
public String nextReal() {
|
||||
String nick = prefix + lines.get(random.nextInt(linesSize));
|
||||
return nick.length() <= 16 ? nick : nick.substring(0, 15);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate next nick
|
||||
* @return generated nick
|
||||
*/
|
||||
public String nextNick() {
|
||||
return real ? nextReal() : nextRandom();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set prefix for generated nicks
|
||||
* @param prefix the prefix
|
||||
*/
|
||||
public void setPrefix(String prefix) {
|
||||
nickLen = NICK_LEN - prefix.length();
|
||||
this.prefix = prefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set nick is real from nick list
|
||||
*
|
||||
* @param real true to generate real nicknames
|
||||
*/
|
||||
public void setReal(boolean real) {
|
||||
if (real && lines == null) loadLines();
|
||||
this.real = real;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user