Browse Source

05.07.2017 -- Prefix Detection improved, Added Markdown Utils Class, Improved Message Deletion

pull/8/head
Niklas H. 2 years ago
parent
commit
1635bec52a
No known key found for this signature in database
19 changed files with 368 additions and 202 deletions
  1. +63
    -88
      lang/lang_en.json
  2. +2
    -9
      momuosb.iml
  3. +26
    -0
      permissions.json
  4. +3
    -3
      pom.xml
  5. +33
    -31
      src/main/java/discord/BotUtils.java
  6. +7
    -0
      src/main/java/events/CommandManager.java
  7. +9
    -8
      src/main/java/events/EventListener.java
  8. +4
    -6
      src/main/java/main/MoMuOSBMain.java
  9. +67
    -0
      src/main/java/modules/ChangeCommands.java
  10. +10
    -10
      src/main/java/modules/InfoCommands.java
  11. +34
    -8
      src/main/java/modules/Moderation.java
  12. +5
    -5
      src/main/java/modules/music/MainMusic.java
  13. +10
    -7
      src/main/java/permission/PermissionController.java
  14. +1
    -0
      src/main/java/storage/ConfigLoader.java
  15. +19
    -15
      src/main/java/storage/FileDriver.java
  16. +13
    -12
      src/main/java/storage/LanguageLoader.java
  17. +5
    -0
      src/main/java/util/Globals.java
  18. +43
    -0
      src/main/java/util/Markdown.java
  19. +14
    -0
      src/main/java/util/Utils.java

+ 63
- 88
lang/lang_en.json View File

@@ -1,90 +1,65 @@
{
"results_cleared":"The results were cleared.",
"common_error":"There was an error!",
"forcedeleteMessages_forcedeletemessages":"Deletion of Message Amount",
"leaveCommand_leave":"The Bot leaves voice Server",
"permlist_title":"Permission List for Group %1s",
"perm_failed":"Failed to manage Permission to group",
"tofewarguments_error":"You have provided to few arguments. %1s of %2s",
"search_count":"Result %1s of %2s",
"private_error":"You can not use commands in direct messages",
"music_volumechangeerror":"Can't change volume.",
"setStream_setstream":"Change the Bot Stream",
"no_search":"There is no search running.",
"login_info":"Bot sign into the server. Please wait until the Bot is ready...",
"changeAvatar_setavatar":"Change the Bot Avatar",
"nomanagepermission_error":"The Bot has no Permission to Manage Messages",
"execution_error":"Error occurred on Command Execution: %1s",
"perm_rem_success":"Permission removed successful",
"deletion_error":"Deletion of Messages failed (%1s of %2s) Error: %3s",
"del_topic":"Deletion %1s of %2s",
"nextImage_next":"Get the next Image",
"commonmessage_error":"There was an error! Error: %1s",
"results_end":"You reached the end of results.",
"music_volumechange":"Volume changed from %1s to %2s",
"perm_add_success":"Permission added successful",
"clearImages_clear":"Clear all image results",
"help_description":"Description",
"notsend_error":"Message could not be sent! Error: %1s",
"command_success":"The command was successful!",
"printProperties_printprop":"Print the Properties",
"help_permission":"Permission",
"perm_add_failed":"Failed to add Permission to group",
"stats_title":"General Stats",
"props":"Properties",
"norolefound":"The Role was not found",
"help_help":"Display the help",
"search_info":"Search Query",
"changeprop_error":"This option can't found in the config file!",
"deleteMessages_deletemessages":"Deletion of Message Amount",
"volumeCommand_volume":"The Bot volume.",
"addPermToGroup_addperm":"Add Permission to Group",
"stats_user":"Users",
"perm_success":"Permission Command successful",
"playCommand_play":"The Bot plays the first song.",
"searchtoken_google":"Please provide a google search api token.",
"stats_commands":"Commands",
"music_add":"Adding to queue: %1s",
"setUsername_setusername":"Change the Bot Name",
"result_out":"The Result is out of Range.",
"stats_owner":"Bot Owner",
"parse_error":"The Value cant parsed into a valid format.",
"perm_rem_failed":"Failed to remove Permission to group",
"joinCommand_join":"The Bot joins voice Server",
"notchanged_error":"The change Command does not provide resetting.",
"searchGoogleImage_search":"Search a Image",
"help_command":"Command",
"changeProperty_changeprop":"Change the Property",
"music_add_queue":"Adding to queue %1s (first track of playlist %2s)",
"music_notloaded":"Could not play.",
"music_skip":"Skipped to next track.",
"help_prefixinfo":"\nThe Prefixes are \nAdmin Prefix: ! \nInfo Prefix: . \nGame Prefix: ~ \nmusic Prefix: $ \n",
"getImage_getImage":"Get Image from Web",
"notdeleted_error":"Message could not be deleted! Error: %1s",
"stats_servercount":"Server Count",
"help_arguments":"Arguments",
"annotation_error":"Invalid Annotation in Module %1s Ex: %2s",
"inviteBot_invitebot":"Invites the bot",
"help_title":"All Commands",
"tomanyarguments_error":"You have provided to many arguments. %1s of %2s",
"shutdowninfo":"The Bot will shutting down in 10 seconds! Bye bye",
"help_alias":"Alias",
"music_notinchannel":"The Bot is not in a voice Channel.",
"search_result":"Your search Result",
"notsendpermission_error":"Message could not be send! The Bot has not enough Permissions for [%1s] - #%2s Error: %3s",
"stats_uptime":"Uptime",
"changeLang_changelang":"Change the Language",
"setplaying_setplaying":"Change the Bot Game",
"removePermToGroup_removeperm":"Remove Permission to Group",
"stats_stats":"Display the stats",
"stats_shards":"Shards",
"shutdownbot_shutdown":"Shutdown the bot",
"nopermissions_error":"You have no Permission to use this command.",
"skipCommand_skip":"The Bot skips a song.",
"help_noneinfo":"If you want to reset a Value, then type for each argument NA.",
"music_notfound":"Nothing found by %1s",
"token_error":"Please provide a token inside of the config.json",
"engine_unknown":"The Search Engine is unknown!",
"botowner_error":"This command can only be used from Bot Owner.",
"command_success_wait":"The command was successful. Please wait... Result is generating..."
"results_cleared": "The results were cleared.",
"common_error": "There was an error!",
"permlist_title": "Permission List for Group %1s",
"tofewarguments_error": "You have provided to few arguments. %1s of %2s",
"search_count": "Result %1s of %2s",
"private_error": "You can not use commands in direct messages",
"music_volumechangeerror": "Can\u0027t change volume.",
"no_search": "There is no search running.",
"login_info": "Bot sign into the server. Please wait until the Bot is ready...",
"nomanagepermission_error": "The Bot has no Permission to Manage Messages.",
"execution_error": "Error occurred on Command Execution: %1s",
"perm_rem_success": "Permission removed successful.",
"deletion_error": "Deletion of Messages failed (%1s of %2s) Error: %3s",
"del_topic": "Deletion %1s of %2s",
"commonmessage_error": "There was an error! Error: %1s",
"results_end": "You reached the end of results.",
"music_volumechange": "Volume changed from %1s to %2s.",
"perm_add_success": "Permission added successful.",
"deleteprivinfo": "Deletion was successfull.",
"help_description": "Description",
"notsend_error": "Message could not be sent! Error: %1s",
"command_success": "The command was successful!",
"help_permission": "Permission",
"perm_add_failed": "Failed to add Permission to group.",
"stats_title": "General Stats",
"props": "Properties",
"norolefound": "The Role was not found.",
"search_info": "Search Query",
"changeprop_error": "This option can\u0027t found in the config file!",
"stats_user": "Users",
"searchtoken_google": "Please provide a google search api token.",
"stats_commands": "Commands",
"music_add": "Adding to queue: %1s.",
"result_out": "The Result is out of Range.",
"stats_owner": "Bot Owner",
"parse_error": "The Value cant parsed into a valid format.",
"perm_rem_failed": "Failed to remove Permission to group.",
"notchanged_error": "The change Command does not provide resetting.",
"help_command": "Command",
"music_add_queue": "Adding to queue %1s (first track of playlist %2s).",
"music_notloaded": "Could not play the choosen song.",
"music_skip": "Skipped to next track.",
"help_prefixinfo": "\nThe Prefixes are \nAdmin Prefix: ! \nInfo Prefix: . \nGame Prefix: ~ \nmusic Prefix: $ \n",
"notdeleted_error": "Message could not be deleted! Error: %1s",
"stats_servercount": "Server Count",
"help_arguments": "Arguments",
"annotation_error": "Invalid Annotation in Module %1s Ex: %2s",
"help_title": "All Commands",
"tomanyarguments_error": "You have provided to many arguments. %1s of %2s",
"shutdowninfo": "The Bot will shutting down in 10 seconds! Bye bye.",
"help_alias": "Alias",
"music_notinchannel": "The Bot is not in a voice Channel.",
"search_result": "Your search Result",
"notsendpermission_error": "Message could not be send! The Bot has not enough Permissions for [%1s] - #%2s Error: %3s",
"stats_uptime": "Uptime",
"stats_shards": "Shards",
"nopermissions_error": "You have no Permission to use this command.",
"help_noneinfo": "If you want to reset a Value, then type for each argument NA.",
"music_notfound": "Nothing found by %1s.",
"token_error": "Please provide a token inside of the config.json",
"engine_unknown": "The Search Engine is unknown!",
"botowner_error": "This command can only be used from Bot Owner.",
"command_success_wait": "The command was successful. Please wait... Result is generating..."
}

