Files
src
build.gradle
main.py
Code
5 614
src/main/java/com/kodari/pythonbot/PythonDiscordBotPlugin.java
package com.kodari.pythonbot;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public final class PythonDiscordBotPlugin extends JavaPlugin {
private static final Pattern ENVIRONMENT_KEY = Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
private static final DateTimeFormatter LOG_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final Object processLock = new Object();
private volatile Process activeProcess;
private volatile boolean shuttingDown;
@Override
public void onEnable() {
saveDefaultConfig();
Path pluginDirectory = getDataFolder().toPath().toAbsolutePath().normalize();
try {
Files.createDirectories(pluginDirectory.resolve("cogs"));
Files.createDirectories(pluginDirectory.resolve("logs"));
} catch (IOException exception) {
getLogger().severe("Could not create the bot folders: " + exception.getMessage());
getServer().getPluginManager().disablePlugin(this);
return;
}
String interpreter = getConfig().getString("python-command", "python3");
String scriptSetting = getConfig().getString("script", "main.py");
if (interpreter == null || interpreter.isBlank() || scriptSetting == null || scriptSetting.isBlank()) {
getLogger().severe("Set both python-command and script in config.yml.");
getServer().getPluginManager().disablePlugin(this);
return;
}
Path script = pluginDirectory.resolve(scriptSetting).normalize();
if (!script.startsWith(pluginDirectory)) {
getLogger().severe("The configured script must be inside this plugin's folder.");
getServer().getPluginManager().disablePlugin(this);
return;
}
if (!Files.isRegularFile(script)) {
getLogger().warning("Python bot was not started: place " + script.getFileName()
+ " in " + pluginDirectory + " and restart the server.");
return;
}
shuttingDown = false;
Thread startupThread = new Thread(
() -> startBot(pluginDirectory, script, interpreter), "PythonDiscordBot-Startup");
startupThread.setDaemon(true);
startupThread.start();
}
@Override
public void onDisable() {
Process process;
synchronized (processLock) {
shuttingDown = true;
process = activeProcess;
}
if (process == null || !process.isAlive()) {
return;
}
process.destroy();
try {
if (!process.waitFor(5, TimeUnit.SECONDS)) {
process.destroyForcibly();
process.waitFor(2, TimeUnit.SECONDS);
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
process.destroyForcibly();
}
}
private void startBot(Path pluginDirectory, Path script, String interpreter) {
Path logFile = pluginDirectory.resolve("logs").resolve("bot.log");
Path requirements = pluginDirectory.resolve("requirements.txt");
try {
if (Files.isRegularFile(requirements) && !installRequirements(interpreter, requirements, logFile)) {
return;
}
if (shuttingDown) {
return;
}
ProcessBuilder processBuilder = new ProcessBuilder(interpreter, "-u", script.toString());
processBuilder.directory(pluginDirectory.toFile());
processBuilder.redirectErrorStream(true);
processBuilder.environment().putAll(readDotEnv(pluginDirectory.resolve(".env")));
Process process = startTrackedProcess(processBuilder);
if (process == null) {
return;
}
getLogger().info("Started Python bot using " + script.getFileName() + ".");
startOutputLogger(process, logFile);
} catch (IOException exception) {
if (!shuttingDown) {
getLogger().severe("Could not start Python. Check python-command and the server's Python installation: "
+ exception.getMessage());
}
}
}
private boolean installRequirements(String interpreter, Path requirements, Path logFile) throws IOException {
getLogger().info("Installing Python packages from " + requirements.getFileName() + ".");
ProcessBuilder processBuilder = new ProcessBuilder(interpreter, "-m", "pip", "install",
"--disable-pip-version-check", "-r", requirements.toString());
processBuilder.directory(requirements.getParent().toFile());
processBuilder.redirectErrorStream(true);
Process process = startTrackedProcess(processBuilder);
if (process == null) {
return false;
}
int exitCode;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
BufferedWriter writer = Files.newBufferedWriter(logFile, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.APPEND)) {
String line;
while ((line = reader.readLine()) != null) {
writer.write("[" + LocalDateTime.now().format(LOG_TIME) + "] [pip] " + line);
writer.newLine();
writer.flush();
getLogger().info("[Python/pip] " + line);
}
exitCode = process.waitFor();
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
process.destroyForcibly();
return false;
} finally {
clearTrackedProcess(process);
}
if (exitCode != 0) {
getLogger().severe("Python package installation failed with exit code " + exitCode
+ ". See plugins/PythonDiscordBot/logs/bot.log.");
return false;
}
return !shuttingDown;
}
private Process startTrackedProcess(ProcessBuilder processBuilder) throws IOException {
synchronized (processLock) {
if (shuttingDown) {
return null;
}
activeProcess = processBuilder.start();
return activeProcess;
}
}
private void clearTrackedProcess(Process process) {
synchronized (processLock) {
if (activeProcess == process) {
activeProcess = null;
}
}
}
private Map<String, String> readDotEnv(Path envFile) throws IOException {
Map<String, String> values = new LinkedHashMap<>();
if (!Files.isRegularFile(envFile)) {
return values;
}
for (String rawLine : Files.readAllLines(envFile, StandardCharsets.UTF_8)) {
String line = rawLine.trim();
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
if (line.startsWith("export ")) {
line = line.substring("export ".length()).trim();
}
int separator = line.indexOf('=');
if (separator < 1) {
continue;
}