delays = new HashMap<>();
-
- ConfigurationSection delaysSection = section.getConfigurationSection("delays");
- if (delaysSection != null) {
- for (String key : delaysSection.getKeys(false)) {
- try {
- int index = Integer.parseInt(key);
- int delay = delaysSection.getInt(key);
- delays.put(index, delay);
- } catch (NumberFormatException e) {
- Dreamvisitor.getPlugin().getLogger().warning("Invalid delay index: " + key);
- }
- }
- }
-
- long lastRun = section.getLong("last-run", 0);
-
- Schedule schedule;
- if (timeSpec instanceof Integer intervalMinutes) {
- // Convert minutes to ticks (20 ticks/second * 60 seconds/minute)
- int intervalTicks = intervalMinutes * 20 * 60;
- schedule = new Schedule(name, intervalTicks, commandList, delays);
- } else if (timeSpec instanceof LocalTime time) {
- schedule = new Schedule(name, time, commandList, delays);
- } else if (timeSpec instanceof CronPattern pattern) {
- schedule = new Schedule(name, pattern, commandList, delays);
- } else {
- return;
- }
-
- if (lastRun > 0) {
- schedule.setLastRun(LocalDateTime.ofEpochSecond(lastRun, 0, java.time.ZoneOffset.UTC));
- }
-
- schedules.add(schedule);
- }
-
- /**
- * Saves the current schedules to the configuration file.
- *
- * This method serializes all schedule objects to YAML format and writes them to
- * the schedules.yml file. Different schedule types (interval, daily, cron) are
- * handled with appropriate type-specific properties. The method also saves
- * metadata
- * such as commands, delays, and last execution time.
- *
- * If the save operation fails, an error is logged, but execution continues.
- */
- public void saveConfig() {
- // Clear existing schedules section to prevent stale data
- config.set("schedules", null);
-
- // Iterate through all schedules and save each one
- for (Schedule schedule : schedules) {
- String path = "schedules." + schedule.getName();
-
- // Save type-specific properties based on schedule type
- switch (schedule.getType()) {
- case INTERVAL -> {
- config.set(path + ".type", "interval");
- // Convert ticks back to minutes for config storage for backward compatibility
- // This allows older versions to read the configuration correctly
- // TODO: Fix this as it cause losses in time units
- config.set(path + ".interval-minutes", schedule.getIntervalMinutes());
- }
- case DAILY -> {
- config.set(path + ".type", "daily");
- // Format time using standard HH:mm:ss format for consistency
- config.set(path + ".time", schedule.getDailyTime().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
- }
- case CRON -> {
- config.set(path + ".type", "cron");
- // Store the raw cron pattern string
- config.set(path + ".pattern", schedule.getCronPattern().getPattern());
- }
- }
-
- config.set(path + ".commands", schedule.getCommands());
-
- // Save delays
- Map delays = schedule.getDelays();
- if (!delays.isEmpty()) {
- for (Map.Entry entry : delays.entrySet()) {
- config.set(path + ".delays." + entry.getKey(), entry.getValue());
- }
- }
-
- if (schedule.getLastRun() != null) {
- config.set(path + ".last-run", schedule.getLastRun().toEpochSecond(java.time.ZoneOffset.UTC));
- }
- }
-
- try {
- config.save(configFile);
- } catch (IOException e) {
- Dreamvisitor.getPlugin().getLogger().log(Level.SEVERE, "Could not save schedules.yml", e);
- }
- }
-
- /**
- * Start the scheduler task
- */
- public void startScheduler() {
- if (taskId != -1) {
- Bukkit.getScheduler().cancelTask(taskId);
- }
-
- taskId = Bukkit.getScheduler().scheduleSyncRepeatingTask(Dreamvisitor.getPlugin(), this::checkSchedules, 20L,
- updateTick);
- }
-
- /**
- * Stop the scheduler task
- */
- public void stopScheduler() {
- if (taskId != -1) {
- Bukkit.getScheduler().cancelTask(taskId);
- taskId = -1;
- }
- }
-
- /**
- * Check if any schedules need to be run
- */
- private void checkSchedules() {
- LocalDateTime now = LocalDateTime.now();
-
- for (Schedule schedule : new ArrayList<>(schedules)) {
- if (schedule.shouldRun(now)) {
- executeSchedule(schedule);
- }
- }
- }
-
- /**
- * Execute a scheduled command
- *
- * @param schedule The schedule to execute
- */
- private void executeSchedule(Schedule schedule) {
- Dreamvisitor.debug("Executing scheduled commands for: " + schedule.getName());
-
- final AtomicBoolean success = new AtomicBoolean(true);
- List commands = schedule.getCommands();
- Map delays = schedule.getDelays();
-
- schedule.setLastRun(LocalDateTime.now());
- saveConfig();
-
- for (int i = 0; i < commands.size(); i++) {
- final int index = i;
- final String command = commands.get(i);
-
- // Get delay for this command in ticks (no conversion needed)
- int delayTicks = 0;
- if (delays.containsKey(index)) {
- delayTicks = delays.get(index);
- }
-
- Bukkit.getScheduler().runTaskLater(Dreamvisitor.getPlugin(), () -> {
- Dreamvisitor.debug("Executing command " + (index + 1) + "/" + commands.size() + ": " + command);
- try {
- boolean result = Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command);
- if (!result) {
- Dreamvisitor.getPlugin().getLogger().warning("Failed to execute scheduled command: " + command);
- success.set(false);
- }
- } catch (Exception e) {
- Dreamvisitor.getPlugin().getLogger().log(Level.SEVERE, "Error executing scheduled command: " + command, e);
- success.set(false);
- }
- }, delayTicks);
- }
- }
-
- /**
- * Add a new interval-based schedule
- *
- * @param name The name of the schedule
- * @param intervalMinutes The interval in minutes
- * @param commands The commands to run
- * @return The created schedule
- */
- public Schedule addSchedule(String name, int intervalMinutes, List commands) {
- return addSchedule(name, intervalMinutes, commands, new HashMap<>());
- }
-
- /**
- * Add a new interval-based schedule
- *
- * @param name The name of the schedule
- * @param intervalMinutes The interval in minutes
- * @param command Single command to run
- * @return The created schedule
- */
- public Schedule addSchedule(String name, int intervalMinutes, String command) {
- return addSchedule(name, intervalMinutes, Collections.singletonList(command));
- }
-
- /**
- * Add a new interval-based schedule with delays
- *
- * @param name The name of the schedule
- * @param intervalMinutes The interval in minutes
- * @param commands The commands to run
- * @param delays Map of command index to delay in ticks
- * @return The created schedule
- */
- public Schedule addSchedule(String name, int intervalMinutes, List commands, Map delays) {
- // Remove existing schedule with the same name
- removeSchedule(name);
-
- // Convert minutes to ticks (20 ticks/second * 60 seconds/minute)
- int intervalTicks = intervalMinutes * 20 * 60;
- Schedule schedule = new Schedule(name, intervalTicks, commands, delays);
- schedules.add(schedule);
- saveConfig();
- return schedule;
- }
-
- /**
- * Add a new daily schedule
- *
- * @param name The name of the schedule
- * @param time The time of day to run
- * @param commands The commands to run
- * @return The created schedule
- */
- public Schedule addDailySchedule(String name, LocalTime time, List commands) {
- return addDailySchedule(name, time, commands, new HashMap<>());
- }
-
- /**
- * Add a new daily schedule
- *
- * @param name The name of the schedule
- * @param time The time of day to run
- * @param command Single command to run
- * @return The created schedule
- */
- public Schedule addDailySchedule(String name, LocalTime time, String command) {
- return addDailySchedule(name, time, Collections.singletonList(command));
- }
-
- /**
- * Add a new daily schedule with delays
- *
- * @param name The name of the schedule
- * @param time The time of day to run
- * @param commands The commands to run
- * @param delays Map of command index to delay in ticks
- * @return The created schedule
- */
- public Schedule addDailySchedule(String name, LocalTime time, List commands, Map delays) {
- // Remove existing schedule with the same name
- removeSchedule(name);
-
- Schedule schedule = new Schedule(name, time, commands, delays);
- schedules.add(schedule);
- saveConfig();
- return schedule;
- }
-
- /**
- * Add a new cron-style schedule
- *
- * @param name The name of the schedule
- * @param pattern The cron pattern
- * @param commands The commands to run
- * @return The created schedule
- */
- public Schedule addCronSchedule(String name, String pattern, List commands) {
- return addCronSchedule(name, pattern, commands, new HashMap<>());
- }
-
- /**
- * Add a new cron-style schedule
- *
- * @param name The name of the schedule
- * @param pattern The cron pattern
- * @param command Single command to run
- * @return The created schedule
- */
- public Schedule addCronSchedule(String name, String pattern, String command) {
- return addCronSchedule(name, pattern, Collections.singletonList(command));
- }
-
- /**
- * Add a new cron-style schedule with delays
- *
- * @param name The name of the schedule
- * @param pattern The cron pattern
- * @param commands The commands to run
- * @param delays Map of command index to delay in ticks
- * @return The created schedule
- */
- public Schedule addCronSchedule(String name, String pattern, List commands, Map delays) {
- // Remove existing schedule with the same name
- removeSchedule(name);
-
- try {
- CronPattern cronPattern = new CronPattern(pattern);
- Schedule schedule = new Schedule(name, cronPattern, commands, delays);
- schedules.add(schedule);
- saveConfig();
- return schedule;
- } catch (PatternSyntaxException e) {
- Dreamvisitor.getPlugin().getLogger().log(Level.SEVERE, "Invalid cron pattern: " + pattern, e);
- return null;
- }
- }
-
- /**
- * Remove a schedule
- *
- * @param name The name of the schedule
- * @return True if removed, false if not found
- */
- public boolean removeSchedule(String name) {
- for (Schedule schedule : new ArrayList<>(schedules)) {
- if (schedule.getName().equals(name)) {
- schedules.remove(schedule);
- saveConfig();
- return true;
- }
- }
- return false;
- }
-
- /**
- * Get all schedules
- *
- * @return An unmodifiable list of schedules
- */
- public List getSchedules() {
- return Collections.unmodifiableList(schedules);
- }
-
- /**
- * Run a schedule immediately
- *
- * @param name The name of the schedule to run
- * @return True if run, false if not found
- */
- public boolean runScheduleNow(String name) {
- for (Schedule schedule : schedules) {
- if (schedule.getName().equals(name)) {
- executeSchedule(schedule);
- return true;
- }
- }
- return false;
- }
-
- /**
- * Get a schedule by name
- *
- * @param name The name of the schedule
- * @return The schedule or null if not found
- */
- @Nullable
- public Schedule getSchedule(String name) {
- for (Schedule schedule : schedules) {
- if (schedule.getName().equals(name)) {
- return schedule;
- }
- }
- return null;
- }
-
- /**
- * Add a delay to a command in a schedule
- *
- * @param name The schedule name
- * @param commandIndex The command index (0-based)
- * @param delayTicks The delay in ticks (20 ticks = 1 second)
- * @return True if successful, false if schedule not found or index invalid
- */
- public boolean addDelay(String name, int commandIndex, int delayTicks) {
- Schedule schedule = getSchedule(name);
- if (schedule == null || commandIndex < 0 || commandIndex >= schedule.getCommands().size()) {
- return false;
- }
-
- schedule.addDelay(commandIndex, delayTicks);
- saveConfig();
- return true;
- }
-
- /**
- * Remove a delay from a command in a schedule
- *
- * @param name The schedule name
- * @param commandIndex The command index (0-based)
- * @return True if successful, false if schedule not found or no delay was set
- */
- public boolean removeDelay(String name, int commandIndex) {
- Schedule schedule = getSchedule(name);
- if (schedule == null) {
- return false;
- }
-
- boolean result = schedule.removeDelay(commandIndex);
- if (result) {
- saveConfig();
- }
- return result;
- }
-
- /**
- * Add a command to an existing schedule
- *
- * @param name The schedule name
- * @param command The command to add
- * @return True if successful, false if schedule not found
- */
- public boolean addCommand(String name, String command) {
- Schedule schedule = getSchedule(name);
- if (schedule == null) {
- return false;
- }
-
- schedule.addCommand(command);
- saveConfig();
- return true;
- }
-
- /**
- * Remove a command from a schedule
- *
- * @param name The schedule name
- * @param commandIndex The command index (0-based)
- * @return True if successful, false if schedule not found or index invalid
- */
- public boolean removeCommand(String name, int commandIndex) {
- Schedule schedule = getSchedule(name);
- if (schedule == null) {
- return false;
- }
-
- boolean result = schedule.removeCommand(commandIndex);
- if (result) {
- saveConfig();
- }
- return result;
- }
-
- /**
- * Simple implementation of cron pattern matching
- */
- public static class CronPattern {
- // Format: minute hour day-of-month month day-of-week
- // Supported: numbers, *, ranges (1-5), lists (1,2,3), step values (*/5, 1-5/2)
- private final String pattern;
- private final String minutePattern;
- private final String hourPattern;
- private final String dayOfMonthPattern;
- private final String monthPattern;
- private final String dayOfWeekPattern;
-
- public CronPattern(String pattern) throws PatternSyntaxException {
- this.pattern = pattern;
- String[] parts = pattern.split("\\s+");
- if (parts.length != 5) {
- throw new PatternSyntaxException("Cron pattern must have 5 parts", pattern, -1);
- }
- minutePattern = parts[0];
- hourPattern = parts[1];
- dayOfMonthPattern = parts[2];
- monthPattern = parts[3];
- dayOfWeekPattern = parts[4];
-
- // Validate all patterns
- validateField(minutePattern, 0, 59);
- validateField(hourPattern, 0, 23);
- validateField(dayOfMonthPattern, 1, 31);
- validateField(monthPattern, 1, 12);
- validateField(dayOfWeekPattern, 0, 6);
- }
-
- private void validateField(String field, int min, int max) throws PatternSyntaxException {
- if (field.equals("*")) {
- return;
- }
-
- if (field.contains("/")) {
- String[] parts = field.split("/");
- if (parts.length != 2) {
- throw new PatternSyntaxException("Invalid step value format", field, -1);
- }
- validateField(parts[0], min, max);
- try {
- int step = Integer.parseInt(parts[1]);
- if (step <= 0) {
- throw new PatternSyntaxException("Step value must be positive", field, -1);
- }
- } catch (NumberFormatException e) {
- throw new PatternSyntaxException("Invalid step value", field, -1);
- }
- return;
- }
-
- if (field.contains(",")) {
- for (String part : field.split(",")) {
- validateField(part, min, max);
- }
- return;
- }
-
- if (field.contains("-")) {
- String[] parts = field.split("-");
- if (parts.length != 2) {
- throw new PatternSyntaxException("Invalid range format", field, -1);
- }
- try {
- int start = Integer.parseInt(parts[0]);
- int end = Integer.parseInt(parts[1]);
- if (start < min || end > max || start > end) {
- throw new PatternSyntaxException("Invalid range values", field, -1);
- }
- } catch (NumberFormatException e) {
- throw new PatternSyntaxException("Invalid range values", field, -1);
- }
- return;
- }
-
- try {
- int value = Integer.parseInt(field);
- if (value < min || value > max) {
- throw new PatternSyntaxException("Value out of range", field, -1);
- }
- } catch (NumberFormatException e) {
- throw new PatternSyntaxException("Invalid value", field, -1);
- }
- }
-
- public String getPattern() {
- return pattern;
- }
-
- public boolean matches(LocalDateTime dateTime) {
- return matchesField(minutePattern, dateTime.getMinute(), 0, 59)
- && matchesField(hourPattern, dateTime.getHour(), 0, 23)
- && matchesField(dayOfMonthPattern, dateTime.getDayOfMonth(), 1, 31)
- && matchesField(monthPattern, dateTime.getMonthValue(), 1, 12)
- && matchesField(dayOfWeekPattern, dateTime.getDayOfWeek().getValue() % 7, 0, 6);
- }
-
- private boolean matchesField(String pattern, int value, int min, int max) {
- if (pattern.equals("*")) {
- return true;
- }
-
- if (pattern.contains("/")) {
- String[] parts = pattern.split("/");
- String range = parts[0];
- int step = Integer.parseInt(parts[1]);
-
- if (range.equals("*")) {
- return (value - min) % step == 0;
- } else {
- return matchesField(range, value, min, max) && (value - min) % step == 0;
- }
- }
-
- if (pattern.contains(",")) {
- for (String part : pattern.split(",")) {
- if (matchesField(part, value, min, max)) {
- return true;
- }
- }
- return false;
- }
-
- if (pattern.contains("-")) {
- String[] parts = pattern.split("-");
- int start = Integer.parseInt(parts[0]);
- int end = Integer.parseInt(parts[1]);
- return value >= start && value <= end;
- }
-
- return Integer.parseInt(pattern) == value;
- }
- }
-
- /**
- * Class representing a scheduled command
- */
- public static class Schedule {
- private final String name;
- private final ScheduleType type;
- private final int intervalTicks; // Now storing interval in ticks instead of minutes
- private final LocalTime dailyTime;
- private final CronPattern cronPattern;
- private final List commands;
- private final Map delays; // Command index -> delay in ticks
- private LocalDateTime lastRun;
-
- public enum ScheduleType {
- INTERVAL, DAILY, CRON
- }
-
- // Interval constructor - now accepts ticks instead of minutes
- public Schedule(String name, int intervalTicks, List commands, Map delays) {
- this.name = name;
- this.type = ScheduleType.INTERVAL;
- this.intervalTicks = intervalTicks;
- this.dailyTime = null;
- this.cronPattern = null;
- this.commands = new ArrayList<>(commands);
- this.delays = new HashMap<>(delays);
- this.lastRun = null;
- }
-
- // Daily constructor
- public Schedule(String name, LocalTime time, List commands, Map delays) {
- this.name = name;
- this.type = ScheduleType.DAILY;
- this.intervalTicks = 0;
- this.dailyTime = time;
- this.cronPattern = null;
- this.commands = new ArrayList<>(commands);
- this.delays = new HashMap<>(delays);
- this.lastRun = null;
- }
-
- // Cron constructor
- public Schedule(String name, CronPattern pattern, List commands, Map delays) {
- this.name = name;
- this.type = ScheduleType.CRON;
- this.intervalTicks = 0;
- this.dailyTime = null;
- this.cronPattern = pattern;
- this.commands = new ArrayList<>(commands);
- this.delays = new HashMap<>(delays);
- this.lastRun = null;
- }
-
- public String getName() {
- return name;
- }
-
- public ScheduleType getType() {
- return type;
- }
-
- /**
- * Get the interval in minutes (converted from ticks for backward compatibility)
- *
- * @return The interval in minutes
- */
- public int getIntervalMinutes() {
- return intervalTicks / (20 * 60); // Convert ticks to minutes
- }
-
- /**
- * Get the interval in ticks
- *
- * @return The interval in ticks
- */
- public int getIntervalTicks() {
- return intervalTicks;
- }
-
- public LocalTime getDailyTime() {
- return dailyTime;
- }
-
- public CronPattern getCronPattern() {
- return cronPattern;
- }
-
- public List getCommands() {
- return Collections.unmodifiableList(commands);
- }
-
- public Map getDelays() {
- return Collections.unmodifiableMap(delays);
- }
-
- public LocalDateTime getLastRun() {
- return lastRun;
- }
-
- public void setLastRun(LocalDateTime lastRun) {
- this.lastRun = lastRun;
- }
-
- public void addCommand(String command) {
- this.commands.add(command);
- }
-
- public boolean removeCommand(int index) {
- if (index < 0 || index >= commands.size()) {
- return false;
- }
- commands.remove(index);
-
- // Remove any delays for this command
- delays.remove(index);
-
- // Adjust delays for higher indexed commands
- Map newDelays = new HashMap<>();
- for (Map.Entry entry : delays.entrySet()) {
- int delayIndex = entry.getKey();
- if (delayIndex > index) {
- newDelays.put(delayIndex - 1, entry.getValue());
- } else {
- newDelays.put(delayIndex, entry.getValue());
- }
- }
- delays.clear();
- delays.putAll(newDelays);
- return true;
- }
-
- public void addDelay(int commandIndex, int delayTicks) {
- delays.put(commandIndex, delayTicks);
- }
-
- public boolean removeDelay(int commandIndex) {
- return delays.remove(commandIndex) != null;
- }
-
- /**
- * Check if this schedule should run
- *
- * @param now The current time
- * @return True if it should run
- */
- public boolean shouldRun(@NotNull LocalDateTime now) {
- switch (type) {
- case INTERVAL:
- if (lastRun == null) {
- return true; // Never run before
- }
- Duration duration = Duration.between(lastRun, now);
- // Convert duration to ticks and compare with intervalTicks
- long durationTicks = duration.toSeconds() * 20;
- return durationTicks >= intervalTicks;
-
- case DAILY:
- if (lastRun != null && lastRun.toLocalDate().equals(now.toLocalDate())) {
- return false; // Already run today
- }
- LocalTime currentTime = now.toLocalTime();
- return currentTime.isAfter(dailyTime) || currentTime.equals(dailyTime);
-
- case CRON:
- if (lastRun != null) {
- LocalDateTime nextMinute = lastRun.plusMinutes(1).withSecond(0).withNano(0);
- if (now.isBefore(nextMinute)) {
- return false; // Don't run more than once per minute
- }
- }
- return cronPattern.matches(now);
-
- default:
- return false;
- }
- }
-
- /**
- * Get a user-friendly string representation of time until next run
- *
- * @return Time until next run as a string
- */
- public String getTimeUntilNextRun() {
- LocalDateTime now = LocalDateTime.now();
-
- switch (type) {
- case INTERVAL:
- if (lastRun == null) {
- return "Ready to run";
- }
-
- // Calculate next run time using ticks
- long durationSeconds = intervalTicks / 20;
- LocalDateTime nextRun = lastRun.plusSeconds(durationSeconds);
- Duration duration = Duration.between(now, nextRun);
-
- if (duration.isNegative()) {
- return "Ready to run";
- }
-
- long hours = duration.toHours();
- long minutes = duration.toMinutesPart();
- long seconds = duration.toSecondsPart();
-
- if (hours > 0) {
- return hours + "h " + minutes + "m " + seconds + "s";
- } else if (minutes > 0) {
- return minutes + "m " + seconds + "s";
- } else {
- return seconds + "s";
- }
-
- case DAILY:
- LocalDateTime nextRunTime = now.toLocalDate().atTime(dailyTime);
- if (now.isAfter(nextRunTime)) {
- nextRunTime = nextRunTime.plusDays(1);
- }
-
- Duration timeUntil = Duration.between(now, nextRunTime);
- long days = timeUntil.toDays();
- long dHours = timeUntil.toHoursPart();
- long dMinutes = timeUntil.toMinutesPart();
-
- if (days > 0) {
- return days + "d " + dHours + "h " + dMinutes + "m";
- } else if (dHours > 0) {
- return dHours + "h " + dMinutes + "m";
- } else {
- return dMinutes + "m";
- }
-
- case CRON:
- // For cron, we check the next few hours in 1-minute increments to find the next
- // match
- LocalDateTime checkTime = now;
- for (int i = 0; i < 24 * 60; i++) { // Check up to 24 hours ahead
- checkTime = checkTime.plusMinutes(1);
- if (cronPattern.matches(checkTime)) {
- Duration cronTimeUntil = Duration.between(now, checkTime);
- long cronHours = cronTimeUntil.toHours();
- long cronMinutes = cronTimeUntil.toMinutesPart();
-
- if (cronHours > 0) {
- return cronHours + "h " + cronMinutes + "m";
- } else {
- return cronMinutes + "m";
- }
- }
- }
- return "More than 24h";
-
- default:
- return "Unknown";
- }
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("Schedule{name='").append(name).append("', type=").append(type);
-
- switch (type) {
- case INTERVAL -> {
- int minutes = intervalTicks / (20 * 60);
- int remainingSeconds = (intervalTicks % (20 * 60)) / 20;
- if (remainingSeconds > 0) {
- sb.append(", interval=").append(minutes).append("m ").append(remainingSeconds).append("s");
- } else {
- sb.append(", interval=").append(minutes).append("m");
- }
- }
- case DAILY -> sb.append(", time=").append(dailyTime);
- case CRON -> sb.append(", pattern='").append(cronPattern.getPattern()).append("'");
- }
-
- sb.append(", commands=").append(commands.size());
- if (!delays.isEmpty()) {
- sb.append(", delays=").append(delays);
- }
-
- return sb.append("}").toString();
- }
- }
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ConsoleLogger.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ConsoleLogger.java
deleted file mode 100644
index 9289e2e..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ConsoleLogger.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package io.github.stonley890.dreamvisitor.functions;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import org.apache.logging.log4j.core.LogEvent;
-import org.apache.logging.log4j.core.appender.AbstractAppender;
-import org.jetbrains.annotations.NotNull;
-
-import java.time.LocalDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.ArrayList;
-import java.util.List;
-
-public class ConsoleLogger extends AbstractAppender {
-
- public static final StringBuilder messageBuilder = new StringBuilder();
- public static final List overFlowMessages = new ArrayList<>();
-
- public ConsoleLogger() {
- super("MyLogAppender", null, null, false, null);
- start();
- }
-
- @Override
- public void append(@NotNull LogEvent event) {
- // if you don't make it immutable, then you may have some unexpected behaviors
- LogEvent log = event.toImmutable();
-
- StringBuilder builder = new StringBuilder(log.getMessage().getFormattedMessage());
-
- if (log.getThrown() != null) {
- builder.append("\n").append(log.getThrown().getMessage());
- for (StackTraceElement stackTraceElement : log.getThrown().getStackTrace()) builder.append("\n").append(stackTraceElement.toString());
- }
-
- String message = builder.toString();
-
- // Remove Minecraft formatting codes
- message = message.replaceAll("\u001B?(\\W1B)?\\[([0-9,;]+)m", "");
- message = "[" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) + " " + event.getLevel().toString() + "] " + Bot.escapeMarkdownFormatting(message);
-
- // Truncate messages over 2000 characters
- if (message.length() >= 2000) {
- String tooLongMessage = "**This message was too long! Here is the shorter version:**\n";
- message = tooLongMessage.concat(message.substring(0, (1998 - tooLongMessage.length())));
- }
-
- // Pause adding strings if the new message will be >= 2000
- if (messageBuilder.toString().length() + message.length() + "\n".length() < 2000) {
-
- if (!messageBuilder.isEmpty()) {
- messageBuilder.append("\n");
- }
- messageBuilder.append(message);
-
- } else {
- overFlowMessages.add(message);
- }
-
-
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Flight.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Flight.java
deleted file mode 100644
index 26bb861..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Flight.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package io.github.stonley890.dreamvisitor.functions;
-
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.NamespacedKey;
-import org.bukkit.boss.BarColor;
-import org.bukkit.boss.BarStyle;
-import org.bukkit.boss.KeyedBossBar;
-import org.bukkit.entity.Player;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class Flight {
- public static double energyCapacity = Dreamvisitor.getPlugin().getConfig().getInt("flightEnergyCapacity");
- public static double reactivationPoint = Dreamvisitor.getPlugin().getConfig().getInt("flightRegenerationPoint");
- public static final Map energy = new HashMap<>();
- private static final Map energyDepletion = new HashMap<>();
- private static final Map flightRestricted = new HashMap<>();
-
- public static void init() {
- Bukkit.getScheduler().runTaskTimer(Dreamvisitor.getPlugin(), () -> {
-
- for (Player player : Bukkit.getOnlinePlayers()) {
-
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- // If player does not have the dreamvisitor.fly permission, disable flight if not in creative
- if ((!player.hasPermission("dreamvisitor.fly") || isFlightRestricted(player) && !inFlightGameMode(player)) || (memory.flightDisabled && !inFlightGameMode(player))) {
- player.setAllowFlight(false);
- } else setupFlight(player);
-
- energy.putIfAbsent(player, energyCapacity);
-
- // Get bossbar (even if it's null)
- NamespacedKey namespacedKey = NamespacedKey.fromString("dreamvisitor:" + player.getUniqueId().toString().toLowerCase() + "-energy", Dreamvisitor.getPlugin());
- assert namespacedKey != null;
- KeyedBossBar bossBar = Bukkit.getBossBar(namespacedKey);
-
- if (energy.get(player) < energyCapacity) {
-
- if (!player.isFlying() || inFlightGameMode(player)) {
- // Regenerate energy if not flying or in creative/spectator mode
- try {
- energy.compute(player, (k, i) -> i + 1);
- } catch (NullPointerException e) {
- energy.put(player, energyCapacity);
- }
- }
-
- if (energy.get(player) > energyCapacity) energy.put(player, energyCapacity);
-
- if (bossBar == null) { // Create bossbar if it's null
- bossBar = Bukkit.createBossBar(namespacedKey, "Energy", BarColor.GREEN, BarStyle.SEGMENTED_10);
- bossBar.addPlayer(player);
- }
-
- bossBar.setVisible(!inFlightGameMode(player));
-
- // Set progress
- bossBar.setProgress(energy.get(player) / energyCapacity);
-
- // Remove player from flight if energy runs out
- if (energy.get(player) <= 0) {
- // Set bossbar to red if it's depleted
- bossBar.setColor(BarColor.RED);
- setPlayerDepleted(player, true);
- if (player.isFlying()) {
- player.setFlying(false);
- player.setGliding(true);
- player.setAllowFlight(false);
- }
- }
-
- // Set bossbar to green if it reaches reactivation point
- if (isPlayerDepleted(player) && energy.get(player) >= reactivationPoint) {
- bossBar.setColor(BarColor.GREEN);
- setPlayerDepleted(player, false);
- setupFlight(player);
- }
-
- } else if (bossBar != null) {
- // Remove bossbar if it's full
- bossBar.removePlayer(player);
- bossBar.setVisible(false);
- Bukkit.removeBossBar(namespacedKey);
- }
- }
- }, 0, 0);
- }
-
- public static boolean isPlayerDepleted(Player player) {
- return (energyDepletion.computeIfAbsent(player, k -> false));
- }
-
- public static void setPlayerDepleted(Player player, boolean depleted) {
- energyDepletion.put(player, depleted);
- }
-
- /**
- * Whether flight is restricted by a WorldGuard region.
- * @param player the player to check for
- * @return whether flying is permitted by the player's region
- */
- public static boolean isFlightRestricted(Player player) {
- return flightRestricted.computeIfAbsent(player, k -> false);
- }
-
- public static void setFlightRestricted(@NotNull Player player, boolean restricted) {
- flightRestricted.put(player, restricted);
- if (player.getGameMode() != GameMode.CREATIVE && player.getGameMode() != GameMode.SPECTATOR) {
-
- if (restricted) {
- if (player.isFlying()) {
- player.setFlying(false);
- player.setGliding(true);
- }
- player.setAllowFlight(false);
- }
- else setupFlight(player);
-
- }
-
- }
-
- public static void setupFlight(@NotNull Player player) {
- // Re-enable flight if it gets disabled by game mode change
- // Dreamvisitor.debug("FlightNotAllowed: " + !player.getAllowFlight() + " Permission: " + player.hasPermission("dreamvisitor.fly") + " NotRestricted: " + !isFlightRestricted(player) + " NotDepleted: " + !isPlayerDepleted(player) + " NotDisabled: " + !PlayerUtility.getPlayerMemory(player.getUniqueId()).flightDisabled);
- if (!player.getAllowFlight() && player.hasPermission("dreamvisitor.fly") && !isFlightRestricted(player) && !isPlayerDepleted(player) && !PlayerUtility.getPlayerMemory(player.getUniqueId()).flightDisabled) {
- Dreamvisitor.debug("All requirements met for flight.");
- Bukkit.getScheduler().runTaskLater(Dreamvisitor.getPlugin(), () -> player.setAllowFlight(true), 1);
- }
- }
-
- /**
- * Whether a player is in a flight-enabled game mode like Creative or Spectator.
- * @param player
- * @return
- */
- public static boolean inFlightGameMode(@NotNull Player player) {
- return (player.getGameMode() == GameMode.CREATIVE || player.getGameMode() == GameMode.SPECTATOR);
- }
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/InvSwap.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/InvSwap.java
deleted file mode 100644
index 3b5d80e..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/InvSwap.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package io.github.stonley890.dreamvisitor.functions;
-
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import org.bukkit.entity.Player;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-
-public class InvSwap {
-
- public static void swapInventories(@NotNull Player player) {
-
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- ItemStack[] invContents;
-
- if (memory.creative) {
- memory.creativeInv = player.getInventory().getContents();
- if (memory.survivalInv == null) invContents = null;
- else invContents = memory.survivalInv;
- } else {
- memory.survivalInv = player.getInventory().getContents();
- if (memory.creativeInv == null) invContents = null;
- else invContents = memory.creativeInv;
- }
-
- if (invContents == null) player.getInventory().clear();
- else player.getInventory().setContents(invContents);
- memory.creative = !memory.creative;
-
- PlayerUtility.setPlayerMemory(player.getUniqueId(), memory);
-
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ItemBanList.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ItemBanList.java
deleted file mode 100644
index 497c902..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/ItemBanList.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package io.github.stonley890.dreamvisitor.functions;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.inventory.InventoryCloseEvent;
-import org.bukkit.inventory.Inventory;
-import org.bukkit.inventory.ItemStack;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.Objects;
-
-public class ItemBanList implements Listener {
- public static final Inventory inv = Bukkit.createInventory(null, 27, "Blacklisted Items");
- public static ItemStack[] badItems;
-
- public static void saveItems() {
- Dreamvisitor plugin = Dreamvisitor.getPlugin();
- badItems = inv.getContents();
- plugin.getConfig().set("itemBlacklist", badItems);
- plugin.saveConfig();
- }
-
- @EventHandler
- public void onInventoryClose(@NotNull InventoryCloseEvent event) {
- Player player = (Player) event.getPlayer();
-
- if (!player.isOp() && ItemBanList.badItems != null) {
-
- for (ItemStack item : ItemBanList.badItems) {
- if (item == null) continue;
- for (ItemStack content : player.getInventory().getContents()) {
- if (content == null || !content.isSimilar(item)) continue;
- player.getInventory().remove(item);
- Bot.sendLog("Removed " + item.getType().name() + " (" + Objects.requireNonNull(item.getItemMeta()).getDisplayName() + ") from " + player.getName());
- }
- }
- }
-
- if (event.getInventory().equals(ItemBanList.inv)) {
- ItemBanList.saveItems();
- }
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Sandbox.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Sandbox.java
deleted file mode 100644
index 6da1251..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/functions/Sandbox.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package io.github.stonley890.dreamvisitor.functions;
-
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import net.md_5.bungee.api.ChatColor;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.block.Container;
-import org.bukkit.block.DecoratedPot;
-import org.bukkit.block.EnderChest;
-import org.bukkit.entity.ItemFrame;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.block.Action;
-import org.bukkit.event.player.PlayerCommandPreprocessEvent;
-import org.bukkit.event.player.PlayerDropItemEvent;
-import org.bukkit.event.player.PlayerInteractEntityEvent;
-import org.bukkit.event.player.PlayerInteractEvent;
-import org.bukkit.inventory.meta.SpawnEggMeta;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.Objects;
-
-public class Sandbox implements Listener {
-
- private static final String[] disallowedCommands = {"tpaccept", "tpa", "hub", "etpa", "etpaccept", "home", "ehome"};
-
- /**
- * Enable sandbox mode for the given {@link Player}. If they are not already in sandbox mode, they will be put into creative mode and their inventory will be swapped.
- *
- * @param player the player to enable sandbox mode for.
- */
- public static void enableSandbox(@NotNull Player player) {
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- if (memory.sandbox) return;
-
- memory.sandbox = true;
- InvSwap.swapInventories(player);
- player.setGameMode(GameMode.CREATIVE);
- player.setGlowing(true);
-
- ComponentBuilder messageBuilder = new ComponentBuilder();
- messageBuilder.append("You are now in sandbox mode.\n").bold(true)
- .append("A staff member put you into sandbox mode. You are now in creative mode. " +
- "Your inventory has been cleared and stored for later restore. " +
- "In sandbox mode, the following limitations are imposed:\n").bold(false)
- .append("- You cannot access containers.\n")
- .append("- You cannot drop items.\n")
- .append("- You cannot use spawn eggs.\n")
- .append("- You cannot teleport.\n")
- .append("Please notify a staff member if you require assistance with any of these rules.");
- player.spigot().sendMessage(messageBuilder.create());
-
- }
-
- /**
- * Disable sandbox mode for the given {@link Player}. If they are still in sandbox mode, they will be put into survival mode and their inventory will be swapped.
- *
- * @param player the player to disable sandbox mode for.
- */
- public static void disableSandbox(@NotNull Player player) {
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- if (!memory.sandbox) return;
-
- memory.sandbox = false;
- InvSwap.swapInventories(player);
- player.setGameMode(GameMode.SURVIVAL);
- player.setGlowing(false);
-
- player.sendMessage(ChatColor.BOLD + "You are no longer in sandbox mode.");
- }
-
- @EventHandler
- public void onPlayerDropItem(@NotNull PlayerDropItemEvent event) {
- Player player = event.getPlayer();
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
- if (memory.sandbox) event.setCancelled(true);
- }
-
- @EventHandler
- public void onPlayerInteract(@NotNull PlayerInteractEvent event) {
- Player player = event.getPlayer();
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
- if (!memory.sandbox) return;
- if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
- assert event.getClickedBlock() != null;
- if ((event.getClickedBlock().getState() instanceof Container && !player.isSneaking())
- || (event.getClickedBlock().getState() instanceof DecoratedPot)
- || (event.getClickedBlock().getState() instanceof EnderChest)
- || (event.getItem() != null && event.getItem().getItemMeta() instanceof SpawnEggMeta))
- event.setCancelled(true);
- }
- }
-
- @EventHandler
- public void onPlayerInteractEntity (@NotNull PlayerInteractEntityEvent event) {
- Player player = event.getPlayer();
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
- if (!memory.sandbox) return;
- if (event.getRightClicked() instanceof ItemFrame) {
- for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) {
- if (onlinePlayer.hasPermission("dreamvisitor.sandbox")) {
- onlinePlayer.sendMessage(Dreamvisitor.PREFIX + event.getPlayer().getName() + " interacted with an item frame with held item " + Objects.requireNonNull(player.getInventory().getItem(event.getHand())).getType());
- }
- }
- }
- }
-
- @EventHandler
- public void onPlayerCommandPreprocess(@NotNull PlayerCommandPreprocessEvent event) {
-
- Player player = event.getPlayer();
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
- if (memory.sandbox) {
- for (String disallowedCommand : disallowedCommands) {
- if (event.getMessage().contains(disallowedCommand)) event.setCancelled(true);
- }
- } else {
- for (String disallowedCommand : disallowedCommands) {
- if (event.getMessage().contains(disallowedCommand))
- for (Player onlinePlayer : Bukkit.getOnlinePlayers())
- if (PlayerUtility.getPlayerMemory(onlinePlayer.getUniqueId()).sandbox && event.getMessage().contains(onlinePlayer.getName())) {
- event.getPlayer().sendMessage(ChatColor.RED + "That player is currently in Sandbox Mode.");
- event.setCancelled(true);
- }
-
- }
- }
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenEntityDamage.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenEntityDamage.java
deleted file mode 100644
index e877cf6..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenEntityDamage.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import org.bukkit.entity.EntityType;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.entity.EntityDamageByEntityEvent;
-
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenEntityDamage implements Listener {
-
- final Dreamvisitor plugin = Dreamvisitor.getPlugin();
-
- @EventHandler
- public void onEntityDamageEvent(@NotNull EntityDamageByEntityEvent event) {
-
- // If PvP is disabled and the damage type is player, cancel the event
- if ((event.getDamager().getType() == EntityType.PLAYER && event.getEntity().getType() == EntityType.PLAYER) && plugin.getConfig().getBoolean("disablepvp")) {
- event.setCancelled(true);
- }
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerChat.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerChat.java
deleted file mode 100644
index c58819c..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerChat.java
+++ /dev/null
@@ -1,155 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import io.github.stonley890.dreamvisitor.data.BadWords;
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import io.github.stonley890.dreamvisitor.functions.Chatback;
-import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
-import net.md_5.bungee.api.chat.BaseComponent;
-import net.md_5.bungee.api.chat.ComponentBuilder;
-import net.md_5.bungee.api.chat.HoverEvent;
-import net.md_5.bungee.api.chat.TextComponent;
-import net.md_5.bungee.api.chat.hover.content.Text;
-import org.bukkit.Bukkit;
-import net.md_5.bungee.api.ChatColor;
-import org.bukkit.configuration.InvalidConfigurationException;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.AsyncPlayerChatEvent;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenPlayerChat implements Listener {
-
- final Dreamvisitor plugin = Dreamvisitor.getPlugin();
-
- @EventHandler
- @SuppressWarnings({"null"})
- public void onPlayerChatEvent(@NotNull AsyncPlayerChatEvent event) {
-
- if (event.getPlayer().hasPermission("dreamvisitor.set.autoradio")) {
- PlayerMemory memory = PlayerUtility.getPlayerMemory(event.getPlayer().getUniqueId());
-
- if (memory.autoRadio) {
- event.setCancelled(true);
- Bukkit.getScheduler().runTask(Dreamvisitor.getPlugin(), () -> Bukkit.dispatchCommand(event.getPlayer(), "radio " + event.getMessage()));
- return;
- }
- }
-
- List badWords = BadWords.getBadWords();
-
- String message = event.getMessage();
-
- for (String badWord : badWords) {
-
- Pattern pattern = Pattern.compile(".*\\b" + badWord + "\\b.*");
-
- if (pattern.matcher(message).matches()) {
- event.getPlayer().sendMessage(ChatColor.RED + "You can't say " + ChatColor.YELLOW + badWord + ChatColor.RED + "!");
- event.setCancelled(true);
- return;
- }
- }
-
- /*
- Send chat messages to Discord
- IF chat is not paused AND the player is not an operator OR the player is an
- operator, send message
- */
-
- String chatMessage = "**" + Bot.escapeMarkdownFormatting(event.getPlayer().getName()) + "**: " + event.getMessage();
-
-
-
- if (!Dreamvisitor.chatPaused || event.isCancelled()) {
- if (event.isCancelled()) return;
-
- try {
- if (Chatback.nextChatback.containsKey(event.getPlayer())) {
- Chatback.ReplyMessage replyMessage = Chatback.nextChatback.get(event.getPlayer());
-
- ComponentBuilder replyNotice = new ComponentBuilder();
- replyNotice.append("โฑ Reply to ").color(ChatColor.GRAY);
- TextComponent replyUser = new TextComponent();
- replyUser.setText(replyMessage.authorEffectiveName);
- replyUser.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(replyMessage.authorUsername)));
- replyNotice.append(replyUser);
-
- Bot.getGameChatChannel().sendMessage(chatMessage).setMessageReference(replyMessage.messageId).failOnInvalidReply(false).queue();
-
- Bukkit.spigot().broadcast(replyNotice.create());
-
- Chatback.nextChatback.remove(event.getPlayer());
- } else {
- Bot.getGameChatChannel().sendMessage(chatMessage).queue();
- }
-
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(chatMessage);
-
- } else {
-
- // Load pauseBypass file
- File file = new File(plugin.getDataFolder().getAbsolutePath() + "/pauseBypass.yml");
- FileConfiguration fileConfig = YamlConfiguration.loadConfiguration(file);
- List bypassedPlayers;
-
- // Load file
- try {
- fileConfig.load(file);
- } catch (IOException | InvalidConfigurationException ignored) {
- }
-
- // Fetch bypassed players
- bypassedPlayers = (fileConfig.getStringList("players"));
-
- // If player is on soft whitelist or is op, allow.
- if (bypassedPlayers.contains(event.getPlayer().getUniqueId().toString())
- || event.getPlayer().hasPermission("dreamvisitor.nopause")) {
-
- try {
- if (Chatback.nextChatback.containsKey(event.getPlayer())) {
- Chatback.ReplyMessage replyMessage = Chatback.nextChatback.get(event.getPlayer());
-
- ComponentBuilder replyNotice = new ComponentBuilder();
- replyNotice.append("โฑ Reply to ").color(ChatColor.GRAY);
- TextComponent replyUser = new TextComponent(replyMessage.authorEffectiveName);
- replyUser.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(replyMessage.authorUsername)));
- replyNotice.append(replyUser);
-
- Bukkit.spigot().broadcast(replyNotice.create());
- Bot.getGameChatChannel().sendMessage(chatMessage).setMessageReference(replyMessage.messageId).failOnInvalidReply(false).queue();
-
- Chatback.nextChatback.remove(event.getPlayer());
- } else {
- Bot.getGameChatChannel().sendMessage(chatMessage).queue();
- }
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(chatMessage);
-
- } else {
- event.setCancelled(true);
- event.getPlayer().sendMessage(ChatColor.RED + "Chat is currently paused.");
-
- Bot.sendLog("Blocked: " + chatMessage);
-
- }
- }
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerCmdPreprocess.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerCmdPreprocess.java
deleted file mode 100644
index d5d2bbb..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerCmdPreprocess.java
+++ /dev/null
@@ -1,129 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import io.github.stonley890.dreamvisitor.functions.Mail;
-import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
-import org.bukkit.Bukkit;
-import org.bukkit.configuration.InvalidConfigurationException;
-import org.bukkit.configuration.file.FileConfiguration;
-import org.bukkit.configuration.file.YamlConfiguration;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.PlayerCommandPreprocessEvent;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import net.md_5.bungee.api.ChatColor;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenPlayerCmdPreprocess implements Listener {
-
- final Dreamvisitor plugin = Dreamvisitor.getPlugin();
- final String[] msgAliases = {"/msg ","/tell ","/whisper ","/reply ","/t ","/w ","/r ", "/mail send "};
- final String[] tpAliases = {
- "/call","/ecall","/tpa","/etpa","/tpask","/etpask",
- "/tpaccept","/etpaccept","/tpyes","/etpyes",
- "/home", "/ehome", "/homes", "/ehomes", "/claimspawn"
- };
-
- @EventHandler
- public void onPlayerCommandPreprocess(@NotNull PlayerCommandPreprocessEvent event) {
-
- String cmd = event.getMessage();
- Player player = event.getPlayer();
-
- // Don't allow /tw facts reset because it is very destructive.
- if (
- cmd.stripTrailing().equalsIgnoreCase("/tw facts reset") ||
- cmd.stripTrailing().equalsIgnoreCase("/typewriter facts reset")
- ) {
- player.sendMessage(ChatColor.RED + "Dreamvisitor stopped you from running that command because it's too destructive <3");
- event.setCancelled(true);
- return;
- }
-
- // '/me' and '/rp' pass through
- if ((cmd.startsWith("/me " ) || cmd.startsWith("/rp" )) && !event.isCancelled()) {
-
- // IF chatPaused stop /me unless bypassing
- if (Dreamvisitor.chatPaused) {
-
- // Init bypassed players file
- File file = new File(plugin.getDataFolder().getAbsolutePath() + "/pauseBypass.yml");
- FileConfiguration fileConfig = YamlConfiguration.loadConfiguration(file);
- List bypassedPlayers;
-
- // Load file
- try {
- fileConfig.load(file);
- } catch (IOException | InvalidConfigurationException e1) {
- Bukkit.getLogger().warning("Could not load 'pauseBypass.yml' file! " + e1.getMessage());
- }
-
- // Remember bypassed players
- bypassedPlayers = fileConfig.getStringList("players");
-
- // If list contains player, allow
- if (bypassedPlayers.contains(player.getUniqueId().toString()) || player.isOp()) {
- // Remove command
- int spaceIndex = cmd.indexOf(' ');
- if (spaceIndex == -1) return;
- String action = cmd.substring(spaceIndex + 1);
- String message = "**[" + Bot.escapeMarkdownFormatting(ChatColor.stripColor(player.getDisplayName())) + " **(" + player.getName()
- + ")**]** " + ChatColor.stripColor(action);
- // Send message
- try {
- Bot.getGameChatChannel().sendMessage(message).queue();
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(message);
- } // If list does not contain player, stop the command
- else {
- event.setCancelled(true);
- player.sendMessage(ChatColor.RED + "Chat is currently paused.");
- }
- } // If chat is not paused, allow
- else {
-
- // Remove command
- int spaceIndex = cmd.indexOf(' ');
- if (spaceIndex == -1) return;
- String action = cmd.substring(spaceIndex + 1);
- String message = "**[" + Bot.escapeMarkdownFormatting(ChatColor.stripColor(player.getDisplayName())) + " **(" + player.getName()
- + ")**]** " + ChatColor.stripColor(action);
- // Send message
- try {
- Bot.getGameChatChannel().sendMessage(message).queue();
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(message);
- }
- } else {
- for (String string : msgAliases) {
- if (cmd.startsWith(string)) {
- String message = "**" + Bot.escapeMarkdownFormatting(player.getName()) + "** sent command: `" + cmd + "`";
- Bot.sendLog(message);
- return;
- }
- }
- for (String tpAlias : tpAliases) {
- if (cmd.startsWith(tpAlias)) {
- if (Mail.isPLayerDeliverer(player)) Mail.cancel(player);
- for (Player sandboxer : Bukkit.getOnlinePlayers()) {
- if (PlayerUtility.getPlayerMemory(sandboxer.getUniqueId()).sandbox && cmd.contains(sandboxer.getName())) {
- player.sendMessage(Dreamvisitor.PREFIX + "That player is currently in Sandbox Mode. Teleportation is not allowed.");
- event.setCancelled(true);
- }
- }
- }
- }
- }
- }
-}
\ No newline at end of file
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerDeath.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerDeath.java
deleted file mode 100644
index d1f3c57..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerDeath.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import io.github.stonley890.dreamvisitor.functions.Mail;
-import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
-import net.md_5.bungee.api.ChatColor;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.entity.PlayerDeathEvent;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenPlayerDeath implements Listener {
-
- @EventHandler
- public void onPlayerDeathEvent(@NotNull PlayerDeathEvent event) {
-
- Player player = event.getEntity().getPlayer();
- if (player != null && Mail.isPLayerDeliverer(player)) Mail.cancel(player);
-
- if (event.getDeathMessage() == null) return;
-
- // Send death messages
- String chatMessage = "**" + Bot.escapeMarkdownFormatting(ChatColor.stripColor(event.getDeathMessage())) + "**";
- try {
- Bot.getGameChatChannel().sendMessage(chatMessage).queue();
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(chatMessage);
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerGameModeChange.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerGameModeChange.java
deleted file mode 100644
index c6e7eba..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerGameModeChange.java
+++ /dev/null
@@ -1,28 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import io.github.stonley890.dreamvisitor.functions.Flight;
-import org.bukkit.Bukkit;
-import org.bukkit.GameMode;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.PlayerGameModeChangeEvent;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenPlayerGameModeChange implements Listener {
-
- @EventHandler
- public void onPlayerGameModeChangeEvent(@NotNull PlayerGameModeChangeEvent event) {
-
- Player player = event.getPlayer();
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- Flight.setupFlight(player);
-
- if (memory.autoinvswap && ((player.getGameMode().equals(GameMode.SURVIVAL) && event.getNewGameMode().equals(GameMode.CREATIVE)) || (player.getGameMode().equals(GameMode.CREATIVE) && event.getNewGameMode().equals(GameMode.SURVIVAL)))) Bukkit.dispatchCommand(player, "invswap");
-
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerJoin.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerJoin.java
deleted file mode 100644
index 39d0fd7..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerJoin.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.data.PlayerTribe;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import io.github.stonley890.dreamvisitor.data.Tribe;
-import io.github.stonley890.dreamvisitor.functions.Sandbox;
-import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
-import net.luckperms.api.model.user.User;
-import net.md_5.bungee.api.ChatColor;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.PlayerJoinEvent;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenPlayerJoin implements Listener {
-
- @EventHandler
- public void onPlayerJoinEvent(@NotNull PlayerJoinEvent event) {
-
- final Player player = event.getPlayer();
-
- // Edit player list name if staff
- final User lpUser = Dreamvisitor.getLuckPerms().getUserManager().getUser(player.getUniqueId());
- if (lpUser != null) {
-
- // Get the player's tribe
- Tribe tribeOfPlayer = PlayerTribe.getTribeOfPlayer(player.getUniqueId());
- // Create a variable that represents the color to set the player's name to
- ChatColor tribeColor;
- // If the player has a tribe, set it to tribe color
- // If not, set to white.
- if (tribeOfPlayer != null) {
- tribeColor = tribeOfPlayer.getColor();
- } else {
- tribeColor = ChatColor.WHITE;
- }
-
- String prefix = lpUser.getCachedData().getMetaData().getPrefix();
- if (prefix != null) player.setPlayerListName(prefix.replace('&', 'ยง') + tribeColor + player.getName());
- }
-
- // Enable flight
- if (player.hasPermission("dreamvisitor.fly")) {
- player.setAllowFlight(true);
- }
-
- // Send join messages
- String chatMessage = "**" + Bot.escapeMarkdownFormatting(ChatColor.stripColor(player.getName())) + " joined the game**";
- try {
- Bot.getGameChatChannel().sendMessage(chatMessage).queue();
- } catch (InsufficientPermissionException e) {
- Bukkit.getLogger().warning("Dreamvisitor does not have sufficient permissions to send messages in game chat channel: " + e.getMessage());
- }
- Bot.sendLog(chatMessage);
-
- PlayerMemory memory = PlayerUtility.getPlayerMemory(player.getUniqueId());
-
- if (memory.sandbox) {
- boolean sandboxerOnline = false;
- for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) {
- if (onlinePlayer.hasPermission("dreamvisitor.sandbox")) {
- sandboxerOnline = true;
- onlinePlayer.sendMessage(Dreamvisitor.PREFIX + player.getName() + " is currently in sandbox mode.");
- }
- }
- if (!sandboxerOnline) Sandbox.disableSandbox(player);
- }
-
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerMoveEvent.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerMoveEvent.java
deleted file mode 100644
index 624a8b0..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerMoveEvent.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.functions.Flight;
-import org.bukkit.GameMode;
-import org.bukkit.Location;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.PlayerMoveEvent;
-import org.jetbrains.annotations.NotNull;
-
-import java.util.Objects;
-
-public class ListenPlayerMoveEvent implements Listener {
-
- @EventHandler
- public void onPlayerMove(@NotNull PlayerMoveEvent event) {
-
- Player player = event.getPlayer();
- if (event.getTo() == null) return;
-
- if (player.isFlying() && !Flight.inFlightGameMode(player)) {
- // Remove energy if flying
- try {
- Double energy = Flight.energy.get(player);
-
- // Return if worlds are different
- if (!Objects.equals(event.getTo().getWorld(), event.getFrom().getWorld())) return;
-
- // Calculate energy to remove
- double energyToRemove = getEnergyToRemove(event);
-
- energy -= energyToRemove;
-
- if (energy < 0) energy = 0.0;
- Flight.energy.put(player, energy);
- } catch (NullPointerException e) {
- Flight.energy.put(player, Flight.energyCapacity);
- }
- }
- }
-
- private static double getEnergyToRemove(@NotNull PlayerMoveEvent event) {
- double energyToRemove;
- Location from2d = event.getFrom().clone();
- from2d.setY(0);
- Location to2d = Objects.requireNonNull(event.getTo()).clone();
- to2d.setY(0);
-
- double distance2d = from2d.distance(to2d);
- distance2d = Math.abs(distance2d);
-
- double fromY = event.getFrom().getY();
- double toY = event.getTo().getY();
-
- double distanceY = toY - fromY;
- if (distanceY < 0) distanceY = 0;
-
- double flightEnergyDepletionXYMultiplier = Dreamvisitor.getPlugin().getConfig().getDouble("flightEnergyDepletionXYMultiplier");
- double flightEnergyDepletionYMultiplier = Dreamvisitor.getPlugin().getConfig().getDouble("flightEnergyDepletionYMultiplier");
- energyToRemove = distance2d * flightEnergyDepletionXYMultiplier + distanceY * flightEnergyDepletionYMultiplier;
- return energyToRemove;
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerQuit.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerQuit.java
deleted file mode 100644
index f365219..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenPlayerQuit.java
+++ /dev/null
@@ -1,82 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.PlayerMemory;
-import io.github.stonley890.dreamvisitor.functions.Sandbox;
-import net.md_5.bungee.api.ChatColor;
-import org.bukkit.Bukkit;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.player.PlayerQuitEvent;
-
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.data.PlayerUtility;
-import org.jetbrains.annotations.NotNull;
-
-import java.io.IOException;
-
-public class ListenPlayerQuit implements Listener {
-
- @EventHandler
- @SuppressWarnings({"null"})
- public void onPlayerQuitEvent(@NotNull PlayerQuitEvent event) {
-
- Player player = event.getPlayer();
-
- // Send player quits to Discord
- String chatMessage = "**" + Bot.escapeMarkdownFormatting(ChatColor.stripColor(player.getName())) + " left the game**";
- Bot.getGameChatChannel().sendMessage(chatMessage).queue();
- Bot.sendLog(chatMessage);
-
- PlayerMemory memory = PlayerUtility.getPlayerMemory(event.getPlayer().getUniqueId());
-
- if (memory.sandbox) {
- for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) {
- if (onlinePlayer.hasPermission("dreamvisitor.sandbox")) {
- onlinePlayer.sendMessage(Dreamvisitor.PREFIX + event.getPlayer().getName() + " left while in sandbox mode.");
- }
- }
- }
-
- try {
- PlayerUtility.savePlayerMemory(player.getUniqueId());
- PlayerUtility.clearPlayerMemory(player.getUniqueId());
- } catch (IOException e) {
- Bukkit.getLogger().severe("Unable to save player memory! Does the server have write access? Player memory will remain in memory. " + e.getMessage());
- }
-
- Dreamvisitor.debug("Checking sandbox.");
-
- Bukkit.getScheduler().runTask(Dreamvisitor.getPlugin(), () -> {
-
- Dreamvisitor.debug("Task start.");
-
- // Check for sandboxed players
- boolean moderatorOnline = false;
- for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
- Dreamvisitor.debug("Is " + onlinePlayer.getName() + " moderator?");
- if (onlinePlayer.hasPermission("dreamvisitor.sandbox")) {
- Dreamvisitor.debug("Yes! All good.");
- moderatorOnline = true;
- break;
- }
- }
- if (!moderatorOnline) {
- Dreamvisitor.debug("No mods online! Gotta disable sandboxed.");
- for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
- Dreamvisitor.debug("Is " + onlinePlayer + " sandboxed?");
- if (PlayerUtility.getPlayerMemory(onlinePlayer.getUniqueId()).sandbox) {
- Dreamvisitor.debug("Yes. Disabling.");
- Sandbox.disableSandbox(onlinePlayer);
- onlinePlayer.sendMessage("You are no longer in Sandbox Mode because there are no sandbox managers available.");
- }
- }
- }
- });
-
-
-
- }
-
-}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenSignChangeEvent.java b/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenSignChangeEvent.java
deleted file mode 100644
index 70fae15..0000000
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/listeners/ListenSignChangeEvent.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package io.github.stonley890.dreamvisitor.listeners;
-
-import com.earth2me.essentials.Essentials;
-import net.md_5.bungee.api.ChatColor;
-import org.bukkit.Bukkit;
-import org.bukkit.block.Block;
-import org.bukkit.entity.Player;
-import org.bukkit.event.EventHandler;
-import org.bukkit.event.Listener;
-import org.bukkit.event.block.SignChangeEvent;
-import org.jetbrains.annotations.NotNull;
-
-public class ListenSignChangeEvent implements Listener {
-
- @EventHandler
- public void onSignChangeEvent(@NotNull SignChangeEvent event) {
- if (event.isCancelled()) return;
- Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
- if (ess == null) return;
- Player editor = event.getPlayer();
- if (editor.isOp()) return;
-
- Block block = event.getBlock();
- String[] lines = event.getLines();
-
- boolean empty = true;
- for (String line : lines) {
- if (!line.isBlank()) {
- empty = false;
- break;
- }
- }
- if (empty) return;
-
- String message = ChatColor.GOLD + editor.getName() + " placed or edited a sign at " + block.getX() + ", " + block.getY() + ", " + block.getZ() + " in " + block.getWorld().getName() + ":\n" + ChatColor.RESET
- + lines[0] + "\n" + lines[1] + "\n" + lines[2] + "\n" + lines[3] + "\n";
-
- for (Player player : Bukkit.getOnlinePlayers()) {
- if (ess.getUser(player).isSocialSpyEnabled())
- player.sendMessage(message);
- }
- Bukkit.getLogger().info(ChatColor.stripColor(message));
- }
-
-}
diff --git a/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/Dreamvisitor.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/Dreamvisitor.java
new file mode 100644
index 0000000..a889298
--- /dev/null
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/Dreamvisitor.java
@@ -0,0 +1,416 @@
+package org.woftnw.dreamvisitor;
+
+import com.sk89q.worldguard.WorldGuard;
+import com.sk89q.worldguard.protection.flags.Flag;
+import com.sk89q.worldguard.protection.flags.StateFlag;
+import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
+import com.sk89q.worldguard.protection.flags.registry.FlagRegistry;
+import com.sk89q.worldguard.session.SessionManager;
+import dev.jorel.commandapi.CommandAPI;
+import dev.jorel.commandapi.CommandAPIBukkitConfig;
+import dev.jorel.commandapi.CommandAPICommand;
+import dev.jorel.commandapi.CommandTree;
+import org.bukkit.plugin.IllegalPluginAccessException;
+import org.woftnw.dreamvisitor.commands.*;
+import org.woftnw.dreamvisitor.data.*;
+import org.woftnw.dreamvisitor.data.repository.*;
+import org.woftnw.dreamvisitor.data.type.ServerCommand;
+import org.woftnw.dreamvisitor.functions.*;
+import org.woftnw.dreamvisitor.functions.worldguard.DragonFlightFlag;
+import org.woftnw.dreamvisitor.functions.worldguard.WitherFlag;
+import org.woftnw.dreamvisitor.listeners.*;
+import org.woftnw.dreamvisitor.pb.PocketBase;
+import org.woftnw.dreamvisitor.util.ConfigKey;
+import net.luckperms.api.LuckPerms;
+import org.apache.logging.log4j.LogManager;
+import org.bukkit.Bukkit;
+import org.bukkit.Location;
+import org.bukkit.plugin.PluginManager;
+import org.bukkit.plugin.RegisteredServiceProvider;
+import org.bukkit.plugin.java.JavaPlugin;
+import org.bukkit.scheduler.BukkitRunnable;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+import java.util.*;
+import java.util.logging.Level;
+
+@SuppressWarnings({"null"})
+public class Dreamvisitor extends JavaPlugin {
+
+ private static final org.apache.logging.log4j.core.Logger logger = (org.apache.logging.log4j.core.Logger) LogManager
+ .getRootLogger();
+ public static Dreamvisitor PLUGIN;
+ public static LuckPerms luckperms;
+ public static String MOTD = null;
+ public static Location hubLocation;
+ public static boolean debugMode;
+ private static ConsoleLogger appender;
+
+ PocketBase pocketBase;
+
+ RepositoryManager repositoryManager;
+
+ public static StateFlag DRAGON_FLIGHT;
+ public static StateFlag WITHER;
+
+ public static Dreamvisitor getPlugin() {
+ return PLUGIN;
+ }
+
+ @NotNull
+ public static LuckPerms getLuckPerms() throws NullPointerException {
+ RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class);
+ LuckPerms luckPerms;
+ if (provider != null)
+ luckPerms = provider.getProvider();
+ else {
+ throw new NullPointerException("LuckPerms cannot be found.");
+ }
+ return luckPerms;
+ }
+
+ @Override
+ public void onLoad() {
+ // Register WorldGuard flags
+ try {
+ // Get registry
+ FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry();
+ // Create and register dragon-flight flag
+ try {
+ StateFlag flag = new StateFlag("dragon-flight", true);
+ registry.register(flag);
+ DRAGON_FLIGHT = flag;
+
+ } catch (FlagConflictException e) {
+ Flag> existing = registry.get("dragon-flight");
+ if (existing instanceof StateFlag) {
+ DRAGON_FLIGHT = (StateFlag) existing;
+ } else {
+ getLogger()
+ .severe("A flag with the name dragon-flight already exists! Some other plugin claimed it already :(");
+ }
+ }
+ // Create and register dragon-flight flag
+ try {
+ StateFlag flag = new StateFlag("wither", true);
+ registry.register(flag);
+ WITHER = flag;
+
+ } catch (FlagConflictException e) {
+ Flag> existing = registry.get("wither");
+ if (existing instanceof StateFlag) {
+ WITHER = (StateFlag) existing;
+ } else {
+ getLogger().severe("A flag with the name wither already exists! Some other plugin claimed it already :(");
+ }
+ }
+ } catch (NoClassDefFoundError e) {
+ getLogger().warning("WorldGuard is not installed, so no flags will be created.");
+ } catch (IllegalStateException e) {
+ getLogger().warning("New WorldGuard flags cannot be registered at this time: " + e.getMessage());
+ }
+ }
+
+ @Override
+ public void onEnable() {
+
+ PLUGIN = this;
+
+ // Can't use debug messages until debug mode is enabled, so these first two are normal info messages.
+
+ getLogger().info("Checking local config file...");
+ checkConfig();
+
+ // Create PocketBase client from config
+ getLogger().info("Initializing PocketBase client...");
+ String baseUrl = getConfig().getString("pocketbaseUrl", "http://127.0.0.1:8090/");
+ String configId = getConfig().getString("pocketbaseConfigId", "");
+ String token = getConfig().getString("pocketbaseToken", "");
+ boolean useRealtime = getConfig().getBoolean("pocketbaseUseRealtime", true);
+
+ if (baseUrl.isEmpty() || configId.isEmpty()) {
+ getLogger().severe("PocketBase URL or Config ID is not defined. Check the config and restart the server. Dreamvisitor is disabling to prevent issues.");
+ Bukkit.getPluginManager().disablePlugin(this);
+ return;
+ }
+
+ getLogger().info("Initialized PocketBase client");
+ Map pbConfig = new HashMap<>();
+ pbConfig.put("pocketbaseUrl", baseUrl);
+ pbConfig.put("pocketbaseToken", token);
+ pocketBase = PocketBase.fromConfig(pbConfig);
+
+ getLogger().info("Initializing PocketBase config loader...");
+ try {
+ Config.init(pocketBase, baseUrl, configId, token, useRealtime);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ getLogger().info("Configuration fetched. Starting enable.");
+
+ debugMode = Config.get(ConfigKey.DEBUG);
+ Messager.debug("Debug mode is enabled.");
+
+ Messager.debug("Ensuring auto-restart is disabled...");
+ if (Config.get(ConfigKey.AUTO_RESTART)) Config.set(ConfigKey.AUTO_RESTART, false);
+
+ Messager.debug("Setting up repositories...");
+ repositoryManager = new RepositoryManager(pocketBase);
+
+ // Set up files. This must happen first because setting up commands require some files to exist.
+
+ Messager.debug("Creating data folder...");
+ boolean directoryCreated = getDataFolder().mkdir();
+ if (!directoryCreated)
+ Messager.debug("Dreamvisitor did not create a data folder. It may already exist.");
+ saveDefaultConfig();
+
+ Messager.debug("Initializing mail.yml");
+ try {
+ Mail.init();
+ } catch (IOException e) {
+ getLogger().warning("Unable to mail locations from " + PlayerTribe.file + ": " + e.getMessage());
+ }
+
+ Messager.debug("Initializing player-tribes.yml");
+ try {
+ PlayerTribe.setup();
+ } catch (IOException e) {
+ getLogger().warning("Unable to load tribes from " + PlayerTribe.file + ": " + e.getMessage());
+ }
+
+ Messager.debug("Initializing energy");
+ Flight.init();
+
+ Messager.debug("Initializing command scheduler");
+ CommandScheduler.getInstance().loadConfig();
+
+ Messager.debug("Initializing badwords.yml");
+ try {
+ BadWords.init();
+ } catch (IOException e) {
+ getLogger().warning("Unable to load bad words from " + BadWords.file + ": " + e.getMessage());
+ }
+
+ // Set up listeners and commands
+
+ Messager.debug("Registering listeners...");
+ registerListeners();
+
+ List commands = new ArrayList<>();
+ commands.add(new CmdAdminRadio());
+ commands.add(new CmdHub());
+ commands.add(new CmdPanic());
+ commands.add(new CmdRadio());
+ commands.add(new CmdSethub());
+ commands.add(new CmdSoftwhitelist());
+ commands.add(new CmdTagRadio());
+ commands.add(new CmdZoop());
+ commands.add(new CmdUser());
+ commands.add(new CmdTribeUpdate());
+ commands.add(new CmdUnwax());
+ commands.add(new CmdInvSwap());
+ commands.add(new CmdDvset());
+ commands.add(new CmdSetmotd());
+ commands.add(new CmdSynctime());
+ commands.add(new CmdSandbox());
+ commands.add(new CmdMoonglobe());
+ commands.add(new CmdSetback());
+ commands.add(new CmdParcel());
+ commands.add(new CmdDreamvisitor());
+ commands.add(new CmdChatback());
+ commands.add(new CmdVelocity());
+ commands.add(new CmdSchedule());
+
+ // CommandAPI is shaded into Dreamvisitor, so it must be loaded and enabled.
+ Messager.debug("Loading the CommandAPI...");
+ CommandAPI.onLoad(new CommandAPIBukkitConfig(this).silentLogs(!debugMode));
+ Messager.debug("Enabling the CommandAPI...");
+ CommandAPI.onEnable();
+ Messager.debug("Registering " + commands.size() + " commands...");
+ registerCommands(commands);
+
+ // Set up misc
+
+ Messager.debug("Initializing LuckPerms API...");
+ RegisteredServiceProvider provider = Bukkit.getServicesManager().getRegistration(LuckPerms.class);
+ if (provider != null)
+ luckperms = provider.getProvider();
+
+ Messager.debug("Registering WorldGuard flag handlers...");
+ SessionManager sessionManager = WorldGuard.getInstance().getPlatform().getSessionManager();
+ sessionManager.registerHandler(DragonFlightFlag.FACTORY, null);
+ sessionManager.registerHandler(WitherFlag.FACTORY, null);
+
+ Messager.debug("Setting up console logging...");
+ appender = new ConsoleLogger();
+ logger.addAppender(appender);
+
+ Messager.debug("Setting up schedules...");
+
+ // Fail old commands still sent in PocketBase
+ List oldCommands = getRepositoryManager().getServerCommandsRepository().getByStatus(ServerCommand.Status.SENT);
+ for (ServerCommand command : oldCommands) {
+ command.setStatus(ServerCommand.Status.FAILED);
+ getRepositoryManager().getServerCommandsRepository().update(command);
+ }
+
+ final CommandRunner commandRunner = new CommandRunner();
+
+ Runnable runCommandsAsync = new BukkitRunnable() {
+ @Override
+ public void run() {
+ commandRunner.run();
+ }
+ };
+
+ Runnable autoRestarts = new BukkitRunnable() {
+ @Override
+ public void run() {
+ try {
+ Config.loadConfig();
+ } catch (IOException e) {
+ getLogger().warning("Unable to load configuration!");
+ }
+
+ if (AutoRestart.isAutoRestart() && Bukkit.getOnlinePlayers().isEmpty()) {
+ AutoRestart.sendAutoRestartMessage();
+ getLogger().info("Restarting the server as scheduled.");
+ getServer().restart();
+ }
+
+ long maxMemory = Runtime.getRuntime().maxMemory();
+ long freeMemory = Runtime.getRuntime().freeMemory();
+ double freeMemoryPercent = ((double) freeMemory / maxMemory) * 100;
+ if (freeMemoryPercent <= 10) {
+ AutoRestart.enableAutoRestart(null);
+ getLogger()
+ .warning("Dreamvisitor scheduled a restart because free memory usage is at or less than 10%.");
+ }
+ }
+ };
+
+ Runnable tickMoonglobe = Moonglobe::tick;
+
+ Runnable checkInactivityTax = new BukkitRunnable() {
+ @Override
+ public void run() {
+ InactivityTax.tax();
+ }
+ };
+
+ Runnable tickFlight = Flight::tick;
+
+ // Run commands every two seconds
+ Bukkit.getScheduler().runTaskTimerAsynchronously(this, runCommandsAsync, 20, 40);
+
+ // Tick moon globes
+ Bukkit.getScheduler().runTaskTimer(this, tickMoonglobe, 0, 0);
+
+ // Check for auto restart every minute
+ Bukkit.getScheduler().runTaskTimer(this, autoRestarts, 200, 1200);
+
+ // Tick flight
+ Bukkit.getScheduler().runTaskTimer(this, tickFlight, 0, 1);
+
+ // Check inactivity tax every day
+ Bukkit.getScheduler().runTaskTimer(this, checkInactivityTax, 200, 24 * 60 * 60 * 20);
+
+ getLogger().log(Level.INFO, "Dreamvisitor has been enabled.");
+
+ }
+
+ /**
+ * Checks the config.yml file and sets default values if they do not exist.
+ */
+ private void checkConfig() {
+ if (!getConfig().contains("pocketbaseUrl")) {
+ getConfig().set("pocketbaseUrl", "http://127.0.0.1:8090/");
+ }
+ if (!getConfig().contains("pocketbaseConfigId")) {
+ getConfig().set("pocketbaseConfigId", "record_id_here");
+ }
+ if (!getConfig().contains("pocketbaseToken")) {
+ getConfig().set("pocketbaseToken", "your_admin_token_here");
+ }
+ if (!getConfig().contains("pocketbaseUseRealtime")) {
+ getConfig().set("pocketbaseUseRealtime", true);
+ }
+
+ saveConfig();
+ }
+
+ /**
+ * Registers listeners so that they can receive events.
+ */
+ private void registerListeners() {
+ PluginManager pluginManager = getServer().getPluginManager();
+ pluginManager.registerEvents(new ListenPlayerChat(), this);
+ pluginManager.registerEvents(new ListenPlayerCmdPreprocess(), this);
+ pluginManager.registerEvents(new ListenPlayerDeath(), this);
+ pluginManager.registerEvents(new ListenPlayerJoin(), this);
+ pluginManager.registerEvents(new ListenPlayerLogin(), this);
+ pluginManager.registerEvents(new ListenPlayerQuit(), this);
+ pluginManager.registerEvents(new ListenPlayerGameModeChange(), this);
+ pluginManager.registerEvents(new ListenServerPing(), this);
+ pluginManager.registerEvents(new Sandbox(), this);
+ pluginManager.registerEvents(new ListenTimeSkip(), this);
+ pluginManager.registerEvents(new ListenSignChange(), this);
+ pluginManager.registerEvents(new ListenPlayerToggleFlight(), this);
+ pluginManager.registerEvents(new ListenEntityToggleGlide(), this);
+ pluginManager.registerEvents(new ListenPlayerChangedWorld(), this);
+ pluginManager.registerEvents(new ListenPlayerRespawn(), this);
+ pluginManager.registerEvents(new ListenCreatureSpawn(), this);
+ }
+
+ /**
+ * Registers commands using CommandAPI.
+ */
+ private void registerCommands(@NotNull List commands) throws NullPointerException {
+ for (DVCommand command : commands) {
+ if (command.getCommand() instanceof CommandAPICommand apiCommand) {
+ apiCommand.register(this);
+ } else if (command.getCommand() instanceof CommandTree apiCommand) {
+ apiCommand.register(this);
+ }
+ }
+ }
+
+ @Override
+ public void onDisable() {
+
+ // Disable CommandAPI
+ CommandAPI.onDisable();
+
+ // Shutdown the realtime updater
+ RealtimeConfigUpdater.shutdown();
+
+ // Remove any active moon globes
+ for (Moonglobe moonglobe : Moonglobe.activeMoonglobes)
+ moonglobe.remove(null);
+
+ // Save and shutdown the Command Scheduler
+ try {
+ CommandScheduler.getInstance().saveConfig();
+ CommandScheduler.getInstance().stopScheduler();
+ } catch (IllegalPluginAccessException ignored) {
+ // This might happen if Dreamvisitor fails to start correctly
+ }
+
+ // Unattach the server logger
+ try {
+ logger.removeAppender(appender);
+ } catch (NullPointerException ignored) {
+ // This might happen if Dreamvisitor fails to start correctly
+ }
+
+ // TODO: Send shutdown signal to PocketBase.
+
+ getLogger().info("Dreamvisitor has been disabled.");
+ }
+
+ public RepositoryManager getRepositoryManager() {
+ return repositoryManager;
+ }
+}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdAdminRadio.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdAdminRadio.java
similarity index 79%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdAdminRadio.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdAdminRadio.java
index 739d2ca..9cb84be 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdAdminRadio.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdAdminRadio.java
@@ -1,12 +1,12 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
import dev.jorel.commandapi.ExecutableCommand;
import dev.jorel.commandapi.arguments.GreedyStringArgument;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.functions.Radio;
+import org.woftnw.dreamvisitor.functions.Messager;
+import org.woftnw.dreamvisitor.functions.Radio;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
@@ -22,11 +22,11 @@ public class CmdAdminRadio implements DVCommand {
.withHelp("Use the admin radio.", "Sends a message to all operators.")
.withArguments(new GreedyStringArgument("message"))
.executesNative(((sender, args) -> {
- String message = (String) args.get("message");
+ final String message = (String) args.get("message");
- Dreamvisitor.debug(sender.getClass().getName());
+ Messager.debug(sender.getClass().getName());
- CommandSender callee = sender.getCallee();
+ final CommandSender callee = sender.getCallee();
if (callee instanceof Player player) {
Radio.buildMessage(message, player.getName(), getCommand().getName(), null);
} else if (callee instanceof ConsoleCommandSender) {
diff --git a/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdChatback.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdChatback.java
new file mode 100644
index 0000000..39ec2b2
--- /dev/null
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdChatback.java
@@ -0,0 +1,40 @@
+package org.woftnw.dreamvisitor.commands;
+
+import dev.jorel.commandapi.CommandAPICommand;
+import dev.jorel.commandapi.ExecutableCommand;
+import dev.jorel.commandapi.arguments.LongArgument;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import org.woftnw.dreamvisitor.functions.Chatback;
+import net.md_5.bungee.api.ChatColor;
+import org.jetbrains.annotations.NotNull;
+
+public class CmdChatback implements DVCommand {
+ @NotNull
+ @Override
+ public ExecutableCommand, ?> getCommand() {
+ return new CommandAPICommand("chatback")
+ .withOptionalArguments(new LongArgument("messageID"))
+ .executesPlayer((sender, args) -> {
+ Long messageID = (Long) args.get(0);
+ if (messageID == null) {
+ sender.sendMessage(Component.text("Canceled chatback.").color(NamedTextColor.GRAY));
+ Chatback.nextChatback.remove(sender);
+ } else {
+ sender.sendMessage(Component.text("Your next message will be a reply. Run /chatback to cancel.").color(NamedTextColor.GRAY));
+ // TODO: Implement chatback.
+// Bot.getGameChatChannel().retrieveMessageById(messageID).queue(message -> {
+// User author = message.getAuthor();
+// Bot.getGameChatChannel().getGuild().retrieveMemberById(author.getId()).queue(member -> {
+// Chatback.nextChatback.put(sender, new Chatback.ReplyMessage(
+// member.getEffectiveName(),
+// author.getName(),
+// message.getContentRaw(),
+// message.getIdLong()
+// ));
+// });
+// });
+ }
+ });
+ }
+}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdDreamvisitor.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDreamvisitor.java
similarity index 93%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdDreamvisitor.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDreamvisitor.java
index 335f1e4..f8457a3 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdDreamvisitor.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDreamvisitor.java
@@ -1,13 +1,13 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
import dev.jorel.commandapi.arguments.*;
import dev.jorel.commandapi.executors.CommandArguments;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.Tribe;
-import io.github.stonley890.dreamvisitor.data.TribeUtil;
-import net.md_5.bungee.api.ChatColor;
+import org.woftnw.dreamvisitor.Dreamvisitor;
+import org.woftnw.dreamvisitor.data.Tribe;
+import org.woftnw.dreamvisitor.data.TribeUtil;
+import org.woftnw.dreamvisitor.functions.Messager;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.NotNull;
@@ -25,14 +25,14 @@ public class CmdDreamvisitor implements DVCommand {
public CommandAPICommand getCommand() {
return new CommandAPICommand("dreamvisitor")
.executes((sender, args) -> {
- sender.sendMessage(ChatColor.BLUE + "Dreamvisitor " + Dreamvisitor.getPlugin().getDescription().getVersion() + "\nDeveloped by Stonley890\nOpen source at https://github.com/Stonley890/Dreamvisitor");
+ Messager.send(sender, "Dreamvisitor " + Dreamvisitor.getPlugin().getPluginMeta().getVersion() + "\nDeveloped by Bog\nOpen source at https://github.com/WOFTNW/Dreamvisitor");
})
.withSubcommand(new CommandAPICommand("reload")
.withPermission(CommandPermission.OP)
.withHelp("Reload Dreamvisitor.", "Reload Dreamvisitor's config file from disk.")
.executes(((sender, args) -> {
Dreamvisitor.getPlugin().reloadConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Configuration reloaded.");
+ Messager.send(sender, "Configuration reloaded.");
}))
)
.withSubcommand(new CommandAPICommand("manage")
@@ -110,12 +110,12 @@ public CommandAPICommand getCommand() {
@NotNull Tribe tribe = (Tribe) Objects.requireNonNull(args.get("tribe"));
int tribeIndex = TribeUtil.indexOf(tribe);
List emblems = plugin.getConfig().getLongList("triberoles");
- if (roleId == null) sender.sendMessage(Dreamvisitor.PREFIX + "role of " + tribe.getName() + " is currently set to\n" + emblems.get(tribeIndex));
+ if (roleId == null) Messager.send(sender, "Role of " + tribe.getName() + " is currently set to\n" + emblems.get(tribeIndex));
else {
emblems.set(tribeIndex, roleId);
plugin.getConfig().set("triberoles", emblems);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set role of " + tribe.getName() + " to\n" + roleId);
+ Messager.send(sender, "Set role of " + tribe.getName() + " to\n" + roleId);
}
}),
new CommandAPICommand("chatPaused")
@@ -168,7 +168,7 @@ public CommandAPICommand getCommand() {
Location location = plugin.getConfig().getLocation(key);
String reply = "none";
if (location != null) reply = location.toString();
- sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + reply);
+ Messager.send(sender, key + " is currently set to\n" + reply);
}),
new CommandAPICommand("log-console")
.withHelp("Set log-console.", """
@@ -443,62 +443,62 @@ Takes the ratio (between 0 and 1) of the distance to the maximum distance betwee
private void configBoolean(CommandSender sender, @NotNull CommandArguments args, String key) {
Boolean value = (Boolean) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getBoolean(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getBoolean(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getBoolean(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getBoolean(key));
}
}
private void configInt(CommandSender sender, @NotNull CommandArguments args, String key) {
Integer value = (Integer) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getInt(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getInt(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getInt(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getInt(key));
}
}
private void configDouble(CommandSender sender, @NotNull CommandArguments args, String key) {
Double value = (Double) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getDouble(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getDouble(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getDouble(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getDouble(key));
}
}
private void configLong(CommandSender sender, @NotNull CommandArguments args, String key) {
Long value = (Long) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getLong(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getLong(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getLong(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getLong(key));
}
}
private void configString(CommandSender sender, @NotNull CommandArguments args, String key) {
String value = (String) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getString(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getString(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getString(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getString(key));
}
}
@SuppressWarnings("unchecked")
private void configLongList(CommandSender sender, @NotNull CommandArguments args, String key) {
List value = (List) args.get(key);
- if (value == null) sender.sendMessage(Dreamvisitor.PREFIX + key + " is currently set to\n" + plugin.getConfig().getLongList(key));
+ if (value == null) Messager.send(sender, key + " is currently set to\n" + plugin.getConfig().getLongList(key));
else {
plugin.getConfig().set(key, value);
plugin.saveConfig();
- sender.sendMessage(Dreamvisitor.PREFIX + "Set " + key + " to\n" + plugin.getConfig().getLongList(key));
+ Messager.send(sender, "Set " + key + " to\n" + plugin.getConfig().getLongList(key));
}
}
}
diff --git a/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDvset.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDvset.java
new file mode 100644
index 0000000..a384621
--- /dev/null
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdDvset.java
@@ -0,0 +1,242 @@
+package org.woftnw.dreamvisitor.commands;
+
+import dev.jorel.commandapi.*;
+import dev.jorel.commandapi.arguments.StringArgument;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.event.ClickEvent;
+import net.kyori.adventure.text.event.HoverEvent;
+import net.kyori.adventure.text.format.NamedTextColor;
+import net.kyori.adventure.text.format.TextDecoration;
+import org.woftnw.dreamvisitor.data.PlayerUtility;
+import org.woftnw.dreamvisitor.data.type.DVUser;
+import org.woftnw.dreamvisitor.functions.Messager;
+import org.bukkit.command.CommandSender;
+import org.bukkit.entity.Player;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Objects;
+
+public class CmdDvset implements DVCommand {
+
+ private static void sendUserGui(@NotNull Player player) {
+
+ DVUser user = PlayerUtility.getUser(player);
+
+ Component message = Component.text("User Options ");
+
+ if (player.hasPermission("dreamvisitor.set.discord")) {
+ message = message.append(Component.text("\n\nDiscord Visibility: ").color(NamedTextColor.WHITE))
+ .append(Component.text("\nWhether to show messages from Discord's chat bridge.").color(NamedTextColor.GRAY))
+ .append(Component.text("\n[").color(NamedTextColor.DARK_GRAY))
+ .append(booleanToggle(user.isShowDiscordOn(), "discord"))
+ .append(Component.text("]").color(NamedTextColor.DARK_GRAY));
+ }
+
+ if (player.hasPermission("dreamvisitor.set.flight")) {
+ message = message.append(Component.text("\n\nFlight Disabled: ").color(NamedTextColor.WHITE))
+ .append(Component.text("\nWhether Flight Mode cannot be activated.").color(NamedTextColor.GRAY))
+ .append(Component.text("\n[").color(NamedTextColor.DARK_GRAY))
+ .append(booleanToggle(user.isFlightDisabled(), "flight"))
+ .append(Component.text("]").color(NamedTextColor.DARK_GRAY));
+ }
+
+ if (player.hasPermission("dreamvisitor.set.zoop")) {
+ message = message.append(Component.text("\n\nDiscord Vanish: ").color(NamedTextColor.WHITE))
+ .append(Component.text("\nWhether to appear offline in Dreamvisitor.").color(NamedTextColor.GRAY))
+ .append(Component.text("\n[").color(NamedTextColor.DARK_GRAY))
+ .append(booleanToggle(user.isVanished(), "vanished"))
+ .append(Component.text("]").color(NamedTextColor.DARK_GRAY));
+ }
+
+ if (player.hasPermission("dreamvisitor.set.autoinvswap")) {
+ message = message.append(Component.text("\n\nAutomatic Inventory Swap: ").color(NamedTextColor.WHITE))
+ .append(Component.text("\nWhether to automatically swap inventories on game mode change.").color(NamedTextColor.GRAY))
+ .append(Component.text("\n[").color(NamedTextColor.DARK_GRAY))
+ .append(booleanToggle(user.isAutoInvSwapEnabled(), "autoinvswap"))
+ .append(Component.text("]").color(NamedTextColor.DARK_GRAY));
+ }
+
+ if (player.hasPermission("dreamvisitor.set.autoradio")) {
+ message = message.append(Component.text("\n\nAutomatic Radio: ").color(NamedTextColor.WHITE))
+ .append(Component.text("\nWhether to send all messages to staff radio.").color(NamedTextColor.GRAY))
+ .append(Component.text("\n[").color(NamedTextColor.DARK_GRAY))
+ .append(booleanToggle(user.isAutoRadioEnabled(), "autoradio"))
+ .append(Component.text("]").color(NamedTextColor.DARK_GRAY));
+ }
+
+ message = message.append(Component.text("\n"));
+ Messager.send(player, message);
+
+ }
+
+ /**
+ * Creates a {@link Component} representing a {@code boolean} value with a
+ * command to change it.
+ *
+ * @param value the {@code boolean} to display.
+ * @param cmdName the command to run. This will be formatted as
+ * {@code /dvset !value}
+ * @return a {@link Component} representing the value with a command to
+ * change it.
+ */
+ private static @NotNull Component booleanToggle(boolean value, String cmdName) {
+ Component toggle = Component.empty();
+
+ if (value) {
+ toggle = toggle.append(
+ Component.text("-O")
+ .decorate(TextDecoration.UNDERLINED)
+ .color(NamedTextColor.GREEN)
+ );
+ } else {
+ toggle = toggle.append(Component.text("0-").decorate(TextDecoration.UNDERLINED).color(NamedTextColor.RED));
+ }
+
+ return toggle.hoverEvent(HoverEvent.showText(
+ Component.text("Currently toggled to ")
+ .append(Component.text(String.valueOf(value).toUpperCase())).color(NamedTextColor.WHITE)
+ .append(Component.text("."))
+ )).clickEvent(ClickEvent.runCommand("/dvset " + cmdName + " " + String.valueOf(!value).toLowerCase()));
+ }
+
+ @NotNull
+ @Override
+ public CommandTree getCommand() {
+
+ return new CommandTree("dvset")
+ .withPermission(CommandPermission.fromString("dreamvisitor.userset"))
+ .withHelp("Manage settings.", "Manage your Dreamvisitor settings.")
+ .executesNative(((sender, args) -> {
+ if (sender instanceof Player player && sender.hasPermission("dreamvisitor.userset")) {
+ // Player GUI
+ sendUserGui(player);
+ } else
+ throw CommandAPI.failWithString("No options specified.");
+ }))
+ .then(new StringArgument("option")
+ .setOptional(true)
+ .executesNative((sender, args) -> {
+ String option = (String) args.get("option");
+
+ CommandSender callee = sender.getCallee();
+ if (!callee.hasPermission("dreamvisitor.userset"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+
+ DVUser user;
+
+ if (callee instanceof Player player) {
+ user = PlayerUtility.getUser(player);
+ } else
+ throw CommandAPI.failWithString("This can only be executed by a player!");
+
+ switch (Objects.requireNonNull(option)) {
+ case "discord" -> {
+ if (!player.hasPermission("dreamvisitor.set.discord"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ Messager.send(callee, Component.text("Discord Visibility is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isShowDiscordOn()).color(NamedTextColor.WHITE)));
+ }
+ case "flight" -> {
+ if (!player.hasPermission("dreamvisitor.set.flight"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ Messager.send(callee, Component.text("Flight Enabled is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isFlightDisabled()).color(NamedTextColor.WHITE)));
+ }
+ case "vanished" -> {
+ if (!player.hasPermission("dreamvisitor.set.zoop"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ Messager.send(callee, Component.text("Discord Vanish is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isVanished()).color(NamedTextColor.WHITE)));
+ }
+ case "autoinvswap" -> {
+ if (!player.hasPermission("dreamvisitor.set.autoinvswap"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ Messager.send(callee, Component.text("Automatic Inventory Swap is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isAutoInvSwapEnabled()).color(NamedTextColor.WHITE)));
+ }
+ case "autoradio" -> {
+ if (!player.hasPermission("dreamvisitor.set.autoradio"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ Messager.send(callee, Component.text("Automatic Radio is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isAutoRadioEnabled()).color(NamedTextColor.WHITE)));
+ }
+ default ->
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ }
+ })
+ .then(new StringArgument("modification")
+ .setOptional(true)
+ .executesNative(((sender, args) -> {
+ String option = (String) args.get("option");
+ String modification = (String) args.get("modification");
+
+ CommandSender callee = sender.getCallee();
+ if (!callee.hasPermission("dreamvisitor.userset"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+
+ DVUser user;
+
+ if (callee instanceof Player player) {
+ user = PlayerUtility.getUser(player);
+ } else
+ throw CommandAPI.failWithString("This can only be executed by a player!");
+
+ if (option == null || modification == null) {
+ sendUserGui(player);
+ return;
+ }
+
+ switch (option) {
+ case "discord" -> {
+ if (!player.hasPermission("dreamvisitor.set.discord"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ user.setShowDiscordMessages(Boolean.parseBoolean(modification));
+ Messager.send(callee, Component.text("Discord Visibility is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isShowDiscordOn()).color(NamedTextColor.WHITE)));
+ }
+ case "flight" -> {
+ if (!player.hasPermission("dreamvisitor.set.flight"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ user.setFlightDisabled(Boolean.parseBoolean(modification));
+ Messager.send(callee, Component.text("Flight Enabled is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isFlightDisabled()).color(NamedTextColor.WHITE)));
+ }
+ case "vanished" -> {
+ if (!player.hasPermission("dreamvisitor.set.zoop"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ user.setVanished(Boolean.parseBoolean(modification));
+
+ String chatMessage;
+ if (user.isVanished()) {
+ chatMessage = "**" + player.getName() + " left the game**";
+ } else {
+ chatMessage = "**" + player.getName() + " joined the game**";
+ }
+ // TODO: Send the message to the chat channel.
+// Bot.getGameChatChannel().sendMessage(chatMessage).queue();
+// Bot.sendLog(chatMessage);
+
+ Messager.send(callee, Component.text("Discord Vanish is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isVanished()).color(NamedTextColor.WHITE)));
+ }
+ case "autoinvswap" -> {
+ if (!player.hasPermission("dreamvisitor.set.autoinvswap"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ user.setAutoInvSwapEnabled(Boolean.parseBoolean(modification));
+ Messager.send(callee, Component.text("Automatic Inventory is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isAutoInvSwapEnabled()).color(NamedTextColor.WHITE)));
+ }
+ case "autoradio" -> {
+ if (!player.hasPermission("dreamvisitor.set.autoradio"))
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ user.setAutoRadioEnabled(Boolean.parseBoolean(modification));
+ Messager.send(callee, Component.text("Automatic Radio is currently set to ").color(NamedTextColor.GRAY)
+ .append(Component.text(user.isAutoRadioEnabled()).color(NamedTextColor.WHITE)));
+ }
+ default ->
+ throw CommandAPI.failWithString("Invalid arguments or insufficient permissions!");
+ }
+ sendUserGui(player);
+ }))));
+ }
+}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdHub.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdHub.java
similarity index 82%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdHub.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdHub.java
index 574b028..44db97a 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdHub.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdHub.java
@@ -1,4 +1,4 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.User;
@@ -6,8 +6,9 @@
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
import dev.jorel.commandapi.arguments.EntitySelectorArgument;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.functions.Mail;
+import org.woftnw.dreamvisitor.Dreamvisitor;
+import org.woftnw.dreamvisitor.functions.Mail;
+import org.woftnw.dreamvisitor.functions.Messager;
import org.bukkit.*;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
@@ -36,9 +37,9 @@ public CommandAPICommand getCommand() {
)
.executesNative(((sender, args) -> {
- Collection entitySelect = (Collection) args.get("entities");
+ final Collection entitySelect = (Collection) args.get("entities");
- CommandSender callee = sender.getCallee();
+ final CommandSender callee = sender.getCallee();
if (entitySelect != null) {
if (entitySelect.isEmpty()) {
@@ -51,7 +52,7 @@ public CommandAPICommand getCommand() {
Dreamvisitor.hubLocation = plugin.getConfig().getLocation("hubLocation");
assert Dreamvisitor.hubLocation != null;
- Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
+ final Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
for (Entity entity : entitySelect) {
@@ -66,21 +67,16 @@ public CommandAPICommand getCommand() {
}
player.teleport(Dreamvisitor.hubLocation);
- player.spawnParticle(Particle.FIREWORKS_SPARK, Dreamvisitor.hubLocation, 100);
+ player.spawnParticle(Particle.FIREWORK, Dreamvisitor.hubLocation, 100);
player.playSound(Dreamvisitor.hubLocation, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.MASTER, 0.5f, 1f);
} else entity.teleport(Dreamvisitor.hubLocation, TeleportCause.COMMAND);
}
}
- if (entitySelect.size() == 1) {
- callee.sendMessage(Dreamvisitor.PREFIX + "Teleported " + entitySelect.stream().findFirst().get().getName() + " to the hub.");
- }
- else {
- callee.sendMessage(Dreamvisitor.PREFIX + "Teleported " + entitySelect.size() + " entities to the hub.");
- }
+ Messager.send(callee, "Teleported " + Messager.nameOrCountEntity(entitySelect) + " to the hub.");
}
} else {
- if (callee instanceof Player) {
+ if (callee instanceof Player player) {
if (plugin.getConfig().getLocation("hubLocation") == null) {
throw CommandAPI.failWithString("No hub is currently set!");
} else {
@@ -88,16 +84,15 @@ public CommandAPICommand getCommand() {
Dreamvisitor.hubLocation = plugin.getConfig().getLocation("hubLocation");
assert Dreamvisitor.hubLocation != null;
- Player player = (Player) callee;
if (Mail.isPLayerDeliverer(player)) Mail.cancel(player);
- Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
+ final Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials");
if (ess != null) {
- User user = ess.getUser(player);
+ final User user = ess.getUser(player);
user.setLastLocation(player.getLocation());
}
- List leashed = new ArrayList<>();
+ final List leashed = new ArrayList<>();
for (Entity entity : player.getNearbyEntities(10, 10, 10)) {
if (entity instanceof LivingEntity livingEntity && livingEntity.isLeashed() && livingEntity.getLeashHolder().equals(player))
@@ -106,15 +101,15 @@ public CommandAPICommand getCommand() {
if (leashed.isEmpty() || !player.hasPermission("dreamvisitor.hub.leash")) {
player.teleport(Dreamvisitor.hubLocation);
- player.spawnParticle(Particle.FIREWORKS_SPARK, Dreamvisitor.hubLocation, 100);
+ player.spawnParticle(Particle.FIREWORK, Dreamvisitor.hubLocation, 100);
player.playSound(Dreamvisitor.hubLocation, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.MASTER, 0.5f,
1f);
} else {
- Location tpLocation = Dreamvisitor.hubLocation.clone().subtract(0, 14, 0);
+ final Location tpLocation = Dreamvisitor.hubLocation.clone().subtract(0, 14, 0);
player.teleport(tpLocation);
- player.spawnParticle(Particle.FIREWORKS_SPARK, tpLocation, 100);
+ player.spawnParticle(Particle.FIREWORK, tpLocation, 100);
player.playSound(tpLocation, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.MASTER, 0.5f,
1f);
for (LivingEntity entity : leashed) {
@@ -153,7 +148,7 @@ public CommandAPICommand getCommand() {
}
closest.teleport(Dreamvisitor.hubLocation);
- closest.spawnParticle(Particle.FIREWORKS_SPARK, Dreamvisitor.hubLocation, 100);
+ closest.spawnParticle(Particle.FIREWORK, Dreamvisitor.hubLocation, 100);
closest.playSound(Dreamvisitor.hubLocation, Sound.ENTITY_EXPERIENCE_ORB_PICKUP, SoundCategory.MASTER, 0.5f,
1f);
}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdInvSwap.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdInvSwap.java
similarity index 78%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdInvSwap.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdInvSwap.java
index 60f3cc0..0368328 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdInvSwap.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdInvSwap.java
@@ -1,10 +1,10 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.functions.InvSwap;
+import org.woftnw.dreamvisitor.functions.InvSwap;
+import org.woftnw.dreamvisitor.functions.Messager;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
@@ -21,7 +21,7 @@ public CommandAPICommand getCommand() {
CommandSender callee = sender.getCallee();
if (callee instanceof Player player) {
InvSwap.swapInventories(player);
- callee.sendMessage(Dreamvisitor.PREFIX + "Your inventory has been swapped!");
+ Messager.send(callee, "Your inventory has been swapped!");
} else throw CommandAPI.failWithString("This command can only be executed as a player!");
}));
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdMoonglobe.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdMoonglobe.java
similarity index 84%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdMoonglobe.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdMoonglobe.java
index 5d066cc..14efb28 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdMoonglobe.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdMoonglobe.java
@@ -1,4 +1,4 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPICommand;
@@ -6,24 +6,20 @@
import dev.jorel.commandapi.arguments.EntitySelectorArgument;
import dev.jorel.commandapi.arguments.FloatArgument;
import dev.jorel.commandapi.arguments.LocationArgument;
-import dev.jorel.commandapi.arguments.LongArgument;
import dev.jorel.commandapi.executors.CommandArguments;
import dev.jorel.commandapi.wrappers.NativeProxyCommandSender;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.functions.Moonglobe;
+import org.woftnw.dreamvisitor.functions.Messager;
+import org.woftnw.dreamvisitor.functions.Moonglobe;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
-import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
-import java.util.ArrayList;
import java.util.Collection;
-import java.util.List;
import java.util.Objects;
public class CmdMoonglobe implements DVCommand {
@@ -40,7 +36,7 @@ private static String create(@NotNull Collection players, @NotNull Locat
if (!alreadyHasGlobe) new Moonglobe(player.getUniqueId(), location, maxDistance);
}
- return (Dreamvisitor.PREFIX + "Created moon globes for " + players.size() + " players.");
+ return ("Created moon globes for " + Messager.nameOrCountPlayer(players) + ".");
}
@@ -55,7 +51,7 @@ public CommandAPICommand getCommand() {
.withArguments(new EntitySelectorArgument.ManyPlayers("players"))
.executesNative((sender, args) -> {
- Collection targets = (Collection) args.get("players");
+ final Collection targets = (Collection) args.get("players");
// Get players
assert targets != null;
@@ -66,7 +62,7 @@ public CommandAPICommand getCommand() {
}
}
- sender.sendMessage(Dreamvisitor.PREFIX + "Removed moon globes of " + targets.size() + " players.");
+ Messager.send(sender, "Removed moon globes of " + Messager.nameOrCountPlayer(targets) + ".");
})
)
.withSubcommand(new CommandAPICommand("create")
@@ -79,15 +75,15 @@ public CommandAPICommand getCommand() {
// Get players
assert targets != null;
- Location location = getLocation(sender, args);
+ final Location location = getLocation(sender, args);
// get distance
float maxDistance = 256.0f;
- Object maxDistanceArg = args.get("maxDistance");
+ final Object maxDistanceArg = args.get("maxDistance");
if (maxDistanceArg != null) maxDistance = (float) maxDistanceArg;
- sender.sendMessage(create(targets, location, maxDistance));
+ Messager.send(sender, create(targets, location, maxDistance));
})
.executesNative((sender, args) -> {
@@ -98,7 +94,7 @@ public CommandAPICommand getCommand() {
World world;
- CommandSender callee = sender.getCallee();
+ final CommandSender callee = sender.getCallee();
if (callee instanceof Player player) world = player.getWorld();
else if (callee instanceof BlockCommandSender block) world = block.getBlock().getWorld();
else world = Bukkit.getWorlds().get(0);
@@ -125,10 +121,10 @@ public CommandAPICommand getCommand() {
// get distance
float maxDistance = 256.0f;
- Object maxDistanceArg = args.get("maxDistance");
+ final Object maxDistanceArg = args.get("maxDistance");
if (maxDistanceArg != null) maxDistance = (float) maxDistanceArg;
- sender.sendMessage(create(targets, location, maxDistance));
+ Messager.send(sender, create(targets, location, maxDistance));
})
);
}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdPanic.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdPanic.java
similarity index 61%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdPanic.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdPanic.java
index 75c3b0a..adfada6 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdPanic.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdPanic.java
@@ -1,15 +1,15 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import java.util.TimerTask;
import dev.jorel.commandapi.CommandAPICommand;
-import dev.jorel.commandapi.ExecutableCommand;
+import net.kyori.adventure.text.Component;
+import org.woftnw.dreamvisitor.functions.Messager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
-import io.github.stonley890.dreamvisitor.Bot;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
+import org.woftnw.dreamvisitor.Dreamvisitor;
import org.jetbrains.annotations.NotNull;
public class CmdPanic implements DVCommand {
@@ -26,8 +26,7 @@ public CommandAPICommand getCommand() {
.executesNative((sender, args) -> {
if (!panicAsked) {
panicAsked = true;
- sender.sendMessage(Dreamvisitor.PREFIX +
- ChatColor.RED + "Are you sure you want to kick all players? Run /panic again to confirm.");
+ Messager.sendDanger(sender,"Are you sure you want to kick all players? Run /panic again to confirm.");
new java.util.Timer().schedule(new TimerTask() {
@Override
public void run() {
@@ -37,15 +36,15 @@ public void run() {
} else {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
if (!player.isOp()) {
- player.kickPlayer("Panic!");
+ player.kick(Component.text("Panic mode activated. The server is temporarily closed."));
}
}
- Dreamvisitor.playerLimit = 0;
- plugin.getConfig().set("playerlimit", 0);
+ // TODO: Set player limit through PlayerCap
+// plugin.getConfig().set("playerlimit", 0);
plugin.saveConfig();
- Bukkit.getServer().broadcastMessage(
- ChatColor.RED + "Panicked by " + sender.getName() + ".\nPlayer limit override set to 0.");
- Bot.sendLog("**Panicked by " + sender.getName());
+ Messager.broadcast(Component.text("Panicked by " + sender.getName() + ".\nPlayer limit override set to 0.", Messager.DANGER_COLOR));
+ // TODO: Send a message to the server log.
+// Bot.sendLog("**Panicked by " + sender.getName());
}
});
}
diff --git a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdParcel.java b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdParcel.java
similarity index 65%
rename from dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdParcel.java
rename to dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdParcel.java
index bb12a95..5efba10 100644
--- a/dreamvisitor/src/main/java/io/github/stonley890/dreamvisitor/commands/CmdParcel.java
+++ b/dreamvisitor/src/main/java/org/woftnw/dreamvisitor/commands/CmdParcel.java
@@ -1,12 +1,14 @@
-package io.github.stonley890.dreamvisitor.commands;
+package org.woftnw.dreamvisitor.commands;
import dev.jorel.commandapi.CommandAPI;
import dev.jorel.commandapi.CommandAPICommand;
import dev.jorel.commandapi.CommandPermission;
import dev.jorel.commandapi.arguments.*;
-import io.github.stonley890.dreamvisitor.Dreamvisitor;
-import io.github.stonley890.dreamvisitor.data.Tribe;
-import io.github.stonley890.dreamvisitor.functions.Mail;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.format.NamedTextColor;
+import org.woftnw.dreamvisitor.data.Tribe;
+import org.woftnw.dreamvisitor.functions.Mail;
+import org.woftnw.dreamvisitor.functions.Messager;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.ComponentBuilder;
import org.bukkit.Location;
@@ -39,21 +41,21 @@ public CommandAPICommand getCommand() {
.withArguments(CommandUtils.customTribeArgument("homeTribe"))
.executesNative(((sender, args) -> {
- Location location = (Location) args.get("location");
+ final Location location = (Location) args.get("location");
if (location == null) throw CommandAPI.failWithString("Location was not provided!");
- String name = (String) args.get("name");
+ final String name = (String) args.get("name");
if (name == null) throw CommandAPI.failWithString("Name was not provided!");
- Object weightArg = args.get("weight");
+ final Object weightArg = args.get("weight");
if (weightArg == null) throw CommandAPI.failWithString("Weight was not provided!");
int weight = (int) weightArg;
- Tribe tribe = (Tribe) args.get("homeTribe");
+ final Tribe tribe = (Tribe) args.get("homeTribe");
if (tribe == null) throw CommandAPI.failWithString("Tribe was not provided!");
Mail.MailLocation mailLocation = new Mail.MailLocation(location, name, weight, tribe);
Mail.saveLocation(mailLocation);
- sender.sendMessage(Dreamvisitor.PREFIX + "Added location " + name + " at " + location.getX() + " " + location.getY() + " " + location.getZ() + " in world " + Objects.requireNonNull(location.getWorld()).getName() + ".");
+ Messager.send(sender, "Added location " + name + " at " + location.getX() + " " + location.getY() + " " + location.getZ() + " in world " + Objects.requireNonNull(location.getWorld()).getName() + ".");
}))
)
.withSubcommand(new CommandAPICommand("remove")
@@ -64,31 +66,30 @@ public CommandAPICommand getCommand() {
)
.executesNative((sender, args) -> {
- String name = (String) args.get("name");
+ final String name = (String) args.get("name");
if (name == null) throw CommandAPI.failWithString("Name is null!");
- Mail.MailLocation location = Mail.getLocationByName(name);
+ final Mail.MailLocation location = Mail.getLocationByName(name);
if (location == null) throw CommandAPI.failWithString("Mail location not found.");
Mail.removeLocation(location);
- sender.sendMessage(Dreamvisitor.PREFIX + "Removed location " + location.getName());
+ Messager.send(sender, "Removed location " + location.getName());
})
)
.withSubcommand(new CommandAPICommand("list")
.executesNative((sender, args) -> {
List locations = Mail.getLocations();
- ComponentBuilder message = new ComponentBuilder(Dreamvisitor.PREFIX + "Mail Locations");
+ Component message = Component.text("Mail Locations");
for (Mail.MailLocation mailLocation : locations) {
- message.append("\n").append(mailLocation.getName()).color(net.md_5.bungee.api.ChatColor.YELLOW)
- .append("\n").reset().append(String.valueOf(mailLocation.getLocation().getX()))
- .append(" ").append(String.valueOf(mailLocation.getLocation().getY()))
- .append(" ").append(String.valueOf(mailLocation.getLocation().getZ()))
- .append(" in world ").append(Objects.requireNonNull(mailLocation.getLocation().getWorld()).getName())
- .append("\n Weight: ").append(String.valueOf(mailLocation.getWeight()))
- .append("\n Home Tribe: ").append(mailLocation.getHomeTribe().getName());
+ Location location = mailLocation.getLocation();
+ message = message.append(Component.text("\n" + mailLocation.getName(), NamedTextColor.YELLOW))
+ .append(Component.text(
+ ": " + location.getX() + " " + location.getY() + " " + location.getZ() + " in " + Objects.requireNonNull(location.getWorld()).getName() +
+ "\n Weight: " + mailLocation.getWeight() + ", Home Tribe: " + mailLocation.getHomeTribe().getName()
+ ));
}
- sender.spigot().sendMessage(message.create());
+ Messager.send(sender, message);
})
)
)
@@ -97,16 +98,16 @@ public CommandAPICommand getCommand() {
.withSubcommand(new CommandAPICommand("terminal")
.withArguments(new EntitySelectorArgument.ManyPlayers("players"))
.executesNative((sender, args) -> {
- Collection players = (Collection) args.get("players");
+ final Collection players = (Collection) args.get("players");
assert players != null;
if (players.isEmpty()) throw CommandAPI.failWithString("No players selected");
- List deliverers = Mail.getDeliverers();
- List playerList = deliverers.stream().map(Mail.Deliverer::getPlayer).toList();
+ final List