80 Commits
Author SHA1 Message Date
crpmax e8e3b4f9c0 fix: downgrade dnsjava, feat: update readme 2025-08-06 14:35:49 +02:00
정현우니andCreeperMax 7c1eb7cf24 Update for Minecraft 1.21.7 (#111)
* chore: update Gradle wrapper to version 9.0.0

* chore: update Java toolchain to version 17

* chore: update dependencies to latest versions

* fix: add missing parameter to chat packet constructor

---------

Co-authored-by: CreeperMax <38163280+crpmax@users.noreply.github.com>
2025-08-06 14:11:38 +02:00
crpmax ce9d01a47f feat: v1.2.16 - update to MC 1.21.6 2025-08-06 13:55:45 +02:00
crpmax b81b61187f feat: v1.2.15 - update to MC 1.21.5 2025-08-06 13:47:38 +02:00
crpmax 5e109efc56 chore: update readme 2025-02-26 21:13:34 +01:00
crpmax 91e4d44170 chore: remove unused constructor 2025-02-26 21:12:04 +01:00
Elecast e2a477e56f update to MC 1.21.4 (#101) 2025-02-26 19:48:04 +01:00
crpmax 1ce1f98801 update to MC 1.21.2 2025-02-21 18:59:54 +01:00
crpmax 9865364919 update to MC 1.21 2025-02-21 18:12:04 +01:00
Lukas ʕ•́ᴥ•̀ʔ fb99076f88 Fix spelling mistake (#93) 2024-07-24 13:56:46 +02:00
crpmax da26ec8a99 update readme to MC 1.20.6 2024-07-17 00:59:12 +02:00
crpmax 8b2dddf8d6 update to MC 1.20.6 2024-07-17 00:58:23 +02:00
crpmax c57febbd0a update to MC 1.20.4 2024-07-17 00:15:52 +02:00
CreeperMaxCZ 78cf07636d update to MC 1.20.2 2023-12-07 21:30:04 +01:00
CreeperMaxCZ 3311f0889a Merge pull request #73 from Norbiros/fix/chat
Important chat bug fixes
2023-08-14 22:48:38 +02:00
CreeperMaxCZ c05b7ffef4 Merge pull request #72 from Norbiros/feat/use-jline
feat: Switch to JLine.
2023-08-14 22:48:08 +02:00
CreeperMaxCZ d8c2139df6 Merge branch 'main' into feat/use-jline 2023-08-14 22:48:00 +02:00
CreeperMaxCZ 5c12776348 Merge pull request #71 from ShayanGsh/main
Added support for Minecraft 1.20
2023-08-14 22:46:00 +02:00
Norbiros 896c320dd7 fix: Chat bug fixes 2023-08-13 00:22:23 +02:00
Shayan d8cd699012 Merging 2023-08-09 18:01:45 +00:00
Shayan d550c69583 Updated Readme for 1.20 and increased mc-bots' version in gradle 2023-08-09 17:57:06 +00:00
Norbiros 4c239b9b5b feat: Switch to JLine. 2023-08-08 13:13:32 +02:00
Shayan f82eb34588 feat: Support for 1.20! 2023-08-01 20:49:16 +03:30
CreeperMaxCZ ea0efd88bb Merge pull request #69 from Norbiros/main
Proper support fo 1.19.4!
2023-07-15 14:13:36 +02:00
CreeperMaxCZ 2d78e85544 docs: readme - commands 2023-07-15 13:58:13 +02:00
Norbiros 1fbadaba9c feat: Support 1.19.4! 2023-07-02 10:55:34 +02:00
CreeperMaxCZ f8e2f2d95a docs: multiple join commands 2023-06-01 13:01:15 +02:00
CreeperMaxCZ d205bd7923 feat: multiple join commands 2023-06-01 12:09:50 +02:00
CreeperMaxCZ f5503b8fc0 feat: leave command with limit 2022-11-16 22:55:12 +01:00
CreeperMaxCZ 6473d53fd7 feat: command: leave - disconnect bots 2022-11-16 22:40:20 +01:00
CreeperMaxCZ 07445c06b4 feat: command: list bots 2022-11-16 21:50:46 +01:00
CreeperMaxCZ d441647ff8 fix: useless prompt rewriting 2022-11-16 19:16:14 +01:00
CreeperMaxCZ c3830fc86b feat: commands: select bots to control 2022-11-16 19:08:25 +01:00
CreeperMaxCZ d6f0adfd57 fix: added argument placeholders in option list in readme 2022-10-08 23:09:06 +02:00
CreeperMaxCZ 6092a5f8f9 feat: auto respawn with delay 2022-10-08 23:03:33 +02:00
CreeperMaxCZ 5346989a92 feat: online mode account support 2022-10-08 22:18:18 +02:00
CreeperMaxCZ 4cd46e8cac Update issue templates 2022-08-29 14:23:52 +02:00
CreeperMaxCZ 8db9603313 Update issue templates 2022-08-29 14:22:40 +02:00
CreeperMaxCZ 48bef04212 Update README.md 2022-08-25 18:46:42 +02:00
CreeperMaxCZ af4e915421 Merge pull request #44 from gooday2die/main
Requesting PR for 1.19.1 (and 1.19.2)
2022-08-16 14:03:14 +02:00
Kim, Isu 191373c430 Update README.md
- doc: set version information to 1.19.1
2022-08-16 18:20:52 +09:00
Kim, Isu 2c2e413d72 Clean up code a bit
- refactor: clean up code a bit
2022-08-16 18:19:15 +09:00
Kim, Isu 9d8800a671 Everything working
- fix: bot command issuing output
- refactor: clean code a bit
- feature: bot can now chat, command and receive chats and receive outputs from command as well.
2022-08-16 18:00:39 +09:00
Kim, Isu 67354e0917 Now bots can send chats
- feature: bots can send chats
- fix: bug with receiving chats that result comes from commands
2022-08-16 17:32:53 +09:00
Kim, Isu 73c51871c9 Fix bug with chat
- fix: bug with some commands (like `/say`) not sending message packets through ClientboundPlayerChatPacket.
- feature: add new getFullText for generating "Sender : Message" format using string, instead of TextComponent for message.
2022-08-16 17:23:14 +09:00
Kim, Isu 5b520dc774 Work on chat feature
- feature: Now supports 1.19.1 chat formatting with sender's name and message with colors
- feature: add getFullText for generating text message with Sender and Message information all together. (Since 1.19.1 sends those two information differently, this method will merge those two information and generate a single string)
- refactor: getSignedContent was removed. (Do not know why but it did from MCProtocollib. Thus need a workaround for receiving messages)
2022-08-16 17:03:26 +09:00
Kim, Isu 4475f6ce7a Now bots can receive message
- feature: Bots can receive message from server chat.
- chore: remove redundant depdendency
2022-08-16 15:48:48 +09:00
Isu Kim 704af34048 Work on 1.19.1 version
- chore: add dependency 1.19.1-SNAPSHOT for 1.19.1 protocol
- feature: work on 1.19.1 sending and receiving chat packets
2022-08-16 12:02:46 +09:00
CreeperMaxCZ f0a2ce1c56 update example command 2022-08-08 22:20:22 +02:00
CreeperMaxCZ 65ce3acab3 get disconnect reason from string using regex 2022-08-05 14:09:33 +02:00
CreeperMaxCZ a5f6d008fa fix: nested chat message parsing 2022-08-05 13:41:06 +02:00
CreeperMaxCZ f3e6ec2d99 fix: handle sending commands too 2022-08-05 13:06:42 +02:00
CreeperMaxCZ d8219a96bf update lang file to mc 1.19 2022-08-05 12:21:26 +02:00
CreeperMaxCZ e8472a51be update included gradle scripts 2022-08-05 12:19:36 +02:00
CreeperMaxCZ b730759721 fix: handle error with server status info 2022-08-05 12:17:17 +02:00
CreeperMaxCZ 97efa9ddb6 Merge pull request #41 from gooday2die/main
Update to 1.19
2022-08-05 11:48:56 +02:00
Kim, Isu c0f446dd29 Update README.md
- doc: change version 1.18 to 1.19 😄
2022-08-05 18:36:25 +09:00
Kim, Isu 0a4e986764 Bots can now get message
- feature: Bots can now get message from server using ClientboundPlayerChatPacket.getSignedContent()
2022-08-05 18:11:29 +09:00
Kim, Isu 6523326fd3 Support for 1.19
- feature: Bots can now connect 1.19 using MCProtocolLib
- chore: change build.gradle in order to use 1.19 features.
2022-08-05 18:06:08 +09:00
CreeperMaxCZ f20c6121d7 added gradle wrapper 2022-07-31 18:59:14 +02:00
CreeperMaxCZ c4660683b9 fix: nicks count check and option rename 2022-07-31 18:00:44 +02:00
CreeperMaxCZ 22c05d18db feat: option to simulate gravity 2022-07-31 17:53:41 +02:00
CreeperMaxCZ 32d760e9eb feat: print server info on start 2022-07-31 15:18:25 +02:00
CreeperMaxCZ 204ff4b850 feat: support for getting proxies from url 2022-07-30 21:35:13 +02:00
CreeperMaxCZ 655bc70eaa feat: option to use nicks from file 2022-07-30 20:46:29 +02:00
CreeperMaxCZ 67de645f90 update version to 1.2.1 2022-05-12 21:53:53 +02:00
CreeperMaxCZ 997c8b8294 update readme with 1.18.2 support 2022-05-12 21:51:59 +02:00
CreeperMaxCZ f64b9d60d5 update library to 1.18.2 2022-05-12 21:51:07 +02:00
CreeperMaxCZ 3498663c01 Merge pull request #28 from sans404-dev/main
Fix build bug - library rename, exclude duplicates option
2022-05-07 15:07:12 +02:00
Sans404 a073d75081 Fix build bug 2022-05-05 00:14:37 +03:00
CreeperMaxCZ 934cc22306 socks proxy support, version bump 2022-03-20 15:38:34 +01:00
CreeperMaxCZ 1c15d0358f rewrite for 1.18, updated libraries 2021-12-23 21:45:43 +01:00
CreeperMaxCZ 1f940aea14 docs: note about 1.16.5 support 2021-04-06 22:43:19 +02:00
CreeperMaxCZ 735446a85e docs: better description 2021-03-14 21:51:38 +01:00
CreeperMaxCZ 4ba567deab fix: error when none dns records found 2021-03-08 21:28:14 +01:00
CreeperMaxCZ eaaf092ae5 style: removed useless comments 2021-02-25 19:22:04 +01:00
CreeperMaxCZ 8e89e2accb style: removed useless comment 2021-02-25 19:21:20 +01:00
CreeperMaxCZ 552456b6a5 Update README.md 2021-02-25 18:15:06 +01:00
CreeperMaxCZ 8ecfcadb4d Update README.md 2021-02-25 13:12:43 +01:00
CreeperMaxCZ c952580661 Update README.md 2021-02-25 13:09:27 +01:00
17 changed files with 6885 additions and 4384 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
---
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
@@ -0,0 +1,20 @@
---
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.
+4
View File
@@ -0,0 +1,4 @@
.gradle
.idea
build
gradle
+40 -13
View File
@@ -1,31 +1,58 @@
# Minecraft bot stress tester # Minecraft bot stress tester
A simple app written in Java used for stress testing Minecraft servers. 🤖 A simple open source app written in Java used for stress testing Minecraft servers with bots (fake players).
It can be also used to test plugins or minigames. 💥 It can be also used to test plugins or minigames.
The MC version of the bots is 1.16.4. ✔️ The MC version of the bots is 1.21.7 (supports server 1.21.8)
For older MC versions please look in the [releases](https://github.com/crpmax/mc-bots/releases " releases").
## Features ## 🆒 Features
- ✅ Connect as many bots as you want - ✅ Connect as many bots as you want
- ✅ Use SOCKS4 or SOCKS5 proxies from file or URL
- ✅ Receive colored or noncolored chat - ✅ Receive colored or noncolored chat
- ✅ Set connection delay - ✅ Set connection delay
- ✅ Set message or command on join - ✅ Set messages or commands on join
- ✅ Generate random or real looking nicknames - ✅ Generate random or real looking nicknames or load from file
- ✅ Online (premium) account support with login using Microsoft
- ✅ Control all or selected bots
## Usage ## 📖 Usage
Minimal Java version: 8 Minimal Java version: 17
Use of pre-compiled jar from [releases](https://github.com/crpmax/mc-bots/releases " releases"): Use of pre-compiled jar from [releases](https://github.com/crpmax/mc-bots/releases " releases"):
`java -jar mc-bots.jar -s <server address> [arguments]` `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. When running, you can write a chat message to the terminal to send it by all bots.
#### Options ## 🧪 Example
`java -jar mc-bots-1.2.17.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"/>
<img src="https://imgur.com/CvJq1Io.gif" title="Sending chat message by bots" width="350px"/>
## ⚡ Options
`-c <count>` The count of bots to connect, default is 1 `-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 `-d <min> <max>` Set the minimum and maximum connection delay range in ms, default is 4000-5000
`-j <message>` The message or command to send on join, does not work with `-m` or `-x` option `-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_` `-p <prefix>` Custom bot nickname prefix eg. `BOT_`
`-r` Generate real looking nicknames instead of random ones `-r` Generate real looking nicknames instead of random ones
`-n` Do not use color in terminal - useful when the terminal does not support it `-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 `-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 `-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
## DISCLAIMER
**This app is made for educational and testing purposes only ## Commands
I am not responsible for any abuse** 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.**
+17 -6
View File
@@ -3,24 +3,35 @@ plugins {
} }
group 'me.creepermaxcz.mc-bots' group 'me.creepermaxcz.mc-bots'
version '1.0.0' version '1.2.17'
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-releases/' }
} }
dependencies { dependencies {
implementation 'com.github.Steveice10:MCProtocolLib:1.16.4-1' implementation 'org.geysermc.mcprotocollib:protocol:1.21.7-SNAPSHOT'
implementation 'commons-cli:commons-cli:1.4' implementation 'net.kyori:adventure-text-serializer-gson:4.24.0'
implementation 'com.diogonunes:JColor:5.0.1' implementation 'commons-cli:commons-cli:1.9.0'
implementation 'dnsjava:dnsjava:3.3.1' implementation 'com.diogonunes:JColor:5.5.1'
implementation 'org.slf4j:slf4j-nop:1.7.30' implementation 'dnsjava:dnsjava:3.5.3'
implementation 'org.slf4j:slf4j-nop:2.0.17'
implementation 'org.jline:jline:3.30.4'
}
java {
toolchain {
languageVersion = JavaLanguageVersion.of(17)
}
} }
jar { jar {
manifest { manifest {
attributes 'Main-Class': 'me.creepermaxcz.mcbots.Main' attributes 'Main-Class': 'me.creepermaxcz.mcbots.Main'
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) }
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.0.0-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Regular → Executable
+159 -110
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env sh #!/bin/sh
# #
# Copyright 2015 the original author or authors. # Copyright © 2015-2021 the original authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -17,67 +17,101 @@
# #
############################################################################## ##############################################################################
## #
## Gradle start up script for UN*X # Gradle start up script for POSIX generated by Gradle.
## #
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (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
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
############################################################################## ##############################################################################
# Attempt to set APP_HOME # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
PRG="$0" app_path=$0
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do # Need this for daisy-chained symlinks.
ls=`ls -ld "$PRG"` while
link=`expr "$ls" : '.*-> \(.*\)$'` APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
if expr "$link" : '/.*' > /dev/null; then [ -h "$app_path" ]
PRG="$link" do
else ls=$( ls -ld "$app_path" )
PRG=`dirname "$PRG"`"/$link" link=${ls#*' -> '}
fi case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle" APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"` APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 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
warn () { warn () {
echo "$*" echo "$*"
} } >&2
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} } >&2
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "`uname`" in case "$( uname )" in #(
CYGWIN* ) CYGWIN* ) cygwin=true ;; #(
cygwin=true Darwin* ) darwin=true ;; #(
;; MSYS* | MINGW* ) msys=true ;; #(
Darwin* ) NONSTOP* ) nonstop=true ;;
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
@@ -87,9 +121,9 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java" JAVACMD=$JAVA_HOME/jre/sh/java
else else
JAVACMD="$JAVA_HOME/bin/java" JAVACMD=$JAVA_HOME/bin/java
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -98,7 +132,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." 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. which java >/dev/null 2>&1 || 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
@@ -106,80 +140,95 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
MAX_FD_LIMIT=`ulimit -H -n` case $MAX_FD in #(
if [ $? -eq 0 ] ; then max*)
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD=$( ulimit -H -n ) ||
MAX_FD="$MAX_FD_LIMIT" warn "Could not query maximum file descriptor limit"
fi esac
ulimit -n $MAX_FD case $MAX_FD in #(
if [ $? -ne 0 ] ; then '' | soft) :;; #(
warn "Could not set maximum file descriptor limit: $MAX_FD" *)
fi ulimit -n "$MAX_FD" ||
else warn "Could not set maximum file descriptor limit to $MAX_FD"
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac esac
fi fi
# Escape application args # Collect all arguments for the java command, stacking in reverse order:
save () { # * args from the command line
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done # * the main class name
echo " " # * -classpath
} # * -D...appname settings
APP_ARGS=`save "$@"` # * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# Collect all arguments for the java command, following the shell quoting and substitution rules # For Cygwin or MSYS, switch paths to Windows format before running java
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@" exec "$JAVACMD" "$@"
Vendored
+3 -18
View File
@@ -40,7 +40,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 init if "%ERRORLEVEL%" == "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.
@@ -54,7 +54,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init if exist "%JAVA_EXE%" goto execute
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -64,21 +64,6 @@ echo location of your Java installation.
goto fail goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
@@ -86,7 +71,7 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
+161 -31
View File
@@ -1,75 +1,175 @@
package me.creepermaxcz.mcbots; package me.creepermaxcz.mcbots;
import com.github.steveice10.mc.protocol.MinecraftProtocol; import org.geysermc.mcprotocollib.auth.GameProfile;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket; import org.geysermc.mcprotocollib.auth.SessionService;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerJoinGamePacket; import org.geysermc.mcprotocollib.network.ClientSession;
import com.github.steveice10.packetlib.Client; import org.geysermc.mcprotocollib.network.ProxyInfo;
import com.github.steveice10.packetlib.ProxyInfo; import org.geysermc.mcprotocollib.network.Session;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent; import org.geysermc.mcprotocollib.network.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.PacketReceivedEvent; import org.geysermc.mcprotocollib.network.event.session.SessionAdapter;
import com.github.steveice10.packetlib.event.session.SessionAdapter; import org.geysermc.mcprotocollib.network.factory.ClientNetworkSessionFactory;
import com.github.steveice10.packetlib.tcp.TcpSessionFactory; import org.geysermc.mcprotocollib.network.packet.Packet;
import org.geysermc.mcprotocollib.network.session.ClientNetworkSession;
import org.geysermc.mcprotocollib.protocol.MinecraftConstants;
import org.geysermc.mcprotocollib.protocol.MinecraftProtocol;
import org.geysermc.mcprotocollib.protocol.data.UnexpectedEncryptionException;
import org.geysermc.mcprotocollib.protocol.data.game.ClientCommand;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundLoginPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerCombatKillPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.entity.player.ClientboundPlayerPositionPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundChatCommandPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundChatPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.ServerboundClientCommandPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.level.ServerboundAcceptTeleportationPacket;
import org.geysermc.mcprotocollib.protocol.packet.ingame.serverbound.player.*;
import java.net.InetSocketAddress; 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 { public class Bot extends Thread {
MinecraftProtocol protocol = null;
private String nickname; private String nickname;
private ProxyInfo proxy; private ProxyInfo proxy;
private InetSocketAddress address; private InetSocketAddress address;
private Client client; private ClientSession client;
private boolean hasMainListener; private boolean hasMainListener;
public Bot(String nickname, InetSocketAddress address, ProxyInfo proxy) { private double lastX, lastY, lastZ = -1;
this.nickname = nickname;
private boolean connected;
private boolean manualDisconnecting = false;
public Bot(MinecraftProtocol protocol, InetSocketAddress address, ProxyInfo proxy) {
this.nickname = protocol.getProfile().getName();
this.address = address; this.address = address;
this.proxy = proxy; this.proxy = proxy;
Log.info("Creating bot", nickname); Log.info("Creating bot", nickname);
protocol = new MinecraftProtocol(nickname);
client = new Client(address.getHostString(), address.getPort(), protocol, new TcpSessionFactory(proxy)); client = ClientNetworkSessionFactory.factory()
.setAddress(address.getHostString(), address.getPort())
.setProtocol(protocol)
.setProxy(proxy)
.create();
SessionService sessionService = new SessionService();
client.setFlag(MinecraftConstants.SESSION_SERVICE_KEY, sessionService);
} }
@Override @Override
public void run() { public void run() {
if (!Main.isMinimal()) { if (!Main.isMinimal()) {
client.getSession().addListener(new SessionAdapter() { client.addListener(new SessionAdapter() {
@Override @Override
public void packetReceived(PacketReceivedEvent event) { public void packetReceived(Session session, Packet packet) {
if (event.getPacket() instanceof ServerJoinGamePacket) { if (packet instanceof ClientboundLoginPacket) {
connected = true;
Log.info(nickname + " connected"); Log.info(nickname + " connected");
if (Main.joinMessage != null) {
sendChat(Main.joinMessage); 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.getPosition().getX();
lastY = p.getPosition().getY();
lastZ = p.getPosition().getZ();
client.send(new ServerboundAcceptTeleportationPacket(p.getId()));
}
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 @Override
public void disconnected(DisconnectedEvent event) { public void disconnected(DisconnectedEvent event) {
Log.info(); connected = false;
Log.info(nickname + " disconnected"); Log.info(nickname + " disconnected");
Log.info(event.getReason());
if(event.getCause() != null) { // Do not write disconnect reason if disconnected by command
event.getCause().printStackTrace(); 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();
} }
Log.info();
Main.removeBot(Bot.this); Main.removeBot(Bot.this);
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();
} }
}); });
} }
client.getSession().connect(); client.connect();
//client.getSession().send(new ClientPlayerPositionPacket(true, 0, 0, 0));
} }
public void sendChat(String text) { public void sendChat(String text) {
client.getSession().send(new ClientChatPacket(text)); // Send command
} if (text.startsWith("/")) {
client.send(new ServerboundChatCommandPacket(
text.substring(1)
));
} 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(),
0
));
}
}
public String getNickname() { public String getNickname() {
return nickname; return nickname;
@@ -78,10 +178,40 @@ public class Bot extends Thread {
public void registerMainListener() { public void registerMainListener() {
hasMainListener = true; hasMainListener = true;
if (Main.isMinimal()) return; if (Main.isMinimal()) return;
client.getSession().addListener(new MainListener(nickname)); client.addListener(new MainListener(nickname));
} }
public boolean hasMainListener() { public boolean hasMainListener() {
return 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, false, x, y, z));
}
public boolean isConnected() {
return connected;
}
public void disconnect()
{
manualDisconnecting = true;
client.disconnect("Leaving");
}
} }
@@ -9,6 +9,7 @@ public class Log {
public static void log(String in) { public static void log(String in) {
System.out.println("\r[" + formatter.format(new Date()) + "] " + in); System.out.println("\r[" + formatter.format(new Date()) + "] " + in);
System.out.print(Main.getPrompt() + "> ");
} }
public static void error(String in) { public static void error(String in) {
@@ -27,6 +28,13 @@ public class Log {
log("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) { public static void chat(String ...in) {
log("CHAT | " + String.join(" ", in)); log("CHAT | " + String.join(" ", in));
} }
+389 -23
View File
@@ -1,16 +1,30 @@
package me.creepermaxcz.mcbots; package me.creepermaxcz.mcbots;
import net.lenni0451.commons.httpclient.HttpClient;
import net.raphimc.minecraftauth.MinecraftAuth;
import net.raphimc.minecraftauth.step.java.session.StepFullJavaSession;
import net.raphimc.minecraftauth.step.msa.StepMsaDeviceCode;
import org.geysermc.mcprotocollib.auth.GameProfile;
import org.geysermc.mcprotocollib.network.ProxyInfo;
import org.geysermc.mcprotocollib.protocol.MinecraftProtocol;
import org.geysermc.mcprotocollib.protocol.data.status.ServerStatusInfo;
import org.apache.commons.cli.*; 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.Lookup;
import org.xbill.DNS.Record; import org.xbill.DNS.Record;
import org.xbill.DNS.SRVRecord; import org.xbill.DNS.SRVRecord;
import org.xbill.DNS.Type; import org.xbill.DNS.Type;
import java.net.InetAddress; import java.io.*;
import java.net.InetSocketAddress; import java.net.*;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.ArrayList; import java.util.*;
import java.util.Scanner; import java.util.stream.Collectors;
public class Main { public class Main {
@@ -24,7 +38,22 @@ public class Main {
private static int delayMax = 5000; private static int delayMax = 5000;
private static boolean minimal = false; private static boolean minimal = false;
private static boolean mostMinimal = false; private static boolean mostMinimal = false;
public static String joinMessage; 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 { public static void main(String[] args) throws Exception {
@@ -45,7 +74,18 @@ public class Main {
options.addOption("p", "prefix", true, "bot nick prefix"); options.addOption("p", "prefix", true, "bot nick prefix");
options.addOption("m", "minimal", false, "minimal run without any listeners"); 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("x", "most-minimal", false, "minimal run without any control, just connect the bots");
options.addOption("j", "join-msg", true, "join message / command"); 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(); CommandLineParser parser = new DefaultParser();
CommandLine cmd = null; CommandLine cmd = null;
@@ -58,6 +98,78 @@ public class Main {
System.exit(1); 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("Invalid 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")); botCount = Integer.parseInt(cmd.getOptionValue('c', "1"));
@@ -83,7 +195,14 @@ public class Main {
String address = cmd.getOptionValue('s'); String address = cmd.getOptionValue('s');
coloredChat = !cmd.hasOption('n'); coloredChat = !cmd.hasOption('n');
joinMessage = cmd.getOptionValue('j'); 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; int port = 25565;
if (address.contains(":")) { if (address.contains(":")) {
@@ -92,17 +211,36 @@ public class Main {
port = Integer.parseInt(split[1]); port = Integer.parseInt(split[1]);
} else { } else {
Record[] records = new Lookup("_minecraft._tcp." + address, Type.SRV).run(); Record[] records = new Lookup("_minecraft._tcp." + address, Type.SRV).run();
for (Record record : records) { if (records != null) {
SRVRecord srv = (SRVRecord) record; for (Record record : records) {
address = srv.getTarget().toString().replaceFirst("\\.$", ""); SRVRecord srv = (SRVRecord) record;
port = srv.getPort(); address = srv.getTarget().toString().replaceFirst("\\.$", "");
port = srv.getPort();
}
} }
} }
boolean realNicknames = cmd.hasOption('r'); boolean realNicknames = cmd.hasOption('r');
NickGenerator nickGen = new NickGenerator(); NickGenerator nickGen = new NickGenerator();
nickGen.setReal(realNicknames);
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', "")); nickGen.setPrefix(cmd.getOptionValue('p', ""));
InetSocketAddress inetAddr = new InetSocketAddress( InetSocketAddress inetAddr = new InetSocketAddress(
@@ -110,18 +248,94 @@ public class Main {
port port
); );
//print info
Log.info("IP:", inetAddr.getHostString()); Log.info("IP:", inetAddr.getHostString());
Log.info("Port: " + inetAddr.getPort()); Log.info("Port: " + inetAddr.getPort());
Log.info("Count: " + botCount); 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.");
}
MinecraftProtocol protocol;
if (cmd.hasOption("o")) {
Log.warn("Online mode enabled. The bot count will be set to 1.");
botCount = 1;
HttpClient httpClient = MinecraftAuth.createHttpClient();
StepFullJavaSession.FullJavaSession javaSession =
MinecraftAuth.JAVA_DEVICE_CODE_LOGIN.getFromInput(
httpClient, new StepMsaDeviceCode.MsaDeviceCodeCallback(
msaDeviceCode -> {
Log.info("Authorize your Microsoft account on " + msaDeviceCode.getDirectVerificationUri());
Log.info("Waiting for authorization.");
}));
Log.info("Logged in with username: " + javaSession.getMcProfile().getName());
GameProfile gameProfile = new GameProfile(javaSession.getMcProfile().getId(), javaSession.getMcProfile().getName());
protocol = new MinecraftProtocol(gameProfile, javaSession.getMcProfile().getMcToken().getAccessToken());
} else {
protocol = null;
}
new Thread(() -> { new Thread(() -> {
for (int i = 0; i < botCount; i++) { for (int i = 0; i < botCount; i++) {
try { try {
Bot bot = new Bot( ProxyInfo proxyInfo = null;
nickGen.nextNick(), if (useProxies) {
inetAddr, InetSocketAddress proxySocket = proxies.get(proxyIndex);
null
); 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 (protocol != null) {
bot = new Bot(
protocol,
inetAddr,
proxyInfo
);
} else {
bot = new Bot(
new MinecraftProtocol(nickGen.nextNick()),
inetAddr,
proxyInfo
);
}
bot.start(); bot.start();
if (!mostMinimal) bots.add(bot); if (!mostMinimal) bots.add(bot);
@@ -146,16 +360,141 @@ public class Main {
} }
}).start(); }).start();
//gravity timer
if (cmd.hasOption("g")) {
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
bots.forEach(Bot::fallDown);
}
}, 1000L, 500L);
}
Scanner scanner = new Scanner(System.in); Terminal terminal = TerminalBuilder.builder().build();
LineReader lineReader = LineReaderBuilder.builder()
.terminal(terminal)
.parser(new org.jline.reader.impl.DefaultParser())
.build();
while (scanner.hasNextLine()) { prompt = "ALL";
String line = scanner.nextLine();
if (line.isEmpty()) continue;
bots.forEach(bot -> bot.sendChat(line)); 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); Thread.sleep(50);
//System.out.print("\r" +prompt + "> ");
} }
} }
@@ -165,6 +504,7 @@ public class Main {
public static synchronized void removeBot(Bot bot) { public static synchronized void removeBot(Bot bot) {
bots.remove(bot); bots.remove(bot);
controlledBots.remove(bot);
if (bot.hasMainListener()) { if (bot.hasMainListener()) {
Log.info("Bot with MainListener removed"); Log.info("Bot with MainListener removed");
isMainListenerMissing = true; isMainListenerMissing = true;
@@ -191,4 +531,30 @@ public class Main {
public static boolean isMinimal() { public static boolean isMinimal() {
return minimal; 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,10 +1,13 @@
package me.creepermaxcz.mcbots; package me.creepermaxcz.mcbots;
import com.github.steveice10.mc.protocol.data.message.Message; import org.geysermc.mcprotocollib.network.Session;
import com.github.steveice10.mc.protocol.data.message.TextMessage; import org.geysermc.mcprotocollib.network.event.session.*;
import com.github.steveice10.mc.protocol.data.message.TranslationMessage; import org.geysermc.mcprotocollib.network.packet.Packet;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket; import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundPlayerChatPacket;
import com.github.steveice10.packetlib.event.session.*; import org.geysermc.mcprotocollib.protocol.packet.ingame.clientbound.ClientboundSystemChatPacket;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
public class MainListener implements SessionListener { public class MainListener implements SessionListener {
@@ -13,19 +16,41 @@ public class MainListener implements SessionListener {
} }
@Override @Override
public void packetReceived(PacketReceivedEvent event) { public void packetReceived(Session session, Packet packet) {
if(event.getPacket() instanceof ServerChatPacket) { // From 1.19.1 (as well as 1.19), the class ClientboundChatPacket was removed.
Message message = event.<ServerChatPacket>getPacket().getMessage(); // Instead, they use ClientboundPlayerChatPacket and ClientboundSystemChatPacket for taking care of chat packets.
if (message instanceof TextMessage) { Component message = null;
if (Main.coloredChat) { Component sender;
Log.chat(Utils.getFormattedFullText(message)); boolean chatPrintedOut = false;
} else {
Log.chat(Utils.getFullText((TextMessage) message));
}
} else if (message instanceof TranslationMessage) { if (packet instanceof ClientboundPlayerChatPacket) {
Log.chat("[T]", Utils.translate((TranslationMessage) message)); 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));
} }
} }
@@ -35,7 +60,7 @@ public class MainListener implements SessionListener {
} }
@Override @Override
public void packetSent(PacketSentEvent event) { public void packetSent(Session session, Packet packet) {
} }
@@ -1,11 +1,12 @@
package me.creepermaxcz.mcbots; package me.creepermaxcz.mcbots;
import java.io.BufferedReader; import java.io.*;
import java.io.InputStream; import java.net.InetSocketAddress;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.SecureRandom; import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class NickGenerator { public class NickGenerator {
@@ -25,6 +26,34 @@ public class NickGenerator {
private String prefix = ""; 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() { private void loadLines() {
try (InputStream resource = getClass().getResourceAsStream("/files/nicks.txt")) { try (InputStream resource = getClass().getResourceAsStream("/files/nicks.txt")) {
lines = new BufferedReader( lines = new BufferedReader(
@@ -0,0 +1,72 @@
package me.creepermaxcz.mcbots;
import org.geysermc.mcprotocollib.network.ClientSession;
import org.geysermc.mcprotocollib.network.Session;
import org.geysermc.mcprotocollib.network.event.session.DisconnectedEvent;
import org.geysermc.mcprotocollib.network.event.session.SessionAdapter;
import org.geysermc.mcprotocollib.network.factory.ClientNetworkSessionFactory;
import org.geysermc.mcprotocollib.protocol.MinecraftConstants;
import org.geysermc.mcprotocollib.protocol.MinecraftProtocol;
import org.geysermc.mcprotocollib.protocol.data.status.ServerStatusInfo;
import org.geysermc.mcprotocollib.protocol.data.status.handler.ServerInfoHandler;
import org.geysermc.mcprotocollib.protocol.data.status.handler.ServerPingTimeHandler;
import java.net.InetSocketAddress;
public class ServerInfo {
private final ClientSession client;
private ServerStatusInfo serverStatusInfo;
private long ping;
private boolean done;
public ServerInfo(InetSocketAddress address) {
MinecraftProtocol protocol = new MinecraftProtocol();
client = ClientNetworkSessionFactory.factory()
.setAddress(address.getHostString(), address.getPort())
.setProtocol(protocol)
.create();
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;
}
}
+128 -117
View File
@@ -1,20 +1,24 @@
package me.creepermaxcz.mcbots; package me.creepermaxcz.mcbots;
import com.diogonunes.jcolor.Attribute; import com.diogonunes.jcolor.Attribute;
import com.github.steveice10.mc.protocol.data.message.Message;
import com.github.steveice10.mc.protocol.data.message.TextMessage;
import com.github.steveice10.mc.protocol.data.message.TranslationMessage;
import com.github.steveice10.mc.protocol.data.message.style.ChatColor;
import com.github.steveice10.mc.protocol.data.message.style.ChatFormat;
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 net.kyori.adventure.text.Component;
import net.kyori.adventure.text.TextComponent;
import net.kyori.adventure.text.TranslatableComponent;
import net.kyori.adventure.text.TranslationArgument;
import net.kyori.adventure.text.format.Style;
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.format.TextDecoration;
import org.jetbrains.annotations.Nullable;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Map;
import static com.diogonunes.jcolor.Ansi.colorize; import static com.diogonunes.jcolor.Ansi.colorize;
@@ -22,142 +26,149 @@ public class Utils {
private static JsonObject lang; private static JsonObject lang;
public static String getFullText(TextMessage message) { public static String getFullText(TextComponent message, boolean colored) {
if (message.getExtra().size() > 0) { if (message.children().size() > 0) {
StringBuilder text = new StringBuilder(); StringBuilder text = new StringBuilder();
for (Message extra : message.getExtra()) { text.append(parseColor(message, colored));
text.append(getFullText((TextMessage) extra)); 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(); return text.toString();
} else { } else {
return ((TextMessage)message).getText(); return parseColor(message, colored);
} }
} }
public static String getFormattedFullText(Message message) { /**
if (message.getExtra().size() > 0) { * A static function that gets full text from text components.
StringBuilder text = new StringBuilder(); * From 1.19.1 the protocol does not include sender's information in the message.
for (Message extra : message.getExtra()) { * Thus, we need to merge two TextComponent (sender and message) and generate a text that consists of sent message.
text.append(getFormattedFullText(extra)); * 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.
} }
return text.toString();
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 { } else {
if (sender == null)
String out = ((TextMessage) message).getText(); return message.content();
else
List<Attribute> formats = new ArrayList<>(getFormat(message.getStyle().getFormats())); return sender.content() + " : " + message.content();
formats.add(getColor(message.getStyle().getColor()));
out = colorize(out, formats.toArray(new Attribute[0]));
return out;
} }
} }
public static Attribute getColor(String name) { private static String parseColor(TextComponent message, boolean colored) {
switch (name) { String out = message.content();
case ChatColor.RED: if (colored) {
return Attribute.BRIGHT_RED_TEXT(); if (message.style().color() != null) {
case ChatColor.DARK_RED: List<Attribute> formats = new ArrayList<>(getFormats(message.style().decorations()));
return Attribute.RED_TEXT(); TextColor color = message.style().color();
formats.add(Attribute.TEXT_COLOR(color.red(), color.green(), color.blue()));
case ChatColor.BLUE: out = colorize(out, formats.toArray(new Attribute[0]));
return Attribute.BRIGHT_BLUE_TEXT(); }
case ChatColor.DARK_BLUE:
return Attribute.BLUE_TEXT();
case ChatColor.WHITE:
return Attribute.BRIGHT_WHITE_TEXT();
case ChatColor.BLACK:
return Attribute.BLACK_TEXT();
case ChatColor.GRAY:
return Attribute.WHITE_TEXT();
case ChatColor.DARK_GRAY:
return Attribute.BRIGHT_BLACK_TEXT();
case ChatColor.AQUA:
return Attribute.BRIGHT_CYAN_TEXT();
case ChatColor.DARK_AQUA:
return Attribute.CYAN_TEXT();
case ChatColor.YELLOW:
return Attribute.BRIGHT_YELLOW_TEXT();
case ChatColor.GOLD:
return Attribute.YELLOW_TEXT();
case ChatColor.GREEN:
return Attribute.BRIGHT_GREEN_TEXT();
case ChatColor.DARK_GREEN:
return Attribute.GREEN_TEXT();
case ChatColor.LIGHT_PURPLE:
return Attribute.BRIGHT_MAGENTA_TEXT();
case ChatColor.DARK_PURPLE:
return Attribute.MAGENTA_TEXT();
} }
return Attribute.NONE(); return out;
} }
public static List<Attribute> getFormat(List<ChatFormat> formats) { 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<>(); List<Attribute> list = new ArrayList<>();
formats.forEach(format -> { decorations.forEach((format, state) -> {
switch (format) { if (state.equals(TextDecoration.State.TRUE)) {
case BOLD: switch (format) {
list.add(Attribute.BOLD()); case ITALIC:
break; list.add(Attribute.ITALIC());
case ITALIC: break;
list.add(Attribute.ITALIC()); case UNDERLINED:
break; list.add(Attribute.UNDERLINE());
case UNDERLINED: break;
list.add(Attribute.UNDERLINE()); case STRIKETHROUGH:
break; list.add(Attribute.STRIKETHROUGH());
case STRIKETHROUGH: break;
list.add(Attribute.STRIKETHROUGH()); }
break;
} }
}); });
return list; return list;
} }
public static String translate(TranslationMessage message) { public static String translate(TranslatableComponent message) {
if (lang == null) { try {
try { if (lang == null) {
InputStream resource = Utils.class.getClass().getResourceAsStream("/files/lang.json"); try {
lang = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject(); InputStream resource = Utils.class.getResourceAsStream("/files/lang.json");
} catch (Exception e) { if (resource == null) {
Log.error(e); throw new Exception("Failed to load lang resource.");
} }
} lang = new JsonParser().parse(new InputStreamReader(resource)).getAsJsonObject();
Log.info(message.toString()); } catch (Exception e) {
Log.crit(e);
String key = message.getKey();
String base = key;
JsonElement value = lang.get(key);
if (value != null) {
base = value.getAsString();
}
ArrayList<String> placeholders = new ArrayList<>();
if (message.getWith().size() > 0) {
for (Message with : message.getWith()) {
if (with instanceof TranslationMessage) {
placeholders.add(translate((TranslationMessage) with));
}
else if (with instanceof TextMessage) {
placeholders.add(((TextMessage) with).getText());
} }
} }
Log.info(Arrays.toString(placeholders.toArray())); //Log.info(message.toString());
return String.format(base, placeholders.toArray());
} else { String key = message.key();
return base; String base = key;
JsonElement value = lang.get(key);
if (value != null) {
base = value.getAsString();
}
ArrayList<String> placeholders = new ArrayList<>();
if (message.arguments().size() > 0) {
for (TranslationArgument arg : message.arguments()) {
Component component = arg.asComponent();
if (component instanceof TranslatableComponent) {
placeholders.add(translate((TranslatableComponent) component));
} else if (arg instanceof TextComponent) {
placeholders.add(getFullText((TextComponent) component, false));
}
}
//Log.info(Arrays.toString(placeholders.toArray()));
try {
return String.format(base, placeholders.toArray());
} catch (Exception e) {
Log.error("Error formatting '"+base+"' with placeholders " + Arrays.toString(placeholders.toArray()));
}
} else {
return base;
}
} catch (Exception e) {
Log.error(e);
} }
return "";
//Log.info(Arrays.toString(message.getWith().toArray()));
//msg = String.format(msg, );
//return msg;
} }
} }
File diff suppressed because it is too large. Load diff