Skip to content

Commit

Permalink
👍 v1.1.1
Browse files Browse the repository at this point in the history
  • Loading branch information
Niix-Dan committed Jul 4, 2024
1 parent 065e6fd commit 1a0ba71
Show file tree
Hide file tree
Showing 9 changed files with 319 additions and 148 deletions.
113 changes: 113 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# User-specific stuff
.idea/

*.iml
*.ipr
*.iws

# IntelliJ
out/

# Compiled class file
*.class

# Log file
*.log

# BlueJ files
*.ctxt

# Package Files #
*.jar
*.war
*.nar
*.ear
*.zip
*.tar.gz
*.rar

# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon

# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

target/

pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next

release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
.mvn/wrapper/maven-wrapper.jar
.flattened-pom.xml

# Common working directory
run/
9 changes: 9 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,18 @@
<id>spigotmc-repo</id>
<url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
</repository>

</repositories>

<dependencies>
<!-- https://mvnrepository.com/artifact/org.kohsuke/github-api -->
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>github-api</artifactId>
<version>1.125</version>
</dependency>


<!-- https://mvnrepository.com/artifact/net.dv8tion/JDA -->
<dependency>
<groupId>net.dv8tion</groupId>
Expand Down
18 changes: 13 additions & 5 deletions src/main/java/niix/dan/consolediscord/Appender.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,16 @@ public Appender(ConsoleDiscord plugin, JDA j) {

public void append(LogEvent event) {
String message = event.getMessage().getFormattedMessage();
message = "["+ LocalTime.now() + " " + event.getLevel().toString() + "]:" + message + "\n";
this.messages+=message;
boolean shouldIgnore = false;

for(String txt : plugin.getConfig().getStringList("Config.IgnoreWords")) {
if(message.contains(txt)) shouldIgnore = true;
}

if(!shouldIgnore) {
message = "["+ LocalTime.now() + " " + event.getLevel().toString() + "]:" + message + "\n";
this.messages+=message;
}
}

public void sendMessages() {
Expand All @@ -35,10 +43,10 @@ public void run() {
msg = msg.replaceAll("(?:[&§][a-fk-oru0-9])", "");

if(msg.length() >= 2000) {
String messageTooLong = "\n\nThis message exceeded discord's 2,000 character limit. To see the complete log look in the console!";
String messageTooLong = plugin.getConfig().getString("Messages.Discord.MessageLimit", "\n\nThis message exceeded discord's 2,000 character limit. To see the complete log look in the console!");

msg = msg.substring(0, 1999 - messageTooLong.length() - 8);
msg =msg + messageTooLong;
msg = msg + messageTooLong;
}

jda.getTextChannelById(plugin.getConfig().getString("Discord-Bot.Channel")).sendMessage("```" + msg + "```").submit();
Expand All @@ -48,6 +56,6 @@ public void run() {
}
messages = "";
}
}, 0L, 20L);
}, 0L, plugin.getConfig().getLong("Config.LogDelay", 20L));
}
}
67 changes: 67 additions & 0 deletions src/main/java/niix/dan/consolediscord/ConfigEnum.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package niix.dan.consolediscord;

import java.util.List;

public enum ConfigEnum {
DISCORD_BOT_TOKEN("BotToken", "Discord-Bot.Token", "Token para a aplicação Discord", "string"),
DISCORD_BOT_CHANNEL("BotChannel", "Discord-Bot.Channel", "Canal Discord associado ao bot", "string"),

BLOCKED_CMDS("BlockedCmds", "Discord-Bot.BlockedCmds", "Comandos bloqueados que não podem ser usados no console", "list"),
WHITELIST_ENABLED("Whitelist_Enabled", "Discord-Bot.Whitelist.Enabled", "Indica se a lista de pessoas permitidas está ativada", "boolean"),
WHITELIST_LIST("Whitelist_List", "Discord-Bot.Whitelist.List", "Lista de IDs Discord permitidos na lista de permissões", "list"),
WHITELIST_MESSAGE("Whitelist_Message", "Discord-Bot.Whitelist.Message", "Mensagem exibida para usuários não autorizados", "string"),

DISCORD_MESSAGE_LIMIT("Msg_MessageLimit", "Messages.Discord.MessageLimit", "Mensagem exibida quando uma mensagem excede o limite do Discord", "string"),
IN_GAME_NO_PERMISSION("Msg_NoPerm", "Messages.InGame.NoPerm", "Mensagem exibida quando o jogador não tem permissão", "string"),

IGNORE_WORDS("IgnoreWords", "Config.IgnoreWords", "Palavras que, se encontradas nos logs, serão ignoradas", "list"),

LOG_DELAY("UpdateDelay", "Config.LogDelay", "Atraso entre verificações de logs do console para enviar para o Discord (em ticks)", "long"),

FILTER_ENABLED("EnableFilter", "Config.Filter.Enabled", "Indica se o filtro de comandos do Discord está habilitado", "boolean"),
FILTER_REGEX("FilterRegex", "Config.Filter.RegEx", "Expressão regular usada para filtrar comandos do Discord", "string"),
FILTER_REPLACE("FilterReplace", "Config.Filter.Replace", "Texto de substituição para comandos filtrados do Discord", "string");

private final String key;
private final String description;
private final String type;
private final String name;

ConfigEnum(String name, String key, String description, String type) {
this.name = name;
this.key = key;
this.type = type;
this.description = description;
}

public String getName() {
return name;
}

public String getType() {
return type;
}

public String getKey() {
return key;
}

public String getDescription() {
return description;
}

/**
* Método de parse para encontrar um ConfigKey com base no caminho da configuração.
*
* @param path O caminho da configuração a ser procurado
* @return O ConfigKey correspondente ao caminho, ou null se não encontrado
*/
public static ConfigEnum parse(String path) {
for (ConfigEnum configKey : values()) {
if (configKey.getKey().equals(path)) {
return configKey;
}
}
return null;
}
}
61 changes: 9 additions & 52 deletions src/main/java/niix/dan/consolediscord/ConsoleDiscord.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.Logger;

