Dev/remove standalone #86

Closed
ShaneBeee wants to merge 11 commits from dev/remove-standalone into main
pull from: dev/remove-standalone
32 changed files with 1038 additions and 6734 deletions

No files matched your search

+7 -11
View File
@@ -1,7 +1,7 @@
--- ---
name: Bug report name: Bug report
about: Create a report to help us improve about: Create a report to help us improve
title: '' title: "[BUG]"
labels: bug labels: bug
assignees: '' assignees: ''
@@ -11,21 +11,17 @@ assignees: ''
A clear and concise description of what the bug is. A clear and concise description of what the bug is.
**To Reproduce** **To Reproduce**
Steps to reproduce the behavior: Please include clear steps to reproduce the behavior
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior** **Expected behavior**
A clear and concise description of what you expected to happen. A clear and concise description of what you expected to happen.
**Screenshot or app console output** **Screenshots/Errors**
If applicable, add screenshots to help explain your problem. If applicable, add screenshots/errors to help explain your problem.
**Whole command used to start the app** **Version Info:**
Please insert the whole command you used to start the app. - **Plugin/App Version:** (ex. 1.0.0)
Censoring ip address is recommended. - **Server Version/Platform** (ex: Paper 1.20.4)
**Additional context** **Additional context**
Add any other context about the problem here. Add any other context about the problem here.
+1 -1
View File
@@ -2,7 +2,7 @@
name: Feature request name: Feature request
about: Suggest an idea for this project about: Suggest an idea for this project
title: '' title: ''
labels: '' labels: enhancement
assignees: '' assignees: ''
--- ---
+41
View File
@@ -0,0 +1,41 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle
name: Java CI with Gradle
on:
push:
branches: [ '**' ]
pull_request:
branches: [ '**' ]
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Build with Gradle
uses: gradle/gradle-build-action@bd5760595778326ba7f1441bcf7e88b49de61a25 # v2.6.0
with:
arguments: build
- name: Upload a Build Artifact
uses: actions/upload-artifact@v3.1.2
with:
# Artifact name
name: McBots-Artifact
# A file, directory or wildcard pattern that describes what to upload
path: build/libs/mc-bots*.jar
+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.**
+47 -17
View File
@@ -1,35 +1,65 @@
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.0.0'
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' // McProtocol
implementation 'commons-cli:commons-cli:1.5.0' implementation('com.github.steveice10:mcprotocollib:1.20.4-2-SNAPSHOT')
implementation 'com.diogonunes:JColor:5.2.0' implementation('net.kyori:adventure-text-serializer-gson:4.16.0')
implementation 'dnsjava:dnsjava:3.4.3'
implementation 'org.slf4j:slf4j-nop:1.7.32' // Paper
implementation 'org.jline:jline:3.22.0' compileOnly("io.papermc.paper:paper-api:1.20.4-R0.1-SNAPSHOT")
// Command Api
implementation("dev.jorel:commandapi-bukkit-shade:9.3.0")
} }
jar { processResources {
manifest { filter ReplaceTokens, tokens: ["version": project.version]
attributes 'Main-Class': 'me.creepermaxcz.mcbots.Main' }
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
} shadowJar {
from { archiveClassifier = null
configurations.runtimeClasspath.filter{ it.exists() }.collect { it.isDirectory() ? it : zipTree(it) } minimize()
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,132 @@
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 java.net.InetSocketAddress;
import java.time.Instant;
import java.util.BitSet;
import java.util.Collections;
@SuppressWarnings("unused")
public class Bot {
private final MinecraftProtocol protocol;
private final BotManager botManager;
private final String nickname;
private final Session client;
private double lastX, lastY, lastZ = -1;
private boolean connected;
private boolean manualDisconnecting = false;
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);
}
/**
* Connect the bot to the server
*/
public void connect() {
new Thread(() -> {
this.client.addListener(new PacketListener(this));
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 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 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,167 @@
package com.shanebeestudios.mcbots.api.bot;
import com.shanebeestudios.mcbots.api.generator.NickGenerator;
import com.shanebeestudios.mcbots.api.timer.GravityTimer;
import com.shanebeestudios.mcbots.api.util.Logger;
import org.bukkit.Bukkit;
import org.jetbrains.annotations.Nullable;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
/**
* Bot manager for server plugin
*/
@SuppressWarnings("unused")
public class BotManager {
private final int autoRespawnDelay;
private final String nickPath = null;
private final String nickPrefix = "";
private final boolean hasGravity;
private final ArrayList<String> joinMessages = new ArrayList<>();
private final InetSocketAddress inetAddr;
private final ArrayList<Bot> bots = new ArrayList<>();
private final NickGenerator nickGenerator;
private final GravityTimer gravityTimer;
public BotManager() {
this.autoRespawnDelay = 3000;
this.inetAddr = createInetAddress(getServerAddress(), Bukkit.getPort());
this.nickGenerator = new NickGenerator("plugins/McBots/nicks.txt", this.nickPrefix, true);
this.hasGravity = true;
this.gravityTimer = new GravityTimer(this);
this.gravityTimer.startTimer();
}
// Methods
private 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 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;
}
public GravityTimer getGravityTimer() {
return this.gravityTimer;
}
/**
* 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;
}
/**
* 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;
}
/**
* Create a bot
*
* @param name Name of bot or null to create random named bot
* Name must be between 1 and 16 characters
* @return Bot if was created, else null
*/
@Nullable
public Bot createBot(@Nullable String name) {
if (name != null && name.length() > 16) return null;
String botname = name != null ? name : getNickGenerator().nextNick();
Bot bot = new Bot(this, botname, getInetAddr(), null);
this.bots.add(bot);
bot.connect();
return bot;
}
private String getServerAddress() {
try {
return Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
}
public void logBotCreated(String name) {
Logger.info("Bot '&b" + name + "&7' created");
}
public void logBotDisconnected(String name) {
Logger.info("Bot '&b" + name + "&7' disconnected");
}
}
@@ -0,0 +1,88 @@
package com.shanebeestudios.mcbots.api.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.event.session.SessionAdapter;
import com.github.steveice10.packetlib.packet.Packet;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings("DuplicatedCode")
public class PacketListener extends SessionAdapter {
protected Bot bot;
protected Session client;
protected BotManager botManager;
protected ArrayList<String> joinMessages;
protected int autoRespawnDelay;
public PacketListener(Bot bot) {
this.bot = bot;
this.client = bot.getClient();
this.botManager = bot.getBotManager();
this.joinMessages = this.botManager.getJoinMessages();
this.autoRespawnDelay = this.botManager.getAutoRespawnDelay();
}
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() {
PacketListener.this.client.send(new ServerboundClientCommandPacket(ClientCommand.RESPAWN));
}
}, this.autoRespawnDelay);
}
}
}
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,106 @@
package com.shanebeestudios.mcbots.api.generator;
import com.shanebeestudios.mcbots.api.util.Logger;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedReader;
import java.io.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,27 @@
package com.shanebeestudios.mcbots.api.timer;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.bot.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,69 @@
package com.shanebeestudios.mcbots.api.util;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@SuppressWarnings("unused")
public class Logger {
private static final String PREFIX = "&7[&bMc&3Bot&7]";
private static final String PREFIX_ERROR = "&7[&bMc&3Bot &cERROR&7]";
private static final String PREFIX_WARN = "&7[&bMc&3Bot &eWARN&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)));
}
public static void log(String prefix, String message) {
String string = getColString(prefix + " " + message);
Bukkit.getConsoleSender().sendMessage(string);
}
public static void error(String error) {
log(PREFIX_ERROR, "&c" + error);
}
@SuppressWarnings("CallToPrintStackTrace")
public static void error(Exception e) {
e.printStackTrace();
}
public static void info(String format, Object... objects) {
log(PREFIX, "&7" + String.format(format, objects));
}
public static void info(String... message) {
log(PREFIX, "&7" + String.join(" ", message));
}
public static void info() {
log(PREFIX, "");
}
public static void warn(String... warning) {
log(PREFIX_WARN, String.join(" ", warning));
}
public static void critical(Exception e) {
error(e);
}
}
@@ -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;
}
}
@@ -0,0 +1,32 @@
package com.shanebeestudios.mcbots.api.util;
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.InputStreamReader;
import java.net.URL;
public class Utils {
/**
* 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,100 @@
package com.shanebeestudios.mcbots.plugin;
import com.shanebeestudios.mcbots.api.bot.Bot;
import com.shanebeestudios.mcbots.api.bot.BotManager;
import com.shanebeestudios.mcbots.api.util.Logger;
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 BotManager 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) {
Logger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else {
Logger.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) {
Logger.logToSender(sender, "Created new bot '&b" + bot.getNickname() + "&7'");
} else {
Logger.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);
Logger.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,93 @@
package com.shanebeestudios.mcbots.plugin;
import com.shanebeestudios.mcbots.api.bot.BotManager;
import com.shanebeestudios.mcbots.api.util.Logger;
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 BotManager botManager;
@Override
public void onLoad() {
if (Bukkit.getOnlineMode()) {
// Don't load CommandAPI
return;
}
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();
PluginManager pluginManager = Bukkit.getPluginManager();
if (Bukkit.getOnlineMode()) {
Logger.error("***********************************************");
Logger.error("* *");
Logger.error("* This plugin will only work in offline mode! *");
Logger.error("* *");
Logger.error("***********************************************");
pluginManager.disablePlugin(this);
return;
}
instance = this;
if (!this.commandApiCanLoad) {
Logger.error("CommandAPI could not be loaded, plugin disabling!");
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() {
if (!Bukkit.getOnlineMode()) CommandAPI.onDisable();
instance = null;
}
private void loadNicknameFile() {
this.saveResource("nicks.txt", false);
}
private void setupBotLogic() {
this.botManager = new BotManager();
}
private void setupCommand() {
CommandAPI.onEnable();
new Command(this);
Bukkit.getPluginManager().registerEvents(new PlayerListener(this), this);
}
// Getters
public static McBotPlugin getInstance() {
return instance;
}
public BotManager getPluginBotManager() {
return this.botManager;
}
}
@@ -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);
}
}
}
@@ -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,66 +0,0 @@
package me.creepermaxcz.mcbots;
import com.github.steveice10.mc.protocol.MinecraftConstants;
import com.github.steveice10.mc.protocol.MinecraftProtocol;
import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.github.steveice10.mc.protocol.data.status.handler.ServerInfoHandler;
import com.github.steveice10.mc.protocol.data.status.handler.ServerPingTimeHandler;
import com.github.steveice10.packetlib.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.tcp.TcpClientSession;
import java.net.InetSocketAddress;
public class ServerInfo {
private final Session client;
private ServerStatusInfo serverStatusInfo;
private long ping;
private boolean done;
public ServerInfo(InetSocketAddress address) {
MinecraftProtocol protocol = new MinecraftProtocol();
client = new TcpClientSession(address.getHostString(), address.getPort(), protocol, null);
client.setFlag(MinecraftConstants.SERVER_INFO_HANDLER_KEY, (ServerInfoHandler) (session, info) -> {
this.serverStatusInfo = info;
});
client.setFlag(MinecraftConstants.SERVER_PING_TIME_HANDLER_KEY, (ServerPingTimeHandler) (session, pingTime) -> {
this.ping = pingTime;
});
client.addListener(new SessionAdapter() {
@Override
public void disconnected(DisconnectedEvent event) {
done = true;
}
});
}
public void requestInfo()
{
client.connect();
//wait to disconnect
while (!done) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public ServerStatusInfo getStatusInfo()
{
return serverStatusInfo;
}
public long getPing() {
return ping;
}
}
@@ -1,158 +0,0 @@
package me.creepermaxcz.mcbots;
import com.diogonunes.jcolor.Attribute;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static com.diogonunes.jcolor.Ansi.colorize;
public class Utils {
private static JsonObject lang;
public static String getFullText(TextComponent message, boolean colored) {
if (message.children().size() > 0) {
StringBuilder text = new StringBuilder();
text.append(parseColor(message, colored));
for (Component child : message.children()) {
if (child instanceof TextComponent) {
text.append(getFullText((TextComponent) child, colored));
} else if (child instanceof TranslatableComponent) {
text.append(translate((TranslatableComponent) child));
}
}
return text.toString();
} else {
return parseColor(message, colored);
}
}
/**
* A static function that gets full text from text components.
* From 1.19.1 the protocol does not include sender's information in the message.
* Thus, we need to merge two TextComponent (sender and message) and generate a text that consists of sent message.
* This means using old getFullText will just send the message. Which does NOT contain username who sent this message
*
* @param sender The TextComponent for sender.
* @param message The TextComponent for message.
* @param colored Whether if this output was colored or not.
* @return Returns String in "Username : Message" format.
*/
public static String getFullText(@Nullable TextComponent sender, TextComponent message, boolean colored) {
if (colored) {
Style messageStyle = message.style();
StringBuilder outString = new StringBuilder();
if (sender != null) {
Style senderStyle = sender.style();
if (senderStyle.color() != null) { // Generate sender text with color.
outString.append(colorizeText(sender.content(), senderStyle.color()));
} else {
outString.append(sender.content());
}
outString.append(" : "); // Add delimiter as : between sender and message.
}
if (messageStyle.color() != null && sender != null) { // Generate message text with color.
outString.append(colorizeText(sender.content(), messageStyle.color()));
} else {
outString.append(message.content());
}
return outString.toString();
} else {
if (sender == null)
return message.content();
else
return sender.content() + " : " + message.content();
}
}
private static String parseColor(TextComponent message, boolean colored) {
String out = message.content();
if (colored) {
if (message.style().color() != null) {
List<Attribute> formats = new ArrayList<>(getFormats(message.style().decorations()));
TextColor color = message.style().color();
formats.add(Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
out = colorize(out, formats.toArray(new Attribute[0]));
}
}
return out;
}
private static String colorizeText(String text, TextColor color) {
return colorize(text, Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
}
public static List<Attribute> getFormats(Map<TextDecoration, TextDecoration.State> decorations) {
List<Attribute> list = new ArrayList<>();
decorations.forEach((format, state) -> {
if (state.equals(TextDecoration.State.TRUE)) {
switch (format) {
case ITALIC:
list.add(Attribute.ITALIC());
break;
case UNDERLINED:
list.add(Attribute.UNDERLINE());
break;
case STRIKETHROUGH:
list.add(Attribute.STRIKETHROUGH());
break;
}
}
});
return list;
}
public static String translate(TranslatableComponent message) {
if (lang == null) {
try {
InputStream resource = Utils.class.getResourceAsStream("/files/lang.json");
lang = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject();
} catch (Exception e) {
Log.crit(e);
}
}
//Log.info(message.toString());
String key = message.key();
String base = key;
JsonElement value = lang.get(key);
if (value != null) {
base = value.getAsString();
}
ArrayList<String> placeholders = new ArrayList<>();
if (message.args().size() > 0) {
for (Component component : message.args()) {
if (component instanceof TranslatableComponent) {
placeholders.add(translate((TranslatableComponent) component));
} else if (component instanceof TextComponent) {
placeholders.add(getFullText((TextComponent) component, false));
}
}
//Log.info(Arrays.toString(placeholders.toArray()));
return String.format(base, placeholders.toArray());
} else {
return base;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -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