+ 2
- 9
momuosb.iml View File

@@ -10,12 +10,6 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: com.sedmelluq:lavaplayer:1.2.36" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: com.sedmelluq:lavaplayer-common:1.0.4" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.5" level="project" />
<orderEntry type="library" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.5" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: org.jsoup:jsoup:1.10.1" level="project" />
<orderEntry type="library" scope="RUNTIME" name="Maven: net.iharder:base64:2.3.9" level="project" />
<orderEntry type="library" name="Maven: com.github.austinv11:Discord4J:2.8.4" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.24" level="project" />
<orderEntry type="library" name="Maven: org.apache.httpcomponents:httpcore:4.4.6" level="project" />
@@ -37,6 +31,7 @@
<orderEntry type="library" name="Maven: net.java.dev.jna:jna:4.3.0" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.soundlibs:mp3spi:1.9.5-2" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.soundlibs:jlayer:1.0.1-2" level="project" />
<orderEntry type="library" name="Maven: junit:junit:3.8.2" level="project" />
<orderEntry type="library" name="Maven: org.jcraft:jorbis:0.0.17" level="project" />
<orderEntry type="library" name="Maven: jflac:jflac:1.3" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.soundlibs:tritonus-share:0.3.7-3" level="project" />
@@ -54,8 +49,6 @@
<orderEntry type="library" scope="RUNTIME" name="Maven: net.iharder:base64:2.3.9" level="project" />
<orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.7.5" level="project" />
<orderEntry type="library" name="Maven: log4j:log4j:1.2.17" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: junit:junit:4.10" level="project" />
<orderEntry type="library" name="Maven: org.hamcrest:hamcrest-core:1.1" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.3" level="project" />
</component>
</module>

+ 26
- 0
permissions.json View File

