TelegramAPI/src/de/mrbesen/telegram/commands/CommandManager.java

76 lines
2.1 KiB
Java
Raw Normal View History

2018-07-17 19:23:54 +02:00
package de.mrbesen.telegram.commands;
2018-10-11 14:49:11 +02:00
import org.json.JSONObject;
2018-07-17 19:23:54 +02:00
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import de.mrbesen.telegram.objects.TUser;
2018-07-17 19:23:54 +02:00
public class CommandManager {
2018-07-18 04:44:04 +02:00
private final static String CMDPATTERN = "^[\\w-]+$";
2018-07-17 19:23:54 +02:00
private Multimap<String, CommandHandler> handlerlist = ArrayListMultimap.create();//list of all registered CommandHandler
public CommandManager() { }
2018-10-11 14:49:11 +02:00
public void onCommand(String line, TUser sender, JSONObject json) {//called by the api (/-prefix already removed)
2018-07-17 19:23:54 +02:00
line = line.trim();
String[] split = line.split(" ",2);
String cmd = split[0].toLowerCase();
2018-10-11 14:49:11 +02:00
if(cmd.contains("@")) {
cmd = cmd.substring(0, cmd.indexOf('@'));
}
2018-07-18 04:44:04 +02:00
boolean result = false;
2018-07-17 19:23:54 +02:00
if(cmd.matches(CMDPATTERN)) {
String[] args = new String[0];
if(split.length == 2) {
args = split[1].split(" ");
}
//call
2018-07-18 04:44:04 +02:00
// System.out.println("cmd " + cmd + " args: " + args.length);
2018-07-17 19:23:54 +02:00
for(CommandHandler cmdhand : handlerlist.get(cmd)) {
try {
2018-10-12 17:24:07 +02:00
if(cmdhand instanceof JSONCommandHandler) {
result = ((JSONCommandHandler) cmdhand).onCommand(sender, cmd, args, json);
} else {
result = cmdhand.onCommand(sender, cmd, args);
}
2018-07-17 19:23:54 +02:00
if(result)
break;
} catch(Throwable t) {
2018-09-15 17:49:25 +02:00
System.err.println("Error, while performing Command. ");//TODO do loggin here
2018-07-17 19:23:54 +02:00
t.printStackTrace();
}
}
2018-07-18 04:44:04 +02:00
}
//do smth. with result
if(!result) {
sender.sendHelpPage();
2018-07-17 19:23:54 +02:00
}
}
public void registerCommand(String cmd, CommandHandler handler) {
if(cmd == null) {
throw new NullPointerException("cmd is not allowed to be null");
}
if(handler == null) {
throw new NullPointerException("handler is not allowed to be null");
}
cmd = cmd.trim();
if(cmd.startsWith("/")) {
cmd = cmd.substring(1);
}
if(cmd.isEmpty()) {
throw new RuntimeException("cmd is not allowed to be empty");
}
if(cmd.matches(CMDPATTERN)) {
handlerlist.put(cmd.toLowerCase(), handler);
2018-07-18 04:44:04 +02:00
//registered successfully!
2018-07-17 19:23:54 +02:00
} else {
throw new IllegalArgumentException("cmd contains unallowed characters. Allowed: a-zA-Z0-9_-");
}
}
}