import java.util.logging.Level;


public final class ConsoleDiscord extends JavaPlugin {
public static ConsoleDiscord plugin;
Expand All @@ -29,7 +29,7 @@ public void onEnable() {
`---' `----' `-' `-'`----' `----' `----'`----' `----' `-'`----' `---' `----' `-' `-'`----'*/

registerConfigs();
registerCmds();
//registerCmds();

checkWarns();
new Updater(this);
Expand All @@ -54,77 +54,34 @@ private void registerConfigs() {
saveDefaultConfig();
}

private void registerCmds() {
getCommand("consolediscord").setExecutor(this);
}

private void checkWarns() {
if(getConfig().getString("Discord-Bot.Token").isEmpty()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Discord-Bot.Token is empty");
plugin.getLogger().log(Level.WARNING, ChatColor.RED + "Discord-Bot.Token is empty");
canRun = false;
}

if(getConfig().getString("Discord-Bot.Channel").isEmpty()) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "Discord-Bot.Channel is empty");
plugin.getLogger().log(Level.WARNING, ChatColor.RED + "Discord-Bot.Channel is empty");
canRun = false;
}
}



@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender.hasPermission("consolediscord.cd") || sender.isOp())) {
sender.sendMessage(getConfig().getString("Messages.NoPermMsg").replaceAll("&", "§")); return true;
}

if(args.length <= 0) {
sender.sendMessage(ChatColor.RED+cmd.getUsage()); return true;
}

if(args[0].equalsIgnoreCase("reload")) {
sender.sendMessage(ChatColor.LIGHT_PURPLE+"Reloading config...");
reloadConfig();
sender.sendMessage(ChatColor.LIGHT_PURPLE+"Done!");
}

if(args[0].equalsIgnoreCase("jda")) {
if(args.length <= 1) {sender.sendMessage(ChatColor.RED+cmd.getUsage()); return true;}

if(args[1].equalsIgnoreCase("restart")) {
try {
sender.sendMessage(ChatColor.RED+"Restarting JDA & Appender...");
this.jda.shutdownNow();
this.appender.jda.shutdownNow();
this.appender.stop();

Bot();
sender.sendMessage(ChatColor.GREEN+"Done! JDA Restated Successfully");
sender.sendMessage(ChatColor.GREEN+"Done! Appender Restated Successfully");
} catch(Exception exx) {
sender.sendMessage(ChatColor.RED+"Error! Please check the logs.");
}
}
}

return false;
}


public void Bot() {
if(canRun) {
try {
this.jda = JDABuilder.createDefault(getConfig().getString("Discord-Bot.Token"), GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT).build();
jda.addEventListener(new Object[] { new Listener(this, this.jda) });
Bukkit.getConsoleSender().sendMessage(ChatColor.GREEN+"JDA Login Successfully - Bot Online");
plugin.getLogger().log(Level.parse("INFO"), ChatColor.GREEN+"JDA Login Successfully - Bot Online");
} catch (Exception e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED+"JDA Login Error: "+e.getMessage());
plugin.getLogger().log(Level.WARNING, ChatColor.RED+"JDA Login Error: "+e.getMessage());
}

try {
RunAppender();
} catch(Exception e) {
Bukkit.getConsoleSender().sendMessage(ChatColor.RED+"JDA Login Error: "+e.getMessage());

plugin.getLogger().log(Level.WARNING, ChatColor.RED+"JDA Login Error: "+e.getMessage());
}
}
}
Expand Down
Loading

0 comments on commit 1a0ba71

Please # to comment.