@@ -0,0 +1,26 @@
{
"328461237715206145": [
"bot_manage"
],
"191530458318766080": [
"bot_info"
],
"329513939018711041": [
"bot_manage"
],
"329656208245915648": [
"bot_manage"
],
"328461443991207937": [
"bot_manage"
],
"293439064055742475": [
"music_control"
],
"328460719098167306": [
"bot_info"
],
"290924825613172737": [
"bot_manage"
]
}

+ 3
- 3
pom.xml View File

@@ -79,9 +79,9 @@
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency>
</dependencies>
</project>

+ 33
- 31
src/main/java/discord/BotUtils.java View File

@@ -1,5 +1,6 @@
package discord;

import sx.blah.discord.handle.impl.obj.Message;
import util.Fast;
import sx.blah.discord.api.ClientBuilder;
import sx.blah.discord.api.IDiscordClient;
@@ -12,6 +13,8 @@ import util.Console;
import util.Footer;

import java.awt.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
@@ -25,6 +28,7 @@ public class BotUtils implements Fast{
* @param token the Auth Token
* @return the BotInstance
*/

static IDiscordClient getBuiltDiscordClient(String token){
// The ClientBuilder object is where you will attach your params for configuring the instance of your bot.
// Such as withToken, setDaemon etc
@@ -41,34 +45,39 @@ public class BotUtils implements Fast{
* @param message Message
* @param delete deletion after time
*/
public static void sendMessage(IChannel channel, String message, boolean delete){
RequestBuffer.request(() -> {
public static IMessage sendMessage(IChannel channel, String message, boolean delete){
RequestBuffer.RequestFuture<IMessage> feature = RequestBuffer.request(() -> {
try{
if (channel.getModifiedPermissions(INIT.BOT.getOurUser()).contains(Permissions.SEND_MESSAGES)) {
channel.sendMessage(message);
deleteMessageFromBot(channel, delete);
IMessage messageinst = channel.sendMessage(message);
deleteMessageFromBot(messageinst, delete);
return messageinst;
} else {
Console.error(String.format(LANG.getTranslation("notsendpermission_error"), channel.getGuild().getName(), channel.getName()));
return null;
}
} catch (DiscordException e){
Console.error(String.format(LANG.getTranslation("notsend_error"), e.getMessage()));
return null;
}
});
return feature.get();
}
/**
* Send a Message in Private Channel
* @param userchannel Channel
* @param message Message
*/
public static void sendPrivMessage(IPrivateChannel userchannel, String message){
RequestBuffer.request(() -> {
public static IMessage sendPrivMessage(IPrivateChannel userchannel, String message){
RequestBuffer.RequestFuture<IMessage> feature = RequestBuffer.request(() -> {
try{
userchannel.sendMessage(message);
return userchannel.sendMessage(message);
} catch (DiscordException e){
Console.error(String.format(LANG.getTranslation("notsend_error"), e.getMessage()));
return null;
}
});
return feature.get();

}
/**
@@ -77,62 +86,55 @@ public class BotUtils implements Fast{
* @param builder Message as Embeded Builder Instance
* @param delete deletion after time
*/
public static void sendEmbMessage(IChannel channel, EmbedBuilder builder, boolean delete){
RequestBuffer.request(() -> {
public static IMessage sendEmbMessage(IChannel channel, EmbedBuilder builder, boolean delete){
RequestBuffer.RequestFuture<IMessage> feature = RequestBuffer.request(() -> {
try{
if (channel.getModifiedPermissions(INIT.BOT.getOurUser()).contains(Permissions.SEND_MESSAGES)) {
Footer.addFooter(builder);
channel.sendMessage(builder.build());
deleteMessageFromBot(channel, delete);
IMessage message = channel.sendMessage(builder.build());
deleteMessageFromBot(message, delete);
return message;
} else {
Console.error(String.format(LANG.getTranslation("notsendpermission_error"), channel.getGuild().getName(), channel.getName()));
return null;
}
} catch (DiscordException e){
Console.error(String.format(LANG.getTranslation("notsend_error"), e.getMessage()));
return null;
}
});
return feature.get();
}
/**
* Send a Message in Channel
* @param channel Channel
* @param builder Message as Embeded Builder Instance
*/
public static void sendPrivEmbMessage(IPrivateChannel channel, EmbedBuilder builder){
RequestBuffer.request(() -> {
public static IMessage sendPrivEmbMessage(IPrivateChannel channel, EmbedBuilder builder){
RequestBuffer.RequestFuture<IMessage> feature = RequestBuffer.request(() -> {
try{
Footer.addFooter(builder);
channel.sendMessage(builder.build());
return channel.sendMessage(builder.build());
} catch (DiscordException e){
Console.error(String.format(LANG.getTranslation("notsend_error"), e.getMessage()));
return null;
}
});
return feature.get();

}

/**
* Delte the Message of the Bot after time
* @param channel Channel
* @param message Channel
* @param delete delete
*/
private static void deleteMessageFromBot(IChannel channel, boolean delete) {
private static void deleteMessageFromBot(IMessage message, boolean delete) {
if (delete && DRIVER.getPropertyOnly(DRIVER.CONFIG,"deleteBotAnswers").equals(true)) {
new Thread(() -> {
try {
Thread.sleep(Integer.parseInt(DRIVER.getPropertyOnly(DRIVER.CONFIG,"botanswerdeletseconds").toString()) * 1000);
MessageHistory messages = channel.getMessageHistory(10);
for (IMessage message: messages) {
if (message.getAuthor().isBot()) {
for (IEmbed obj: message.getEmbeds()) {
if (obj.getColor().equals(Color.green)) {
if (!message.isDeleted()) {
message.delete();
}
}
}
break;
}
}
message.delete();
} catch (Exception ex) {
Console.error(LANG.getTranslation("common_error"));
}

+ 7
- 0
src/main/java/events/CommandManager.java View File

@@ -16,6 +16,7 @@ import java.util.Set;
public class CommandManager {
private HashMap<Command, Method> modules = new HashMap<>();
private HashMap<Command, Module> instances = new HashMap<>();
private ArrayList<String> prefixe = new ArrayList<>();

private static CommandManager instance;

@@ -85,4 +86,10 @@ public class CommandManager {
public String getMethodNameByCommand(Command command) {
return modules.get(command).getName();
}
public ArrayList<String> getAllPrefixe() {
for (Command command: getAllCommands()) {
prefixe.add(command.prefix());
}
return prefixe;
}
}

+ 9
- 8
src/main/java/events/EventListener.java View File

@@ -2,7 +2,7 @@ package events;

import com.sedmelluq.discord.lavaplayer.source.AudioSourceManagers;
import discord.BotUtils;
import util.Fast;
import util.*;
import modules.music.MainMusic;
import org.tritonus.share.ArraySet;
import sx.blah.discord.api.events.EventSubscriber;
@@ -10,9 +10,6 @@ import sx.blah.discord.handle.impl.events.ReadyEvent;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.Permissions;
import util.Console;
import util.GetAnnotation;
import util.SMB;

import java.lang.reflect.Method;
import java.util.ArrayList;
@@ -51,11 +48,15 @@ public class EventListener implements Fast{
String message = event.getMessage().getContent();
String[] messageparts = message.split(" ");
if (messageparts.length > 0) {
String prefix = messageparts[0].substring(0, 1).trim();
String botprefix = DRIVER.getPropertyOnly(DRIVER.CONFIG, "botprefix").toString();
String commandstring = messageparts[0].replace(botprefix, "");
for (String prefixs: COMMAND.getAllPrefixe()) {
commandstring = commandstring.replace(prefixs, "");
}
String prefix = messageparts[0].replace(commandstring, "");
String[] args = new String[]{};
Command command = COMMAND.getCommandByName(messageparts[0].replace(prefix, ""));
Console.debug("Command: "+command);
if (command != null && command.prefix().equalsIgnoreCase(prefix)) {
Command command = COMMAND.getCommandByName(commandstring);
if (command != null && (botprefix+command.prefix()).equalsIgnoreCase(prefix)) {
Console.debug(Console.recievedprefix + "Message: " + message + " Author: " + event.getAuthor().getName() + " Channel: " + event.getChannel().getName());
//Check if Invoke Messages should be deleted
if (DRIVER.getProperty(DRIVER.CONFIG, "deleteinvokes", true).equals(true)) {

+ 4
- 6
src/main/java/main/MoMuOSBMain.java View File

@@ -28,13 +28,11 @@ public class MoMuOSBMain implements Fast {
LANG.createTranslations();
LANG.setDefaultLanguage();
Console.println("Language loading complete!");


Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
shutdown();
}
});
public void run() {
shutdown();
}
});
DiscordInit.getInstance().init();

} catch (Exception ex) {

+ 67
- 0
src/main/java/modules/ChangeCommands.java View File

@@ -3,16 +3,20 @@ package modules;
import discord.BotUtils;
import events.Command;
import events.Module;
import sx.blah.discord.handle.obj.IGuild;
import util.Globals;
import org.apache.commons.lang3.math.NumberUtils;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.util.EmbedBuilder;
import sx.blah.discord.util.Image;
import util.Markdown;
import util.SMB;
import util.Utils;

import java.awt.*;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;

/**
* Created by N.Hartmann on 28.06.2017.
@@ -215,4 +219,67 @@ public class ChangeCommands extends Module {
return true;
}

@Command(
command = "leaveserver",
arguments = {"ServerID"},
description = "Leaves a specific Server",
alias = "leaves",
permission = Globals.BOT_OWNER,
prefix = Globals.ADMIN_PREFIX
)
public boolean leaveServer(MessageReceivedEvent event, String[] args) {
try {
IGuild guild = INIT.BOT.getGuildByID(Long.valueOf(args[0]));
guild.leave();
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS+LANG.getTranslation("command_success")), true);
} catch (Exception ex) {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(String.format(LANG.SUCCESS+LANG.getTranslation("commonmessage_error"), ex.getMessage())), true);
}
return true;
}

@Command(
command = "muteserver",
arguments = {"ServerID", "true or false"},
description = "Mutes a specific Server",
alias = "mutes",
permission = Globals.BOT_OWNER,
prefix = Globals.ADMIN_PREFIX
)
public boolean muteServer(MessageReceivedEvent event, String[] args) {
try {
IGuild guild = INIT.BOT.getGuildByID(Long.valueOf(args[0]));
INIT.BOT.mute(guild, Boolean.valueOf(args[1]));
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS+LANG.getTranslation("command_success")), true);
} catch (Exception ex) {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(String.format(LANG.SUCCESS+LANG.getTranslation("commonmessage_error"), ex.getMessage())), true);
}
return true;
}

@Command(
command = "getserver",
arguments = {},
description = "Get Servers",
alias = "gets",
permission = Globals.BOT_OWNER,
prefix = Globals.ADMIN_PREFIX
)
public boolean getServer(MessageReceivedEvent event, String[] args) {
try {
List<IGuild> server = INIT.BOT.getGuilds();
EmbedBuilder builder = new EmbedBuilder();
builder.withTitle("ServerList");
builder.withDescription(Markdown.bold("Size: "+server.size())+" \n");
for (IGuild serverinst: server) {
builder.appendDesc(Markdown.bold(serverinst.getName())+": "+serverinst.getStringID()+" \n");
}
builder.withColor(Color.green);
BotUtils.sendPrivEmbMessage(event.getAuthor().getOrCreatePMChannel(), builder);
} catch (Exception ex) {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(String.format(LANG.SUCCESS+LANG.getTranslation("commonmessage_error"), ex.getMessage())), true);
}
return true;
}

}

+ 10
- 10
src/main/java/modules/InfoCommands.java View File

@@ -42,7 +42,7 @@ public class InfoCommands extends Module implements Fast {
)
public boolean help(MessageReceivedEvent event, String[] args) {
new Thread(() -> {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS+LANG.getTranslation("command_success_wait")), true);
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS + LANG.getTranslation("command_success_wait")), true);
for (EmbedBuilder builder : genbuildHelp(event)) {
BotUtils.sendPrivEmbMessage(event.getAuthor().getOrCreatePMChannel(), builder);
}
@@ -70,7 +70,7 @@ public class InfoCommands extends Module implements Fast {
EnumSet<Permissions> permissions = EnumSet.allOf(Permissions.class);
BotInviteBuilder builder = new BotInviteBuilder(INIT.BOT).withPermissions(permissions);
BotUtils.sendPrivMessage(event.getAuthor().getOrCreatePMChannel(), builder.build());
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS+LANG.getTranslation("command_success")), true);
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS + LANG.getTranslation("command_success")), true);
} else {
BotUtils.sendMessage(event.getChannel(), LANG.ERROR + LANG.getTranslation("botowner_error"), true);
}
@@ -104,11 +104,11 @@ public class InfoCommands extends Module implements Fast {
builder.withColor(Color.CYAN);

ArrayList<IUser> statusTypes = new ArrayList<>();
event.getGuild().getUsers().forEach(iUser -> {
INIT.BOT.getGuilds().forEach(iGuild -> iGuild.getUsers().forEach(iUser -> {
if (iUser.getPresence().getStatus() != StatusType.OFFLINE) {
statusTypes.add(iUser);
}
});
}));

String stringBuilder = LANG.getTranslation("stats_servercount") + ": " + INIT.BOT.getGuilds().size() +
"\n" + LANG.getTranslation("stats_shards") + ": " + event.getGuild().getShard().getInfo()[0] + " / " + INIT.BOT.getShardCount() +
@@ -124,7 +124,7 @@ public class InfoCommands extends Module implements Fast {
private ArrayList<EmbedBuilder> genbuildHelp(MessageReceivedEvent event) {
ArrayList<EmbedBuilder> builders = new ArrayList<>();
int page = 1;
int pagelenght = 0;
String botprefix = DRIVER.getPropertyOnly(DRIVER.CONFIG, "botprefix").toString();
EmbedBuilder builder = new EmbedBuilder();
builders.add(page - 1, builder);
builders.get(page - 1).withDescription(LANG.getTranslation("help_noneinfo"));
@@ -132,13 +132,13 @@ public class InfoCommands extends Module implements Fast {
int count = 0;
for (Command command : COMMAND.getAllCommands()) {
if (PERM.hasPermission(event.getAuthor(), event.getGuild(), command.permission())) {
String string = "\n" + LANG.getTranslation("help_alias") + ": | " + command.prefix() + command.alias() +
String string = "\n" + LANG.getTranslation("help_alias") + ": | " + botprefix + command.prefix() + command.alias() +
"\n" + LANG.getTranslation("help_arguments") + ": | " + Arrays.toString(command.arguments()).replace("[", "").replace("]", "") +
"\n" + LANG.getTranslation("help_description") + ": | " + LANG.getMethodDescription(command)+
"\n" + LANG.getTranslation("help_description") + ": | " + LANG.getMethodDescription(command) +
"\n" + LANG.getTranslation("help_permission") + ": | " + command.permission() + "\n";
builders.get(page - 1).appendField(LANG.getTranslation("help_command") + " | " + command.prefix() + command.command(), string, false);
builders.get(page - 1).appendField(count+". "+LANG.getTranslation("help_command") + " | " + botprefix + command.prefix() + command.command(), string, false);
}
if (builders.get(page - 1).getFieldCount() >= EmbedBuilder.FIELD_COUNT_LIMIT || builders.get(page-1).getTotalVisibleCharacters() >= (EmbedBuilder.MAX_CHAR_LIMIT-1000)) {
if (builders.get(page - 1).getFieldCount() >= EmbedBuilder.FIELD_COUNT_LIMIT || builders.get(page - 1).getTotalVisibleCharacters() >= (EmbedBuilder.MAX_CHAR_LIMIT - 1000)) {
page++;
EmbedBuilder buildertemp = new EmbedBuilder();
builders.add(page - 1, buildertemp);
@@ -147,7 +147,7 @@ public class InfoCommands extends Module implements Fast {
builders.get(page - 1).withTitle(":information_source: " + LANG.getTranslation("help_title") + " Page: " + page + " :information_source:");
builders.get(page - 1).withColor(Color.CYAN);
}
builders.get(0).withTitle(":information_source: " + LANG.getTranslation("help_title") +"("+count+")"+ " Page: " + 1 + " :information_source:");
builders.get(0).withTitle(":information_source: " + LANG.getTranslation("help_title") + "(" + count + ")" + " Page: " + 1 + " :information_source:");
return builders;
}


+ 34
- 8
src/main/java/modules/Moderation.java View File

@@ -3,6 +3,7 @@ package modules;
import discord.BotUtils;
import events.Command;
import events.Module;
import sx.blah.discord.handle.obj.IPrivateChannel;
import util.Globals;
import sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent;
import sx.blah.discord.handle.obj.IChannel;
@@ -11,6 +12,8 @@ import sx.blah.discord.util.MessageHistory;
import util.Console;
import util.SMB;

import java.util.List;

/**
* Created by N.Hartmann on 28.06.2017.
* Copyright 2017
@@ -114,15 +117,38 @@ public class Moderation extends Module{
prefix = Globals.ADMIN_PREFIX
)
public boolean shutdownbot(MessageReceivedEvent event, String[] args) {
new Thread(new Runnable() {
public void run() {
try {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS + LANG.getTranslation("shutdowninfo")), true);
Thread.sleep(10000);
System.exit(0);
} catch (Exception ex) {
Console.error("Error on shutdown: "+ex.getMessage());
new Thread(() -> {
try {
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS + LANG.getTranslation("shutdowninfo")), true);
Thread.sleep(10000);
System.exit(0);
} catch (Exception ex) {
Console.error("Error on shutdown: "+ex.getMessage());
}
}).start();
return true;
}
@Command(
command = "deleteprivmsg",
description = "Shutdown the bot",
alias = "dpm",
arguments = {"Count"},
permission = Globals.BOT_MANAGE,
prefix = Globals.ADMIN_PREFIX
)
public boolean deleteprivateMessages(MessageReceivedEvent event, String[] args) {
new Thread(() -> {
try {
IPrivateChannel privateChannel = event.getAuthor().getOrCreatePMChannel();
List<IMessage> messageList = privateChannel.getMessageHistory(Integer.parseInt(args[0]));
for (IMessage message: messageList) {
if (message.getAuthor().isBot()) {
BotUtils.deleteMessageOne(message);
}
}
BotUtils.sendEmbMessage(event.getChannel(), SMB.shortMessage(LANG.SUCCESS + LANG.getTranslation("deleteprivinfo")), true);
} catch (Exception ex) {
Console.error(String.format(LANG.getTranslation("commonmessage_error"), ex.getMessage()));
}
}).start();
return true;

+ 5
- 5
src/main/java/modules/music/MainMusic.java View File

@@ -43,7 +43,7 @@ public class MainMusic extends Module{
return false;

userVoiceChannel.join();
this.volumeCommand(event, new String[] {DRIVER.getPropertyOnly(DRIVER.CONFIG, "defaultvolume").toString()});
this.volumeMusic(event, new String[] {DRIVER.getPropertyOnly(DRIVER.CONFIG, "defaultvolume").toString()});
return true;
}

@@ -55,7 +55,7 @@ public class MainMusic extends Module{
permission = "music_control",
prefix = Globals.MUSIC_PREFIX
)
public boolean leaveCommand(MessageReceivedEvent event, String[] args) {
public boolean leaveMusic(MessageReceivedEvent event, String[] args) {
IVoiceChannel botVoiceChannel = event.getClient().getOurUser().getVoiceStateForGuild(event.getGuild()).getChannel();

if(botVoiceChannel == null)
@@ -77,7 +77,7 @@ public class MainMusic extends Module{
permission = "music_control",
prefix = Globals.MUSIC_PREFIX
)
public boolean playCommand(MessageReceivedEvent event, String[] args) {
public boolean playMusic(MessageReceivedEvent event, String[] args) {
IVoiceChannel botVoiceChannel = event.getClient().getOurUser().getVoiceStateForGuild(event.getGuild()).getChannel();

if(botVoiceChannel == null) {
@@ -100,7 +100,7 @@ public class MainMusic extends Module{
permission = "music_control",
prefix = Globals.MUSIC_PREFIX
)
public boolean skipCommand(MessageReceivedEvent event, String[] args) {
public boolean skipTrack(MessageReceivedEvent event, String[] args) {
skipTrack(event.getChannel());
return true;
}
@@ -113,7 +113,7 @@ public class MainMusic extends Module{
permission = "music_control",
prefix = Globals.MUSIC_PREFIX
)
public boolean volumeCommand(MessageReceivedEvent event, String[] args) {
public boolean volumeMusic(MessageReceivedEvent event, String[] args) {
try {
int volumebefore = getGuildAudioPlayer(event.getGuild()).player.getVolume();
getGuildAudioPlayer(event.getGuild()).player.setVolume(Integer.parseInt(args[0]));

+ 10
- 7
src/main/java/permission/PermissionController.java View File

@@ -1,7 +1,8 @@
package permission;

import com.google.gson.JsonArray;
import events.Command;
import org.json.simple.JSONArray;
import org.json.JSONArray;
import sx.blah.discord.handle.obj.IGuild;
import sx.blah.discord.handle.obj.IRole;
import sx.blah.discord.handle.obj.IUser;
@@ -83,10 +84,11 @@ public class PermissionController implements Fast {
grouppermission.add(permission);
grouppermissions.put(role, grouppermission);
} else {
Console.debug("This permission doesnt exist: "+permission);
Console.debug("This permission doesnt exist: " + permission);
}
savePermissions();
}

public void removePermissionToGroup(IRole role, String permission) {
if (permissions.containsValue(permission)) {
ArrayList<String> grouppermission = grouppermissions.get(role);
@@ -95,10 +97,11 @@ public class PermissionController implements Fast {
}
grouppermission.remove(permission);
} else {
Console.debug("This permission doesnt exist: "+permission);
Console.debug("This permission doesnt exist: " + permission);
}
savePermissions();
}

public void removePermissionToGroup(IRole role, Command command) {
ArrayList<String> grouppermission = grouppermissions.get(role);
if (grouppermission == null) {
@@ -157,14 +160,14 @@ public class PermissionController implements Fast {
ArrayList<String> permission = new ArrayList<String>();
JSONArray jArray = (JSONArray) values.get(roleid);
if (jArray != null) {
for (Object aJArray : jArray) {
permission.add(aJArray.toString());
for (int i = 0; i < jArray.length(); i++) {
permission.add(jArray.get(i).toString());
}
}
grouppermissions.put(role, permission);
for (String perm : permission) {
Console.debug("Permission: " + perm);
for (Command command: COMMAND.getCommandByPermission(perm)) {
for (Command command : COMMAND.getCommandByPermission(perm)) {
permissions.put(command, perm);
}
}
@@ -179,7 +182,7 @@ public class PermissionController implements Fast {


public void setDefaultPermissions(List<IGuild> server) {
if (!DRIVER.checkIfFileExists(PERMFILE) && DRIVER.checkIfFileisEmpty(PERMFILE)) {
if (!DRIVER.checkIfFileExists(PERMFILE) || DRIVER.checkIfFileisEmpty(PERMFILE)) {
Console.debug("Load default permissions...");
List<IRole> adminroles = new ArrayList<>();
List<IRole> everyoneroles = new ArrayList<>();

+ 1
- 0
src/main/java/storage/ConfigLoader.java View File

@@ -22,6 +22,7 @@ public class ConfigLoader implements Fast {
DRIVER.getProperty(DRIVER.CONFIG, "language", "en");
DRIVER.getProperty(DRIVER.CONFIG,"token", "");
DRIVER.getProperty(DRIVER.CONFIG, "ownerbypass", true);
DRIVER.getProperty(DRIVER.CONFIG, "botprefix", "");
DRIVER.saveJson();
}
}

+ 19
- 15
src/main/java/storage/FileDriver.java View File

@@ -1,12 +1,18 @@
package storage;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import main.MoMuOSBMain;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.JSONObject;
import util.Console;
import util.Utils;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
* Created by N.Hartmann on 28.06.2017.
@@ -36,7 +42,7 @@ public class FileDriver {
}
public boolean checkIfFileisEmpty(String filename) {
loadJson();
return jsons.get(filename).isEmpty();
return jsons.get(filename).keySet().size() == 0;
}

/**
@@ -81,8 +87,8 @@ public class FileDriver {
JSONObject json = new JSONObject();
try {
if (!string.equals("")) {
JSONParser jsonParser = new JSONParser();
json = (JSONObject) jsonParser.parse(string);
JsonParser jsonParser = new JsonParser();
json = new JSONObject(jsonParser.parse(string).getAsJsonObject().toString());
}
} catch (Exception ex) {
Console.error("Parsing error");
@@ -121,10 +127,8 @@ public class FileDriver {
try {
for (String filename: files.keySet()) {
BufferedWriter writer = new BufferedWriter(new FileWriter(files.get(filename)));
String json = jsons.get(filename).toJSONString();
json = json.replace("{\"", "{\n \"")
.replace(",\"", ",\n \"")
.replace("\"}", "\"\n}");
String json = jsons.get(filename).toString();
json = Utils.crunchifyPrettyJSONUtility(json);
writer.write(json);
writer.close();
}
@@ -144,7 +148,7 @@ public class FileDriver {
public void setProperty(String filename, String option, Object value) {
try {
if (jsons.get(filename) != null) {
if (jsons.get(filename).containsKey(option)) {
if (jsons.get(filename).has(option)) {
removeProperty(filename, option);
}
jsons.get(filename).put(option, value);
@@ -168,7 +172,7 @@ public class FileDriver {
*/
public Object getProperty(String filename, String option, Object defaultvalue) {
try {
if (jsons.get(filename) == null || !jsons.get(filename).containsKey(option)) {
if (jsons.get(filename) == null || !jsons.get(filename).has(option)) {
setProperty(filename, option, defaultvalue);
}
} catch (Exception ex) {
@@ -185,7 +189,7 @@ public class FileDriver {
* @return value
*/
public Object getPropertyOnly(String filename, String option) {
if (jsons.get(filename).containsKey(option)) {
if (jsons.get(filename).has(option)) {
return jsons.get(filename).get(option);
} else {
return "No Value";
@@ -200,7 +204,7 @@ public class FileDriver {
*/
public void removeProperty(String filename, String option) {
try {
if (jsons.get(filename).containsKey(option)) {
if (jsons.get(filename).has(option)) {
jsons.get(filename).remove(option);
}
} catch (Exception ex) {
@@ -212,8 +216,8 @@ public class FileDriver {
public HashMap<String, Object> getAllKeysWithValues(String filename) {
HashMap<String, Object> objects = new HashMap<>();
try {
for (Object string: jsons.get(filename).keySet()) {
objects.put(string.toString(), jsons.get(filename).get(string));
for (Object key: jsons.get(filename).keySet()) {
objects.put(key.toString(), jsons.get(filename).get(key.toString()));
}
} catch (Exception ex) {
Console.error("Can not list Property: ");

+ 13
- 12
src/main/java/storage/LanguageLoader.java View File

@@ -71,17 +71,18 @@ public class LanguageLoader implements Fast{
DRIVER.setProperty(DEF_LANG, "notsendpermission_error", "Message could not be send! The Bot has not enough Permissions for [%1s] - #%2s Error: %3s");
DRIVER.setProperty(DEF_LANG, "private_error", "You can not use commands in direct messages");
DRIVER.setProperty(DEF_LANG, "nopermissions_error", "You have no Permission to use this command.");
DRIVER.setProperty(DEF_LANG, "nomanagepermission_error", "The Bot has no Permission to Manage Messages");
DRIVER.setProperty(DEF_LANG, "nomanagepermission_error", "The Bot has no Permission to Manage Messages.");
DRIVER.setProperty(DEF_LANG, "tofewarguments_error", "You have provided to few arguments. %1s of %2s");
DRIVER.setProperty(DEF_LANG, "tomanyarguments_error", "You have provided to many arguments. %1s of %2s");
DRIVER.setProperty(DEF_LANG, "botowner_error", "This command can only be used from Bot Owner.");
DRIVER.setProperty(DEF_LANG, "deletion_error", "Deletion of Messages failed (%1s of %2s) Error: %3s");
DRIVER.setProperty(DEF_LANG, "deleteprivinfo", "Deletion was successfull.");

//Infos
DRIVER.setProperty(DEF_LANG, "login_info", "Bot sign into the server. Please wait until the Bot is ready...");
DRIVER.setProperty(DEF_LANG, "command_success", "The command was successful!");
DRIVER.setProperty(DEF_LANG, "command_success_wait", "The command was successful. Please wait... Result is generating...");
DRIVER.setProperty(DEF_LANG, "shutdowninfo", "The Bot will shutting down in 10 seconds! Bye bye");
DRIVER.setProperty(DEF_LANG, "shutdowninfo", "The Bot will shutting down in 10 seconds! Bye bye.");

//Stats Command
DRIVER.setProperty(DEF_LANG, "stats_title", "General Stats");
@@ -122,12 +123,12 @@ public class LanguageLoader implements Fast{

//Music
DRIVER.setProperty(DEF_LANG, "music_notinchannel", "The Bot is not in a voice Channel.");
DRIVER.setProperty(DEF_LANG, "music_volumechange", "Volume changed from %1s to %2s");
DRIVER.setProperty(DEF_LANG, "music_volumechange", "Volume changed from %1s to %2s.");
DRIVER.setProperty(DEF_LANG, "music_volumechangeerror", "Can't change volume.");
DRIVER.setProperty(DEF_LANG, "music_add","Adding to queue: %1s");
DRIVER.setProperty(DEF_LANG, "music_add_queue", "Adding to queue %1s (first track of playlist %2s)");
DRIVER.setProperty(DEF_LANG, "music_notfound", "Nothing found by %1s");
DRIVER.setProperty(DEF_LANG, "music_notloaded", "Could not play.");
DRIVER.setProperty(DEF_LANG, "music_add","Adding to queue: %1s.");
DRIVER.setProperty(DEF_LANG, "music_add_queue", "Adding to queue %1s (first track of playlist %2s).");
DRIVER.setProperty(DEF_LANG, "music_notfound", "Nothing found by %1s.");
DRIVER.setProperty(DEF_LANG, "music_notloaded", "Could not play the choosen song.");
DRIVER.setProperty(DEF_LANG, "music_skip", "Skipped to next track.");

//Changes
@@ -137,12 +138,12 @@ public class LanguageLoader implements Fast{
DRIVER.setProperty(DEF_LANG, "props", "Properties");

//Permission
DRIVER.setProperty(DEF_LANG, "perm_add_success", "Permission added successful");
DRIVER.setProperty(DEF_LANG, "perm_add_failed", "Failed to add Permission to group");
DRIVER.setProperty(DEF_LANG, "perm_rem_success", "Permission removed successful");
DRIVER.setProperty(DEF_LANG, "perm_rem_failed", "Failed to remove Permission to group");
DRIVER.setProperty(DEF_LANG, "perm_add_success", "Permission added successful.");
DRIVER.setProperty(DEF_LANG, "perm_add_failed", "Failed to add Permission to group.");
DRIVER.setProperty(DEF_LANG, "perm_rem_success", "Permission removed successful.");
DRIVER.setProperty(DEF_LANG, "perm_rem_failed", "Failed to remove Permission to group.");
DRIVER.setProperty(DEF_LANG, "permlist_title", "Permission List for Group %1s");
DRIVER.setProperty(DEF_LANG, "norolefound", "The Role was not found");
DRIVER.setProperty(DEF_LANG, "norolefound", "The Role was not found.");

DRIVER.saveJson();
}

+ 5
- 0
src/main/java/util/Globals.java View File

@@ -5,10 +5,15 @@ package util;
* Copyright 2017
*/
public interface Globals {
//Prefix Globals
String ADMIN_PREFIX = "!";
String INFO_PREFIX = ".";
String GAME_PREFIX = "~";
String MUSIC_PREFIX = "$";

String[] allprefixes = new String[] {ADMIN_PREFIX, INFO_PREFIX, GAME_PREFIX, MUSIC_PREFIX};

//Permission globals
String BOT_OWNER = "bot_owner";
String BOT_MANAGE = "bot_manage";
String BOT_INFO = "bot_info";

+ 43
- 0
src/main/java/util/Markdown.java View File

@@ -0,0 +1,43 @@
package util;

/**
* Created by N.Hartmann on 05.07.2017.
* Copyright 2017
*/
public class Markdown {

//Generell Markdown
public static String bold(String text){
return "**"+text+"**";
}
public static String italic(String text){
return "*"+text+"*";
}
public static String underline(String text){
return "__"+text+"__";
}
public static String striketrought(String text){
return "~~"+text+"~~";
}
public static String codeOL(String text){
return "`"+text+"`";
}
public static String codeML(String text){
return "```\n"+text+"\n```";
}


//Utils
public static String bolditalic(String text){
return Markdown.italic(Markdown.bold(text));
}
public static String underlineitalic(String text){
return Markdown.underline(Markdown.italic(text));
}
public static String underlinebold(String text){
return Markdown.underline(Markdown.bold(text));
}
public static String underlinebolditalic(String text){
return Markdown.underline(Markdown.bolditalic(text));
}
}

+ 14
- 0
src/main/java/util/Utils.java View File

@@ -1,5 +1,11 @@
package util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Arrays;
@@ -45,4 +51,12 @@ public class Utils {
}
return string.trim();
}
public static String crunchifyPrettyJSONUtility(String simpleJSON) {
JsonParser crunhifyParser = new JsonParser();
JsonObject json = crunhifyParser.parse(simpleJSON).getAsJsonObject();

Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();

return prettyGson.toJson(json);
}
}

Loading…
Cancel
Save