Dev/remove standalone #86

Closed
ShaneBeee wants to merge 11 commits from dev/remove-standalone into main
pull from: dev/remove-standalone
42 changed files with 2163 additions and 1246 deletions
Showing only changes of commit 1c8eb3304a - Show all commits

No files matched your search

-31
View File
@@ -1,31 +0,0 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshot or app console output**
If applicable, add screenshots to help explain your problem.
**Whole command used to start the app**
Please insert the whole command you used to start the app.
Censoring ip address is recommended.
**Additional context**
Add any other context about the problem here.
-20
View File
@@ -1,20 +0,0 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+9 -53
View File
@@ -1,58 +1,14 @@
# Minecraft bot stress tester # Minecraft Bot Stress Tester
🤖 A simple open source app written in Java used for stress testing Minecraft servers with bots (fake players). A simple app used to stress test Minecraft servers by loading in fake players (bots).
💥 It can be also used to test plugins or minigames.
✔️ The MC version of the bots is 1.20 (supports 1.20.x).
For older MC versions please look in the [releases](https://github.com/crpmax/mc-bots/releases " releases").
## 🆒 Features This is a fork of the [**original**](https://github.com/crpmax/mc-bots) with a big re-write to the codebase, along with a built in plugin that can be directly used on the server.
- ✅ Connect as many bots as you want
- ✅ Use SOCKS4 or SOCKS5 proxies from file or URL
- ✅ Receive colored or noncolored chat
- ✅ Set connection delay
- ✅ Set messages or commands on join
- ✅ Generate random or real looking nicknames or load from file
- ✅ Online (premium) account support with login using Microsoft OAuth - only for migrated accounts
- ✅ Control all or selected bots
## 📖 Usage # Usage:
Minimal Java version: 8 There are two different ways you can use this, either as a standalone app run from a console, or by adding it to your server and running as a plugin.
Use of pre-compiled jar from [releases](https://github.com/crpmax/mc-bots/releases " releases"):
`java -jar mc-bots.jar -s <server address> [arguments]`
When running, you can write a chat message to the terminal to send it by all bots.
## 🧪 Example To use as a standalone app, see the [**standalone wiki**](https://github.com/ShaneBeee/mc-bots/wiki/Standalone)
`java -jar mc-bots-1.2.6.jar -s 192.168.0.189:25565 -p BOT_ -d 4000 5000 -c 30 -r`
This will connect 30 bots to server at 192.168.0.189:25565 with delay 4000-5000 ms and will use real-looking nicknames prefixed with BOT_
<img src="https://imgur.com/XWcckas.png" title="Connected bots" width="350px"/> To use as a plugin on your server, see [**plugin wiki**](https://github.com/ShaneBeee/mc-bots/wiki/Plugin)
<img src="https://imgur.com/CvJq1Io.gif" title="Sending chat message by bots" width="350px"/>
# Requirements:
## ⚡ Options - Java 17+
`-c <count>` The count of bots to connect, default is 1
`-d <min> <max>` Set the minimum and maximum connection delay range in ms, default is 4000-5000
`-j <message>` Messages or commands to send on join, separated by `&&`, does not work with `-m` or `-x` option
`-p <prefix>` Custom bot nickname prefix eg. `BOT_`
`-r` Generate real looking nicknames instead of random ones
`-n` Do not use color in terminal - useful when the terminal does not support it
`-m` Minimal run - do not use any listeners, will not receive chat, useful for large amounts of bots
`-x` The most minimal run - No listeners, no control, no chat - useful for large amounts of bots for better performance
`-t <type>` Set proxy type - SOCKS4 or SOCKS5
`-l <path>` Set proxy list file
`-g` Try to simulate gravity by falling down
`-o` Use online (premium) account (login with Microsoft OAuth)
`-ar <delay>` Set auto-respawn delay (default is 100 ms, set to -1 to disable)
`--nicks <file>` Set nicknames file
## Commands
Commands can be typed to the console. They are prefixed with `.` or `!`.
Without the prefix it will be sent as a chat message!
`.list` or `.ls` - list all connected bots
`.control <nick>` or `.ctrl <nick>` - select one or multiple bots to control
`.exit <limit>` or `.leave <limit>` - disconnect all or specified number of bots
## ⚠ DISCLAIMER
**This app is made for educational and testing purposes only.
This app can be used like spambots.
I am not responsible for any abuse.**
+51 -7
View File
@@ -1,35 +1,79 @@
import org.apache.tools.ant.filters.ReplaceTokens
plugins { plugins {
id 'java' id 'java'
id "io.github.goooler.shadow" version "8.1.7"
} }
group 'me.creepermaxcz.mc-bots' group 'com.shanebeestudios'
version '1.2.9' version '1.2.9'
sourceCompatibility = 1.8 compileJava {
targetCompatibility = 1.8 sourceCompatibility = '17'
targetCompatibility = '17'
options.encoding = 'UTF-8'
}
repositories { repositories {
mavenCentral() mavenCentral()
maven { url 'https://jitpack.io' } maven { url 'https://jitpack.io' }
maven { url 'https://repo.opencollab.dev/maven-snapshots/' } maven { url 'https://repo.opencollab.dev/maven-snapshots/' }
maven { url 'https://repo.opencollab.dev/maven-releases/' } maven { url 'https://repo.opencollab.dev/maven-releases/' }
// Paper
maven { url 'https://repo.papermc.io/repository/maven-public/' }
} }
dependencies { 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 'commons-cli:commons-cli:1.5.0'
implementation 'com.diogonunes:JColor:5.2.0' implementation 'com.diogonunes:JColor:5.2.0'
implementation 'dnsjava:dnsjava:3.4.3' implementation 'dnsjava:dnsjava:3.4.3'
implementation 'org.slf4j:slf4j-nop:1.7.32' implementation 'org.slf4j:slf4j-nop:1.7.32'
implementation 'org.jline:jline:3.22.0' implementation 'org.jline:jline:3.25.0'
// Paper
compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT")
// Command Api
implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
}
processResources {
filter ReplaceTokens, tokens: ["version": project.version]
} }
jar { jar {
manifest { manifest {
attributes 'Main-Class': 'me.creepermaxcz.mcbots.Main' attributes 'Main-Class': 'com.shanebeestudios.mcbots.standalone.Main', 'Manifest-Version': project.version
duplicatesStrategy = DuplicatesStrategy.EXCLUDE duplicatesStrategy = DuplicatesStrategy.EXCLUDE
} }
from { from {
configurations.runtimeClasspath.filter{ it.exists() }.collect { it.isDirectory() ? it : zipTree(it) } configurations.runtimeClasspath.filter { it.exists() }.collect { it.isDirectory() ? it : zipTree(it) }
} }
} }
shadowJar {
dependsOn(jar)
archiveClassifier = null
relocate("dev.jorel.commandapi", "com.shanebeestudios.mcbots.api.commandapi")
}
build {
dependsOn(shadowJar)
tasks.withType(JavaCompile).tap {
configureEach {
options.compilerArgs.add("-Xlint:unchecked")
options.compilerArgs.add("-Xlint:deprecation")
}
}
}
// Run task to build jar to another spot
tasks.register('server', Copy) {
from shadowJar
// Change this to wherever you want your jar to build
into '/Users/ShaneBee/Desktop/Server/Skript/1-20-4/plugins'
}
Binary file not shown.
+3 -1
View File
@@ -1,5 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored
+28 -13
View File
@@ -55,7 +55,7 @@
# Darwin, MinGW, and NonStop. # Darwin, MinGW, and NonStop.
# #
# (3) This script is generated from the Groovy template # (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project. # within the Gradle project.
# #
# You can find Gradle at https://github.com/gradle/gradle/. # You can find Gradle at https://github.com/gradle/gradle/.
@@ -80,13 +80,11 @@ do
esac esac
done done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # This is normally unused
# shellcheck disable=SC2034
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -133,22 +131,29 @@ location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
case $MAX_FD in #( case $MAX_FD in #(
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -193,11 +198,15 @@ if "$cygwin" || "$msys" ; then
done done
fi fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
# shell script including quotes and variable substitutions, so put them in DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded. # Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \
@@ -205,6 +214,12 @@ set -- \
org.gradle.wrapper.GradleWrapperMain \ org.gradle.wrapper.GradleWrapperMain \
"$@" "$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args. # Use "xargs" to parse quoted args.
# #
# With -n1 it outputs one arg per line, with the quotes and backslashes removed. # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
Vendored
+9 -6
View File
@@ -14,7 +14,7 @@
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%" == "" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@@ -25,7 +25,8 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=. if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% set APP_HOME=%DIRNAME%
@@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto execute if %ERRORLEVEL% equ 0 goto execute
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd if %ERRORLEVEL% equ 0 goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 set EXIT_CODE=%ERRORLEVEL%
exit /b 1 if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
-2
View File
@@ -1,2 +0,0 @@
rootProject.name = 'mc-bots'
-3
View File
@@ -1,3 +0,0 @@
Manifest-Version: 1.0
Main-Class: me.creepermaxcz.mcbots.Main
@@ -0,0 +1,140 @@
package com.shanebeestudios.mcbots.api;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.timer.GravityTimer;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import org.jetbrains.annotations.Nullable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Base bot manager
*/
public abstract class BotManager {
protected int autoRespawnDelay;
protected boolean minimal = false;
protected boolean mostMinimal = false;
protected String nickPath = null;
protected String nickPrefix = "";
protected boolean hasGravity;
protected ArrayList<String> joinMessages = new ArrayList<>();
protected InetSocketAddress inetAddr;
protected final ArrayList<Bot> bots = new ArrayList<>();
protected NickGenerator nickGenerator;
protected final GravityTimer gravityTimer;
public BotManager() {
this.gravityTimer = new GravityTimer(this);
}
// Methods
protected InetSocketAddress createInetAddress(String address, int port) {
try {
InetAddress inetAddress = InetAddress.getByName(address);
return new InetSocketAddress(inetAddress.getHostAddress(), port);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public boolean isMinimal() {
return this.minimal;
}
public boolean isMostMinimal() {
return this.mostMinimal;
}
public int getAutoRespawnDelay() {
return this.autoRespawnDelay;
}
public String getNickPath() {
return this.nickPath;
}
public String getNickPrefix() {
return this.nickPrefix;
}
public boolean hasGravity() {
return this.hasGravity;
}
public ArrayList<String> getJoinMessages() {
return this.joinMessages;
}
public InetSocketAddress getInetAddr() {
return this.inetAddr;
}
/**
* Get all loaded bots
*
* @return All loaded bots
*/
public ArrayList<Bot> getBots() {
return this.bots;
}
/**
* Get instance of nick generator
*
* @return Nick generator
*/
public NickGenerator getNickGenerator() {
return this.nickGenerator;
}
public void logBotCreated(String name) {
Logger.info("Bot '" + name + "' created");
}
public void logBotDisconnected(String name) {
Logger.info("Bot '" + name + "' disconnected");
}
/**
* Remove a bot
*
* @param bot Bot to remove
*/
public void removeBot(Bot bot) {
this.bots.remove(bot);
}
/**
* Disconnect and remove a bot
*
* @param bot Bot to disconnect and remove
*/
public void disconnectBot(Bot bot) {
bot.disconnect();
this.bots.remove(bot);
}
/**
* Find a bot by name
*
* @param text Name of player to get bot from
* @return Bot from name
*/
@Nullable
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;
}
}
@@ -1,4 +1,4 @@
package me.creepermaxcz.mcbots; package com.shanebeestudios.mcbots.api;
import com.github.steveice10.mc.protocol.MinecraftConstants; import com.github.steveice10.mc.protocol.MinecraftConstants;
@@ -21,19 +21,18 @@ public class ServerInfo {
private boolean done; private boolean done;
public ServerInfo(InetSocketAddress address) { public ServerInfo(InetSocketAddress address) {
MinecraftProtocol protocol = new MinecraftProtocol(); 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; 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; this.ping = pingTime;
}); });
client.addListener(new SessionAdapter() { this.client.addListener(new SessionAdapter() {
@Override @Override
public void disconnected(DisconnectedEvent event) { public void disconnected(DisconnectedEvent event) {
done = true; done = true;
@@ -41,12 +40,11 @@ public class ServerInfo {
}); });
} }
public void requestInfo() public void requestInfo() {
{ this.client.connect();
client.connect();
//wait to disconnect //wait to disconnect
while (!done) { while (!this.done) {
try { try {
Thread.sleep(5); Thread.sleep(5);
} catch (InterruptedException e) { } catch (InterruptedException e) {
@@ -55,12 +53,11 @@ public class ServerInfo {
} }
} }
public ServerStatusInfo getStatusInfo() public ServerStatusInfo getStatusInfo() {
{ return this.serverStatusInfo;
return serverStatusInfo;
} }
public long getPing() { public long getPing() {
return ping; return this.ping;
} }
} }
@@ -0,0 +1,152 @@
package com.shanebeestudios.mcbots.api.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.BotManager;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import com.shanebeestudios.mcbots.api.listener.MessageListener;
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 BotManager botManager;
private final String nickname;
private final Session client;
private boolean hasMainListener;
private double lastX, lastY, lastZ = -1;
private boolean connected;
private boolean manualDisconnecting = false;
private BaseSessionListener sessionListener;
public Bot(BotManager botManager, String nickname, InetSocketAddress address, ProxyInfo proxy) {
this.botManager = botManager;
this.nickname = nickname;
botManager.logBotCreated(nickname);
this.protocol = new MinecraftProtocol(nickname);
this.client = new TcpClientSession(address.getHostString(), address.getPort(), this.protocol, proxy);
}
public Bot(BotManager botManager, AuthenticationService authService, InetSocketAddress address, ProxyInfo proxy) {
this.botManager = botManager;
this.nickname = authService.getUsername();
botManager.logBotCreated(this.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);
}
public void setupSessionListener(BaseSessionListener listener) {
this.sessionListener = listener.init(this);
}
/**
* Connect the bot to the server
*/
public void connect() {
new Thread(() -> {
if (!this.botManager.isMinimal() && this.sessionListener != null) {
this.client.addListener(this.sessionListener);
}
this.client.connect();
}).start();
}
public BotManager getBotManager() {
return this.botManager;
}
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 boolean hasMainListener() {
return this.hasMainListener;
}
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
packet = new ServerboundChatPacket(text, timeStamp, 0L, null, 0, bitSet);
}
this.client.send(packet);
}
public void registerMainListener() {
this.hasMainListener = true;
if (this.botManager.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,105 @@
package com.shanebeestudios.mcbots.api.bot;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.packetlib.ProxyInfo;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneSessionListener;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Random;
public class BotLoader {
private final StandaloneBotManager standaloneLoader;
private final int delayMin;
private final int delayMax;
private final Random random;
private int triedToConnect = 0;
private int proxyIndex = 0;
public BotLoader(StandaloneBotManager standaloneLoader) {
this.standaloneLoader = standaloneLoader;
this.delayMin = standaloneLoader.getDelayMin();
this.delayMax = standaloneLoader.getDelayMax();
this.random = new Random();
}
@SuppressWarnings("CallToPrintStackTrace")
public void spin() {
int botCount = this.standaloneLoader.getBotCount();
boolean minimal = this.standaloneLoader.isMinimal();
boolean mostMinimal = this.standaloneLoader.isMostMinimal();
InetSocketAddress inetAddr = this.standaloneLoader.getInetAddr();
NickGenerator nickGenerator = this.standaloneLoader.getNickGenerator();
AuthenticationService authService = this.standaloneLoader.getAuthenticationService();
ProxyGenerator proxyGenerator = this.standaloneLoader.getProxyGenerator();
int proxyCount = proxyGenerator != null ? proxyGenerator.getProxies().size() : 0;
ArrayList<InetSocketAddress> proxies = proxyGenerator != null ? proxyGenerator.getProxies() : null;
new Thread(() -> {
for (int i = 0; i < botCount; i++) {
try {
ProxyInfo proxyInfo = null;
if (proxies != null && !proxies.isEmpty()) {
InetSocketAddress proxySocket = proxies.get(this.proxyIndex);
if (!minimal) {
Logger.info("Using proxy: (" + this.proxyIndex + ")", proxySocket.getHostString() + ":" + proxySocket.getPort());
}
proxyInfo = new ProxyInfo(proxyGenerator.getProxyType(), proxySocket);
//increment or reset current proxy index
if (this.proxyIndex < (proxyCount - 1)) {
this.proxyIndex++;
} else {
this.proxyIndex = 0;
}
}
Bot bot;
if (authService != null) {
bot = new Bot(this.standaloneLoader, authService, inetAddr, proxyInfo);
} else {
bot = new Bot(this.standaloneLoader, nickGenerator.nextNick(), inetAddr, proxyInfo);
}
bot.setupSessionListener(new StandaloneSessionListener());
bot.connect();
if (!mostMinimal) this.standaloneLoader.getBots().add(bot);
this.triedToConnect++;
if (this.standaloneLoader.isMainListenerMissing() && !minimal) {
this.standaloneLoader.setMainListenerMissing(false);
bot.registerMainListener();
}
if (i < botCount - 1) {
long delay = getRandomDelay();
Logger.info("Waiting", delay + "", "ms");
Thread.sleep(delay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public int getTriedToConnect() {
return this.triedToConnect;
}
private long getRandomDelay() {
return this.random.nextInt(this.delayMax - this.delayMin) + this.delayMin;
}
}
@@ -0,0 +1,106 @@
package com.shanebeestudios.mcbots.api.generator;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
@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 {
Logger.info("Loaded %s nicknames", this.linesSize);
}
} else {
if (useRealNicknames && this.lines == null) {
loadDefaultFile();
Logger.info("Loaded %s nicknames", this.linesSize);
}
this.real = useRealNicknames;
}
this.nickLength = DEFAULT_NICK_LENGTH - prefix.length();
this.prefix = prefix;
}
private int loadFromFile(String filePath) {
this.lines = new ArrayList<>();
try {
this.lines = getListFromReader(new FileReader(filePath));
} catch (FileNotFoundException ignore) {
Logger.error("Invalid nicknames list file path, loading default file!");
loadDefaultFile();
}
this.linesSize = this.lines.size();
this.real = true;
return this.linesSize;
}
private void loadDefaultFile() {
try (InputStream resource = getClass().getResourceAsStream("/nicks.txt")) {
assert resource != null;
this.lines = getListFromReader(new InputStreamReader(resource, StandardCharsets.UTF_8));
this.linesSize = this.lines.size();
} catch (Exception e) {
Logger.error(e);
System.exit(1);
}
}
private List<String> getListFromReader(Reader reader) {
return new BufferedReader(reader)
.lines()
.filter(line -> line.matches("^[a-zA-Z0-9_]{3," + DEFAULT_NICK_LENGTH + "}$"))
.toList();
}
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.logging.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class ProxyGenerator {
private ProxyInfo.Type proxyType;
private final String proxyPath;
private final ArrayList<InetSocketAddress> proxies = new ArrayList<>();
public ProxyGenerator(String proxyType, String proxyPath) {
this.proxyPath = proxyPath;
//get proxy type
try {
this.proxyType = ProxyInfo.Type.valueOf(proxyType);
} catch (IllegalArgumentException e) {
Logger.error("Invalid proxy type, use SOCKS4 or SOCKS5.");
System.exit(1);
}
readProxyFileList();
}
private void readProxyFileList() {
try {
try {
//try to read specified path as URL
URL url = new URL(this.proxyPath);
BufferedReader read = new BufferedReader(
new InputStreamReader(url.openStream()));
Logger.info("Reading proxies from URL");
String line;
while ((line = read.readLine()) != null) {
try {
String[] parts = line.trim().split(":");
if (parts.length == 2) {
int port = Integer.parseInt(parts[1]);
this.proxies.add(new InetSocketAddress(parts[0], port));
}
} catch (Exception ignored) {
}
}
read.close();
} catch (MalformedURLException e) {
Logger.info("Specified proxy file is not a URL, trying to read file");
Scanner scanner = new Scanner(new File(this.proxyPath));
while (scanner.hasNextLine()) {
try {
String[] parts = scanner.nextLine().trim().split(":");
if (parts.length == 2) {
int port = Integer.parseInt(parts[1]);
proxies.add(new InetSocketAddress(parts[0], port));
}
} catch (Exception ignored) {
}
}
scanner.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
} catch (FileNotFoundException e) {
Logger.error("Invalid proxy list file path.");
System.exit(1);
}
int size = this.proxies.size();
if (size > 0) {
Logger.info("Loaded " + size + " valid proxies");
} else {
Logger.error("No valid proxies loaded");
System.exit(1);
}
}
public ProxyInfo.Type getProxyType() {
return this.proxyType;
}
public ArrayList<InetSocketAddress> getProxies() {
return this.proxies;
}
}
@@ -0,0 +1,27 @@
package com.shanebeestudios.mcbots.api.listener;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.bot.Bot;
import java.util.ArrayList;
public class BaseSessionListener extends SessionAdapter {
protected Bot bot;
protected Session client;
protected BotManager botManager;
protected ArrayList<String> joinMessages;
protected int autoRespawnDelay;
public BaseSessionListener init(Bot bot) {
this.bot = bot;
this.client = bot.getClient();
this.botManager = bot.getBotManager();
this.joinMessages = this.botManager.getJoinMessages();
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
return this;
}
}
@@ -0,0 +1,62 @@
package com.shanebeestudios.mcbots.api.listener;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundPlayerChatPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundSystemChatPacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.util.Utils;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
public class MessageListener extends SessionAdapter {
private final boolean coloredChat;
public MessageListener(Bot bot) {
this.coloredChat = !(bot.getBotManager() instanceof StandaloneBotManager botManager) || botManager.isColoredChat();
Logger.info("MessageListener registered for: " + bot.getNickname());
}
@Override
public void packetReceived(Session session, Packet packet) {
// From 1.19.1 (as well as 1.19), the class ClientboundChatPacket was removed.
// Instead, they use ClientboundPlayerChatPacket and ClientboundSystemChatPacket for taking care of chat packets.
Component message = null;
Component sender;
boolean chatPrintedOut = false;
if (packet instanceof ClientboundPlayerChatPacket playerChatPacket) {
message = playerChatPacket.getUnsignedContent();
sender = playerChatPacket.getName();
// Sometimes the message's body gets null.
// For example, some commands like /say makes the message content as null.
// However, the message exists as in getMessagePlain(), thus can retrieve message using the method.
if (message == null) {
Logger.chat(Utils.getFullText((TextComponent) sender, Component.text(playerChatPacket.getContent()), this.coloredChat));
} else {
Logger.chat(Utils.getFullText((TextComponent) sender, (TextComponent) message, this.coloredChat));
}
chatPrintedOut = true;
} else if (packet instanceof ClientboundSystemChatPacket systemChatPacket) { // When this was SystemChat packet.
if (systemChatPacket.isOverlay()) return; // Actionbar
message = systemChatPacket.getContent();
}
// For output of commands, this is the case where this program prints out the message to user.
if (message instanceof TextComponent textComponent && !chatPrintedOut) {
Logger.chat(Utils.getFullText(textComponent, this.coloredChat));
}
if (message instanceof TranslatableComponent translatableComponent) {
Logger.chat("[T]", Utils.translate(translatableComponent));
}
}
}
@@ -0,0 +1,27 @@
package com.shanebeestudios.mcbots.api.timer;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.BotManager;
import java.util.Timer;
import java.util.TimerTask;
public class GravityTimer {
private final Timer timer = new Timer();
private final BotManager botManager;
public GravityTimer(BotManager botManager) {
this.botManager = botManager;
}
public void startTimer() {
this.timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
GravityTimer.this.botManager.getBots().forEach(Bot::fallDown);
}
}, 1000L, 50L);
}
}
@@ -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;
}
}
@@ -1,40 +1,47 @@
package me.creepermaxcz.mcbots; package com.shanebeestudios.mcbots.api.util;
import com.diogonunes.jcolor.Attribute; import com.diogonunes.jcolor.Attribute;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import net.kyori.adventure.text.Component; import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent; 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.Style;
import net.kyori.adventure.text.format.TextColor; import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration; import net.kyori.adventure.text.format.TextDecoration;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static com.diogonunes.jcolor.Ansi.colorize; import static com.diogonunes.jcolor.Ansi.colorize;
@SuppressWarnings("deprecation")
public class Utils { public class Utils {
private static JsonObject lang; private static JsonObject MINECRAFT_LANG;
public static String getFullText(TextComponent message, boolean colored) { public static String getFullText(TextComponent message, boolean colored) {
if (message.children().size() > 0) { if (!message.children().isEmpty()) {
StringBuilder text = new StringBuilder(); StringBuilder text = new StringBuilder();
text.append(parseColor(message, colored)); text.append(parseColor(message, colored));
for (Component child : message.children()) { for (Component child : message.children()) {
if (child instanceof TextComponent) { if (child instanceof TextComponent textComponent) {
text.append(getFullText((TextComponent) child, colored)); text.append(getFullText(textComponent, colored));
} else if (child instanceof TranslatableComponent) { } else if (child instanceof TranslatableComponent translatableComponent) {
text.append(translate((TranslatableComponent) child)); text.append(translate(translatableComponent));
} }
} }
return text.toString(); return text.toString();
} else { } else {
@@ -60,35 +67,34 @@ public class Utils {
if (sender != null) { if (sender != null) {
Style senderStyle = sender.style(); Style senderStyle = sender.style();
if (senderStyle.color() != null) { // Generate sender text with color. TextColor color = senderStyle.color();
outString.append(colorizeText(sender.content(), senderStyle.color())); if (color != null) { // Generate sender text with color.
outString.append(colorizeText(sender.content(), color));
} else { } else {
outString.append(sender.content()); outString.append(sender.content());
} }
outString.append(" : "); // Add delimiter as : between sender and message. outString.append(" : "); // Add delimiter as : between sender and message.
} }
if (messageStyle.color() != null && sender != null) { // Generate message text with color. TextColor color = messageStyle.color();
outString.append(colorizeText(sender.content(), messageStyle.color())); if (color != null && sender != null) { // Generate message text with color.
outString.append(colorizeText(sender.content(), color));
} else { } else {
outString.append(message.content()); outString.append(message.content());
} }
return outString.toString(); return outString.toString();
} else { } else {
if (sender == null) if (sender == null) return message.content();
return message.content(); else return sender.content() + " : " + message.content();
else
return sender.content() + " : " + message.content();
} }
} }
private static String parseColor(TextComponent message, boolean colored) { private static String parseColor(TextComponent message, boolean colored) {
String out = message.content(); String out = message.content();
if (colored) { if (colored) {
if (message.style().color() != null) {
List<Attribute> formats = new ArrayList<>(getFormats(message.style().decorations()));
TextColor color = message.style().color(); 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())); formats.add(Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
out = colorize(out, formats.toArray(new Attribute[0])); out = colorize(out, formats.toArray(new Attribute[0]));
} }
@@ -121,38 +127,56 @@ public class Utils {
} }
public static String translate(TranslatableComponent message) { public static String translate(TranslatableComponent message) {
if (lang == null) { if (MINECRAFT_LANG == null) {
try { try {
InputStream resource = Utils.class.getResourceAsStream("/files/lang.json"); InputStream resource = Utils.class.getResourceAsStream("/files/lang.json");
lang = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject(); if (resource == null) return null;
MINECRAFT_LANG = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject();
} catch (Exception e) { } catch (Exception e) {
Log.crit(e); Logger.critical(e);
} }
} }
//Log.info(message.toString());
String key = message.key(); String key = message.key();
String base = key; String base = key;
JsonElement value = lang.get(key); JsonElement value = MINECRAFT_LANG.get(key);
if (value != null) { if (value != null) {
base = value.getAsString(); base = value.getAsString();
} }
ArrayList<String> placeholders = new ArrayList<>(); ArrayList<String> placeholders = new ArrayList<>();
if (message.args().size() > 0) { if (!message.arguments().isEmpty()) {
for (Component component : message.args()) { for (TranslationArgument arg : message.arguments()) {
if (component instanceof TranslatableComponent) { if (arg.asComponent() instanceof TranslatableComponent translatableComponent) {
placeholders.add(translate((TranslatableComponent) component)); placeholders.add(translate(translatableComponent));
} else if (component instanceof TextComponent) { } else if (arg.asComponent() instanceof TextComponent textComponent) {
placeholders.add(getFullText((TextComponent) component, false)); placeholders.add(getFullText(textComponent, false));
} }
} }
//Log.info(Arrays.toString(placeholders.toArray()));
return String.format(base, placeholders.toArray()); return String.format(base, placeholders.toArray());
} else { } else {
return base; return base;
} }
} }
/**
* Get a UUID from a player name
*
* @param playerName Player name to fetch UUID from
* @return UUID from player name if available
*/
@Nullable
public static String nameToUUID(String playerName) {
try {
URL url = new URL("https://api.mojang.com/users/profiles/minecraft/" + playerName);
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new InputStreamReader(url.openStream()));
return (String) json.get("id");
} catch (ParseException | IOException ignore) {
}
return null;
}
} }
@@ -0,0 +1,25 @@
package com.shanebeestudios.mcbots.api.util.logging;
public abstract class BaseLogger {
public abstract void log(String prefix, String message);
public abstract void error(String error);
public abstract void error(Exception e);
public abstract void info(String format, Object... objects);
public abstract void info(String... message);
public abstract void info();
public abstract void warn(String... warning);
public abstract void warn();
public abstract void chat(String... chat);
public abstract void critical(Exception e);
}
@@ -0,0 +1,50 @@
package com.shanebeestudios.mcbots.api.util.logging;
import com.shanebeestudios.mcbots.plugin.McBotPlugin;
@SuppressWarnings("unused")
public class Logger {
private static BaseLogger INSTANCE = new StandaloneLogger();
public static void setupBukkitLogging(McBotPlugin plugin) {
INSTANCE = new PluginLogger(plugin);
}
public static void error(String error) {
INSTANCE.error(error);
}
public static void error(Exception e) {
INSTANCE.error(e);
}
public static void info(String format, Object... objects) {
INSTANCE.info(format, objects);
}
public static void info(String... message) {
INSTANCE.info(message);
}
public static void info() {
INSTANCE.info();
}
public static void warn(String... warning) {
INSTANCE.warn(warning);
}
public static void warn() {
INSTANCE.warn();
}
public static void chat(String... chat) {
INSTANCE.chat(chat);
}
public static void critical(Exception e) {
INSTANCE.critical(e);
}
}
@@ -0,0 +1,93 @@
package com.shanebeestudios.mcbots.api.util.logging;
import com.shanebeestudios.mcbots.plugin.McBotPlugin;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PluginLogger extends BaseLogger {
private static final String PREFIX = "&7[&bMc&3Bot&7]";
private static final String PREFIX_ERROR = "&7[&bMc&3Bot &cERROR&7]";
private static final Pattern HEX_PATTERN = Pattern.compile("<#([A-Fa-f\\d]){6}>");
@SuppressWarnings("deprecation") // Paper deprecation
public static String getColString(String string) {
Matcher matcher = HEX_PATTERN.matcher(string);
while (matcher.find()) {
final ChatColor hexColor = ChatColor.of(matcher.group().substring(1, matcher.group().length() - 1));
final String before = string.substring(0, matcher.start());
final String after = string.substring(matcher.end());
string = before + hexColor + after;
matcher = HEX_PATTERN.matcher(string);
}
return ChatColor.translateAlternateColorCodes('&', string);
}
public static void logToSender(CommandSender sender, String format, Object... objects) {
sender.sendMessage(getColString(PREFIX + " &7" + String.format(format, objects)));
}
private final Logger bukkitLogger;
public PluginLogger(McBotPlugin plugin) {
this.bukkitLogger = plugin.getLogger();
}
@Override
public void log(String prefix, String message) {
String string = getColString(prefix + " " + message);
Bukkit.getConsoleSender().sendMessage(string);
}
@Override
public void error(String error) {
log(PREFIX_ERROR, "&c" + error);
}
@SuppressWarnings("CallToPrintStackTrace")
@Override
public void error(Exception e) {
e.printStackTrace();
}
@Override
public void info(String format, Object... objects) {
log(PREFIX, "&7" + String.format(format, objects));
}
@Override
public void info(String... message) {
log(PREFIX, "&7" + String.join(" ", message));
}
@Override
public void info() {
log(PREFIX, "");
}
@Override
public void warn(String... warning) {
this.bukkitLogger.warning(String.join(" ", warning));
}
@Override
public void warn() {
this.bukkitLogger.warning("");
}
@Override
public void chat(String... chat) {
log("[CHAT]", String.join(" ", chat));
}
@Override
public void critical(Exception e) {
error(e);
}
}
@@ -0,0 +1,55 @@
package com.shanebeestudios.mcbots.api.util.logging;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StandaloneLogger extends BaseLogger {
private static final SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
public void log(String prefix, String message) {
System.out.println("\r[" + formatter.format(new Date()) + " " + prefix + "] " + message);
//System.out.print(StandaloneLoader.getInstance().getPrompt() + "> ");
}
public void error(String error) {
log("ERROR", error);
}
@SuppressWarnings("CallToPrintStackTrace")
public void error(Exception e) {
log("ERROR", "");
e.printStackTrace();
}
@Override
public void info(String format, Object... objects) {
log("INFO", String.format(format, objects));
}
public void info(String... message) {
log("INFO", String.join(" ", message));
}
public void info() {
log("INFO", "");
}
public void warn(String... warning) {
log("WARN", String.join(" ", warning));
}
public void warn() {
log("WARN", "");
}
public void chat(String... chat) {
log("CHAT", String.join(" ", chat));
}
public void critical(Exception e) {
error(e);
System.exit(1);
}
}
@@ -0,0 +1,86 @@
package com.shanebeestudios.mcbots.plugin;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.plugin.bot.PluginBotManager;
import com.shanebeestudios.mcbots.plugin.command.Command;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPIBukkitConfig;
import dev.jorel.commandapi.exceptions.UnsupportedVersionException;
import org.bukkit.Bukkit;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
@SuppressWarnings("unused")
public class McBotPlugin extends JavaPlugin {
private static McBotPlugin instance;
private boolean commandApiCanLoad;
private PluginBotManager pluginBotManager;
@Override
public void onLoad() {
try {
CommandAPI.onLoad(new CommandAPIBukkitConfig(this).verboseOutput(false));
this.commandApiCanLoad = true;
} catch (UnsupportedVersionException ignore) {
this.commandApiCanLoad = false;
}
}
@SuppressWarnings("deprecation")
@Override
public void onEnable() {
long start = System.currentTimeMillis();
instance = this;
Logger.setupBukkitLogging(this);
PluginManager pluginManager = Bukkit.getPluginManager();
if (!this.commandApiCanLoad) {
Logger.error("CommandAPI could not be loaded, plugin disabling!");
pluginManager.disablePlugin(this);
return;
}
if (Bukkit.getOnlineMode()) {
Logger.error("This plugin will only work in offline mode!");
pluginManager.disablePlugin(this);
return;
}
loadNicknameFile();
setupBotLogic();
setupCommand();
long finish = System.currentTimeMillis() - start;
String version = getDescription().getVersion();
Logger.info("&aSuccessfully enabled v%s&7 in &b%s ms", version, finish);
}
@Override
public void onDisable() {
CommandAPI.onDisable();
}
private void loadNicknameFile() {
this.saveResource("nicks.txt", false);
}
private void setupBotLogic() {
this.pluginBotManager = new PluginBotManager();
}
private void setupCommand() {
new Command(this);
Bukkit.getPluginManager().registerEvents(new PlayerListener(this), this);
}
// Getters
public static McBotPlugin getInstance() {
return instance;
}
public PluginBotManager getPluginBotManager() {
return this.pluginBotManager;
}
}
@@ -0,0 +1,48 @@
package com.shanebeestudios.mcbots.plugin;
import com.destroystokyo.paper.profile.PlayerProfile;
import com.shanebeestudios.mcbots.api.util.Utils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@SuppressWarnings({"FieldCanBeLocal", "unused"})
public class PlayerListener implements Listener {
private final McBotPlugin plugin;
private final Map<UUID, PlayerProfile> profileMap = new HashMap<>();
public PlayerListener(McBotPlugin plugin) {
this.plugin = plugin;
}
@EventHandler
private void onPreJoin(AsyncPlayerPreLoginEvent event) {
String name = event.getName();
String uuidString = Utils.nameToUUID(name);
if (uuidString != null) {
UUID uuid = UUID.fromString(uuidString.replaceFirst("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5"));
PlayerProfile profile = Bukkit.createProfile(uuid, name);
profile.complete(true, true);
this.profileMap.put(event.getUniqueId(), profile);
}
}
@EventHandler
private void onJoin(PlayerJoinEvent event) {
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
if (this.profileMap.containsKey(uuid)) {
player.setPlayerProfile(this.profileMap.get(uuid));
this.profileMap.remove(uuid);
}
}
}
@@ -0,0 +1,63 @@
package com.shanebeestudios.mcbots.plugin.bot;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable;
import java.net.Inet4Address;
import java.net.UnknownHostException;
/**
* Bot manager for server plugin
*/
public class PluginBotManager extends BotManager {
public PluginBotManager() {
this.autoRespawnDelay = 3000;
this.inetAddr = createInetAddress(getServerAddress(), Bukkit.getPort());
this.nickGenerator = new NickGenerator("plugins/McBots/nicks.txt", this.nickPrefix, true);
this.hasGravity = true;
this.gravityTimer.startTimer();
}
/**
* Create a bot
*
* @param name Name of bot or null to create random named bot
* Name must be between 1 and 16 characters
* @return Bot if was created, else null
*/
@Nullable
public Bot createBot(@Nullable String name) {
if (name != null && name.length() > 16) return null;
String botname = name != null ? name : getNickGenerator().nextNick();
Bot bot = new Bot(this, botname, getInetAddr(), null);
this.bots.add(bot);
bot.setupSessionListener(new PluginSessionListener());
bot.connect();
return bot;
}
private String getServerAddress() {
try {
return Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
@Override
public void logBotCreated(String name) {
Logger.info("Bot '&b" + name + "&7' created");
}
@Override
public void logBotDisconnected(String name) {
Logger.info("Bot '&b" + name + "&7' disconnected");
}
}
@@ -0,0 +1,75 @@
package com.shanebeestudios.mcbots.plugin.bot;
import com.github.steveice10.mc.protocol.data.game.ClientCommand;
import com.github.steveice10.mc.protocol.data.game.level.notify.GameEvent;
import com.github.steveice10.mc.protocol.data.game.level.notify.RespawnScreenValue;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundLoginPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerCombatKillPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundClientCommandPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("DuplicatedCode")
public class PluginSessionListener extends BaseSessionListener {
@Override
public void packetReceived(Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket gameEventPacket) {
if (gameEventPacket.getNotification() == GameEvent.ENABLE_RESPAWN_SCREEN) {
RespawnScreenValue respawnScreenValue = (RespawnScreenValue) gameEventPacket.getValue();
if (respawnScreenValue == RespawnScreenValue.IMMEDIATE_RESPAWN) {
this.autoRespawnDelay = 0;
} else {
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
}
}
} else if (packet instanceof ClientboundLoginPacket loginPacket) {
if (!loginPacket.isEnableRespawnScreen()) {
this.autoRespawnDelay = 0;
}
this.bot.setConnected(true);
// Might implement this later
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) {
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
PluginSessionListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
}
}, this.autoRespawnDelay);
}
}
}
@Override
public void disconnected(DisconnectedEvent event) {
this.bot.setConnected(false);
this.botManager.logBotDisconnected(this.bot.getNickname());
this.botManager.removeBot(this.bot);
Thread.currentThread().interrupt();
}
}
@@ -0,0 +1,101 @@
package com.shanebeestudios.mcbots.plugin.command;
import com.shanebeestudios.mcbots.api.util.logging.PluginLogger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.plugin.McBotPlugin;
import com.shanebeestudios.mcbots.plugin.bot.PluginBotManager;
import dev.jorel.commandapi.CommandTree;
import dev.jorel.commandapi.arguments.EntitySelectorArgument;
import dev.jorel.commandapi.arguments.GreedyStringArgument;
import dev.jorel.commandapi.arguments.IntegerArgument;
import dev.jorel.commandapi.arguments.LiteralArgument;
import dev.jorel.commandapi.arguments.StringArgument;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.scheduler.BukkitScheduler;
import java.util.Collection;
public class Command {
private final McBotPlugin plugin;
private final PluginBotManager botManager;
private final BukkitScheduler scheduler;
public Command(McBotPlugin plugin) {
this.plugin = plugin;
this.botManager = plugin.getPluginBotManager();
this.scheduler = Bukkit.getScheduler();
registerCommand();
}
@SuppressWarnings("unchecked")
public void registerCommand() {
CommandTree command = new CommandTree("mcbots")
// Create a bot
.then(new LiteralArgument("create")
.then(new LiteralArgument("named")
.then(new StringArgument("name")
.executes((sender, args) -> {
String name = (String) args.get("name");
Bot bot = this.botManager.createBot(name);
if (bot != null) {
PluginLogger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else {
PluginLogger.logToSender(sender, "&cFailed to create bot '&b" + name + "&7'");
}
})))
.then(new LiteralArgument("random")
.then(new IntegerArgument("amount")
.setOptional(true)
.then(new IntegerArgument("delay-ticks")
.setOptional(true)
.executes((sender, args) -> {
int amount = (int) args.getOrDefault("amount", 1);
long delay = (int) args.getOrDefault("delay-ticks", 20);
for (int i = 0; i < amount; i++) {
this.scheduler.runTaskLater(this.plugin, () -> {
Bot bot = this.botManager.createBot(null);
if (bot != null) {
PluginLogger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else {
PluginLogger.logToSender(sender, "&cFailed to create random bot!");
}
}, delay * i);
}
})))))
// Remove a bot
.then(new LiteralArgument("remove")
.then(new EntitySelectorArgument.ManyPlayers("players")
.executes((sender, args) -> {
Collection<Entity> players = (Collection<Entity>) args.get("players");
assert players != null;
players.forEach(player -> {
Bot bot = this.botManager.findBotByName(player.getName());
if (bot != null) {
this.botManager.disconnectBot(bot);
PluginLogger.logToSender(sender, "Removed bot &7'" + bot.getNickname() + "&7'");
}
});
})))
// Make a bot send a chat message or command
.then(new LiteralArgument("chat")
.then(new EntitySelectorArgument.ManyPlayers("players")
.then(new GreedyStringArgument("message")
.executes((sender, args) -> {
String message = (String) args.get("message");
Collection<Entity> players = (Collection<Entity>) args.get("players");
assert message != null;
assert players != null;
players.forEach(player -> {
Bot bot = this.botManager.findBotByName(player.getName());
if (bot != null) bot.sendChat(message);
});
}))));
command.register();
}
}
@@ -0,0 +1,43 @@
package com.shanebeestudios.mcbots.standalone;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
public class Main {
public static void main(String[] args) {
Options options = new Options();
options.addOption("c", "count", true, "bot count");
Option addressOption = new Option("s", "server", true, "server IP[:port]");
addressOption.setRequired(true);
options.addOption(addressOption);
Option delayOption = new Option("d", "delay", true, "connection delay (ms) <min> <max>");
delayOption.setArgs(2);
options.addOption(delayOption);
options.addOption("r", "real", false, "generate real looking nicknames");
options.addOption("n", "nocolor", false, "dont color & format incoming chat messages");
options.addOption("p", "prefix", true, "bot nick prefix");
options.addOption("m", "minimal", false, "minimal run without any listeners");
options.addOption("x", "most-minimal", false, "minimal run without any control, just connect the bots");
options.addOption("j", "join-msg", true, "join messages / commands, separated by &&");
options.addOption("l", "proxy-list", true, "Path or URL to proxy list file with proxy:port on every line");
options.addOption("t", "proxy-type", true, "Proxy type: SOCKS4 or SOCKS5");
options.addOption(null, "nicks", true, "Path to nicks file with nick on every line");
options.addOption("g", "gravity", false, "Try to simulate gravity by falling down");
options.addOption("o", "online", false, "Use online mode (premium) account");
options.addOption("ar", "auto-respawn", true, "Set autorespawn delay (-1 to disable)");
new StandaloneBotManager(options, args);
}
}
@@ -0,0 +1,161 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ConsoleReader {
private final StandaloneBotManager standaloneLoader;
public ConsoleReader(StandaloneBotManager standaloneLoader) {
this.standaloneLoader = standaloneLoader;
}
@SuppressWarnings("BusyWait")
public void start() {
Terminal terminal;
try {
terminal = TerminalBuilder.builder().build();
} catch (IOException e) {
throw new RuntimeException(e);
}
LineReader lineReader = LineReaderBuilder.builder()
.terminal(terminal)
.parser(new org.jline.reader.impl.DefaultParser())
.build();
while (true) {
HashSet<Bot> controlledBots = this.standaloneLoader.getControlledBots();
ArrayList<Bot> bots = this.standaloneLoader.getBots();
String line;
try {
line = lineReader.readLine();
} catch (UserInterruptException e) {
System.exit(0);
break;
}
if (line.isEmpty()) {
System.out.print(this.standaloneLoader.getPrompt() + "> ");
continue;
}
if (line.startsWith("!") || line.startsWith(".")) {
String command = line.substring(1);
String[] split = command.split(" ");
String commandName = split[0];
// Bot control selection
if (commandName.equalsIgnoreCase("control") || commandName.equalsIgnoreCase("ctrl")) {
if (split.length >= 2) {
controlledBots.clear();
int newBotCount = 0;
// Search for all bot names, from index 1 - skip command name
for (int i = 1; i < split.length; i++) {
String searchedName = split[i];
Bot bot = this.standaloneLoader.findBotByName(searchedName);
if (bot != null) {
controlledBots.add(bot);
newBotCount++;
} else {
Logger.warn("Bot not found: " + searchedName);
}
}
if (newBotCount > 0) {
// Join bot nicknames
String botNames = controlledBots
.stream()
.map(Bot::getNickname)
.collect(Collectors.joining(", "));
if (newBotCount == 1) {
Logger.info("Now controlling 1 bot: " + botNames);
} else {
Logger.info("Now controlling " + newBotCount + " bots: " + botNames);
}
} else {
Logger.warn("No bots found.");
}
} else {
// If no bot names are supplied, remove all bots
controlledBots.clear();
Logger.info("No bots selected - now controlling all bots.");
}
}
// List command
else if (commandName.equalsIgnoreCase("list") || commandName.equalsIgnoreCase("ls")) {
Logger.info("There are " + bots.size() + " bots connected:");
for (Bot bot : bots) {
Logger.info(bot.getNickname(), bot.hasMainListener() ? "[MainListener]" : "");
}
}
// Leave command
else if (commandName.equalsIgnoreCase("leave") || commandName.equalsIgnoreCase("exit")) {
int limit = -1;
if (split.length >= 2) {
try {
limit = Integer.parseInt(split[1]);
} catch (NumberFormatException e) {
limit = 0;
Logger.warn("Invalid limit.");
}
}
int i = 0;
if (!controlledBots.isEmpty()) {
Logger.info("Disconnecting controlled bots.");
for (Bot bot : controlledBots) {
if (i++ == limit) {
break;
}
bot.disconnect();
}
} else {
Logger.info("Disconnecting all bots.");
for (Bot bot : bots) {
if (i++ == limit) {
break;
}
bot.disconnect();
}
}
} else {
Logger.warn("Invalid command");
}
} else if (!controlledBots.isEmpty()) {
controlledBots.forEach(bot -> bot.sendChat(line));
} else {
bots.forEach(bot -> bot.sendChat(line));
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
@@ -0,0 +1,79 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.auth.exception.request.AuthPendingException;
import com.github.steveice10.mc.auth.exception.request.RequestException;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.mc.auth.service.MsaAuthenticationService;
import com.github.steveice10.mc.auth.util.HTTP;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.standalone.bot.StandaloneBotManager;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
public class OnlineService {
private final String clientId = "8bef943e-5a63-429e-a93a-96391d2e32a9";
private final StandaloneBotManager botManager;
public OnlineService(StandaloneBotManager botManager) {
this.botManager = botManager;
}
public AuthenticationService getOnlineAuthenticationService() {
Logger.warn("Online mode enabled. The bot count will be set to 1.");
this.botManager.setBotCount(1);
// Create request parameters map
Map<String, String> params = new HashMap<>();
params.put("client_id", clientId);
params.put("scope", "XboxLive.signin");
// Send request to Microsoft OAuth api
// https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-device-code
URI endpointURI = URI.create("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode");
MsaAuthenticationService.MsCodeResponse response;
try {
response = HTTP.makeRequestForm(
Proxy.NO_PROXY, endpointURI, params, MsaAuthenticationService.MsCodeResponse.class
);
} catch (RequestException e) {
throw new RuntimeException(e);
}
try {
Logger.info("Please go to " + response.verification_uri.toURL() + " to authenticate your account - Code: " + response.user_code);
} catch (MalformedURLException e) {
Logger.error("Error while trying to get the url of the authentication page");
}
AuthenticationService authService = new MsaAuthenticationService(clientId, response.device_code);
// Wait for user to login on microsoft page
int retryMax = 20;
while (true) {
try {
authService.login();
break;
} catch (Exception e) {
if (e instanceof AuthPendingException) {
Logger.info("Authentication is pending, waiting for user to authenticate...");
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
if (retryMax == 0)
throw new RuntimeException(e);
retryMax--;
} else {
throw new RuntimeException(e);
}
}
}
return authService;
}
}
@@ -0,0 +1,268 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.auth.service.AuthenticationService;
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.shanebeestudios.mcbots.api.BotManager;
import com.shanebeestudios.mcbots.api.ServerInfo;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.generator.ProxyGenerator;
import com.shanebeestudios.mcbots.api.util.Pair;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.bot.BotLoader;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.jetbrains.annotations.Nullable;
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import java.net.InetSocketAddress;
import java.util.HashSet;
public class StandaloneBotManager extends BotManager {
protected int botCount;
private final int delayMin;
private final int delayMax;
private final boolean coloredChat;
private final boolean online;
private ProxyGenerator proxyGenerator;
private final HashSet<Bot> controlledBots = new HashSet<>();
private final AuthenticationService authenticationService;
private final BotLoader botLoader;
private boolean isMainListenerMissing = true;
public StandaloneBotManager(Options options, String[] args) {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = null;
try {
cmd = parser.parse(options, args);
} catch (ParseException e) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("mcbots", e.getMessage(), options, "\nhttps://github.com/ShaneBeee/mc-bots", true);
System.exit(1);
}
this.autoRespawnDelay = Integer.parseInt(cmd.getOptionValue("ar", "100"));
boolean hasProxy = cmd.hasOption('t') && cmd.hasOption('l');
if (hasProxy) {
String proxyType = cmd.getOptionValue('t').toUpperCase();
String proxyPath = cmd.getOptionValue("l");
this.proxyGenerator = new ProxyGenerator(proxyType, proxyPath);
}
this.botCount = Integer.parseInt(cmd.getOptionValue('c', "1"));
this.minimal = cmd.hasOption('m');
if (cmd.hasOption('x')) {
this.minimal = this.mostMinimal = true;
}
if (cmd.hasOption('d')) {
String[] delays = cmd.getOptionValues('d');
Pair<Integer, Integer> delay = parseDelays(delays);
this.delayMin = delay.getFirst();
this.delayMax = delay.getSecond();
} else {
this.delayMin = 4000;
this.delayMax = 5000;
}
String address = cmd.getOptionValue('s');
Pair<String, Integer> addressPort = parseAddress(address);
this.inetAddr = createInetAddress(addressPort.getFirst(), addressPort.getSecond());
this.coloredChat = !cmd.hasOption('n');
if (cmd.hasOption('j')) {
// Split messages by &&, trim and append to arraylist
String[] messages = cmd.getOptionValue('j').split("&&");
for (String msg : messages) {
this.joinMessages.add(msg.trim());
}
}
boolean useRealNick = cmd.hasOption('r');
this.nickPath = cmd.getOptionValue("nicks", null);
this.nickPrefix = cmd.getOptionValue('p', "");
this.nickGenerator = new NickGenerator(this.nickPath, this.nickPrefix, useRealNick);
this.online = cmd.hasOption("o");
this.hasGravity = cmd.hasOption("g");
getAndPrintServerInfo(getInetAddr());
if (isOnline()) {
OnlineService onlineService = new OnlineService(this);
this.authenticationService = onlineService.getOnlineAuthenticationService();
} else {
this.authenticationService = null;
}
// Load bots
this.botLoader = new BotLoader(this);
this.botLoader.spin();
if (hasGravity()) {
this.gravityTimer.startTimer();
}
// Load console reader
ConsoleReader consoleReader = new ConsoleReader(this);
consoleReader.start();
}
private Pair<String, Integer> parseAddress(String address) {
int port = 25565;
if (address.contains(":")) {
String[] split = address.split(":", 2);
address = split[0];
port = Integer.parseInt(split[1]);
} else {
Record[] records;
try {
records = new Lookup("_minecraft._tcp." + address, Type.SRV).run();
} catch (TextParseException e) {
throw new RuntimeException(e);
}
if (records != null) {
for (Record record : records) {
SRVRecord srv = (SRVRecord) record;
address = srv.getTarget().toString().replaceFirst("\\.$", "");
port = srv.getPort();
}
}
}
return new Pair<>(address, port);
}
private Pair<Integer, Integer> parseDelays(String[] delays) {
int delayMin = Integer.parseInt(delays[0]);
int delayMax = delayMin + 1;
if (delays.length == 2) {
delayMax = Integer.parseInt(delays[1]);
}
if (delayMax <= delayMin) {
throw new IllegalArgumentException("delay max must not be equal or lower than delay min");
}
return new Pair<>(delayMin, delayMax);
}
private void getAndPrintServerInfo(InetSocketAddress inetAddr) {
//print info
Logger.info("Server Address:", inetAddr.getHostString());
Logger.info("Server Port: " + inetAddr.getPort());
Logger.info("Bot count: " + getBotCount());
//get and print server info
ServerInfo serverInfo = new ServerInfo(inetAddr);
serverInfo.requestInfo();
ServerStatusInfo statusInfo = serverInfo.getStatusInfo();
if (statusInfo != null) {
Logger.info(
"Server version: "
+ statusInfo.getVersionInfo().getVersionName()
+ " (" + statusInfo.getVersionInfo().getProtocolVersion()
+ ")"
);
Logger.info("Player Count: " + statusInfo.getPlayerInfo().getOnlinePlayers()
+ " / " + statusInfo.getPlayerInfo().getMaxPlayers());
Logger.info();
} else {
Logger.warn("There was an error retrieving server status information. The server may be offline or running on a different version.");
}
}
public void renewMainListener() {
this.bots.get(0).registerMainListener();
}
@Override
public void removeBot(Bot bot) {
super.removeBot(bot);
controlledBots.remove(bot);
if (bot.hasMainListener()) {
Logger.info("Bot with MainListener removed");
this.isMainListenerMissing = true;
}
if (!this.bots.isEmpty()) {
if (this.isMainListenerMissing && !isMinimal()) {
Logger.info("Renewing MainListener");
renewMainListener();
this.isMainListenerMissing = false;
}
} else {
if (this.botLoader.getTriedToConnect() == getBotCount()) {
Logger.error("All bots disconnected, exiting");
System.exit(0);
}
}
}
public String getPrompt() {
int count = this.getControlledBots().size();
if (count == 0) {
return "ALL";
} else if (count == 1) {
//If controlling only one bot, return its nickname
return getControlledBots().iterator().next().getNickname();
} else {
return count + " BOTS";
}
}
public int getBotCount() {
return this.botCount;
}
public void setBotCount(int botCount) {
this.botCount = botCount;
}
public int getDelayMin() {
return this.delayMin;
}
public int getDelayMax() {
return this.delayMax;
}
public boolean isColoredChat() {
return this.coloredChat;
}
public boolean isOnline() {
return this.online;
}
@Nullable
public ProxyGenerator getProxyGenerator() {
return this.proxyGenerator;
}
public HashSet<Bot> getControlledBots() {
return this.controlledBots;
}
public AuthenticationService getAuthenticationService() {
return this.authenticationService;
}
public boolean isMainListenerMissing() {
return this.isMainListenerMissing;
}
public void setMainListenerMissing(boolean missing) {
this.isMainListenerMissing = missing;
}
}
@@ -0,0 +1,101 @@
package com.shanebeestudios.mcbots.standalone.bot;
import com.github.steveice10.mc.protocol.data.UnexpectedEncryptionException;
import com.github.steveice10.mc.protocol.data.game.ClientCommand;
import com.github.steveice10.mc.protocol.data.game.level.notify.GameEvent;
import com.github.steveice10.mc.protocol.data.game.level.notify.RespawnScreenValue;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.ClientboundLoginPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerCombatKillPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import com.github.steveice10.mc.protocol.packet.ingame.clientbound.level.ClientboundGameEventPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.ServerboundClientCommandPacket;
import com.github.steveice10.mc.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.packet.Packet;
import com.shanebeestudios.mcbots.api.listener.BaseSessionListener;
import com.shanebeestudios.mcbots.api.util.Utils;
import com.shanebeestudios.mcbots.api.util.logging.Logger;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings({"CallToPrintStackTrace", "DuplicatedCode"})
public class StandaloneSessionListener extends BaseSessionListener {
@Override
public void packetReceived(Session session, Packet packet) {
if (packet instanceof ClientboundGameEventPacket gameEventPacket) {
if (gameEventPacket.getNotification() == GameEvent.ENABLE_RESPAWN_SCREEN) {
RespawnScreenValue value = (RespawnScreenValue) gameEventPacket.getValue();
if (value == RespawnScreenValue.IMMEDIATE_RESPAWN) {
this.autoRespawnDelay = 0;
} else {
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
}
}
} else if (packet instanceof ClientboundLoginPacket loginPacket) {
if (!loginPacket.isEnableRespawnScreen()) {
this.autoRespawnDelay = 0;
}
this.bot.setConnected(true);
Logger.info(this.bot.getNickname() + " connected");
if (!this.joinMessages.isEmpty()) {
for (String msg : this.joinMessages) {
this.bot.sendChat(msg);
try {
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}
}
} else if (packet instanceof ClientboundPlayerPositionPacket positionPacket) {
this.bot.setLastPosition(positionPacket.getX(), positionPacket.getY(), positionPacket.getZ());
this.client.send(new ServerboundAcceptTeleportationPacket(positionPacket.getTeleportId()));
} else if (packet instanceof ClientboundPlayerCombatKillPacket) {
if (this.autoRespawnDelay >= 0) {
Logger.info("Bot " + this.bot.getNickname() + " died. Respawning in " + this.autoRespawnDelay + " ms.");
new Timer().schedule(
new TimerTask() {
@Override
public void run() {
StandaloneSessionListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
}
}, this.autoRespawnDelay);
}
}
}
@Override
public void disconnected(DisconnectedEvent event) {
this.bot.setConnected(false);
this.botManager.logBotDisconnected(this.bot.getNickname());
// Do not write disconnect reason if disconnected by command
if (!this.bot.isManualDisconnecting()) {
Component reason = event.getReason();
if (reason != null) {
String reasonText = Utils.getFullText((TextComponent) reason, true);
Logger.info("Reason: " + reasonText);
}
Throwable cause = event.getCause();
if (cause != null) {
cause.printStackTrace();
if (cause instanceof UnexpectedEncryptionException) {
Logger.warn("Server is running in online (premium) mode. Please use the -o option to use online mode bot.");
System.exit(1);
}
}
Logger.info();
}
this.botManager.removeBot(this.bot);
Thread.currentThread().interrupt();
}
}
@@ -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;
}
}
@@ -1,3 +1,7 @@
# NickName File
# Add/Remove whatever names you want
# Names need to be between 3 and 16 characters
Ceweau Ceweau
Grossier Grossier
Conjuh Conjuh
@@ -837,7 +841,6 @@ Dreadknotts
PresleyNaeNae PresleyNaeNae
GalaxyApples GalaxyApples
FruitPvP FruitPvP
GayCuntNiggerKys
JapanaTTV JapanaTTV
Infidante Infidante
Mxtte_ Mxtte_
@@ -995,7 +998,6 @@ Kurokami_PL_
Sqahseh Sqahseh
SydHatesLemons SydHatesLemons
BIGDictation BIGDictation
pileofcum
DerpyTheSnowman DerpyTheSnowman
surfyyy surfyyy
MinaPenguini MinaPenguini
@@ -2047,7 +2049,6 @@ JamesMaris
khunt6 khunt6
EivindRyntveit EivindRyntveit
fromshifter fromshifter
QueerFaggot
ReqtAngle3 ReqtAngle3
EndlessName EndlessName
_16cps_ _16cps_
+6
View File
@@ -0,0 +1,6 @@
main: com.shanebeestudios.mcbots.plugin.McBotPlugin
name: "McBots"
version: @version@
api-version: 1.13
loadbefore:
- Skript