package de.mrbesen.telegram.commands; import org.apache.logging.log4j.message.TimestampMessage; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import de.mrbesen.telegram.objects.TMessage; import de.mrbesen.telegram.objects.TUser; import de.mrbesen.telegram.*; public class CommandManager { private final static String CMDPATTERN = "^[\\w-]+$"; private final TelegramAPI api; private Multimap handlerlist = ArrayListMultimap.create();//list of all registered CommandHandler public CommandManager(TelegramAPI a) { api = a; } public void onCommand(String line, TUser sender, TMessage json) {//called by the api (/-prefix already removed) line = line.trim(); String[] split = line.split(" ",2); String cmd = split[0].toLowerCase(); if(cmd.contains("@")) { cmd = cmd.substring(0, cmd.indexOf('@')); } boolean result = false; if(cmd.matches(CMDPATTERN)) { String[] args = new String[0]; if(split.length == 2) { args = split[1].split(" "); } //call // System.out.println("cmd " + cmd + " args: " + args.length); for(ICommandHandler cmdhand : handlerlist.get(cmd)) { try { if(cmdhand instanceof JSONCommandHandler) { result = ((JSONCommandHandler) cmdhand).onCommand(sender, cmd, args, json); } else if( cmdhand instanceof CommandHandler){ result = ((CommandHandler) cmdhand).onCommand(sender, cmd, args); } if(result) break; } catch(Throwable t) { System.err.println("Error, while performing Command. ");//TODO do loggin here t.printStackTrace(); } } } //do smth. with result if(!result) { TUser.sendMessage(api, json.getChatID(), api.getHelpMessage(), null, 0, true, null); } } public void registerCommand(String cmd, ICommandHandler 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); //registered successfully! } else { throw new IllegalArgumentException("cmd contains unallowed characters. Allowed: a-zA-Z0-9_-"); } } }