public async Task <string> Execute(object sender, MessageEventArgs args) { var text = args.Message.Text; if (CommandString.TryParse(text, out var cmd)) { if (cmd.Username != null && cmd.Username != Username) { Log.LogDebug("Message not directed at us"); return(null); } if (Commands.ContainsKey(cmd.Command)) { try { Log.LogDebug($"Handling message via {Commands[cmd.Command].GetType().Name}"); return(await Commands[cmd.Command].Execute(cmd, args)); } catch (Exception e) { Log.LogError(e, $"Error while executing command {cmd.Command}!"); } } else { Log.LogDebug($"Command {cmd.Command} not found"); } } return(null); }
public static bool TryParse(string s, out CommandString result) { result = null; if (string.IsNullOrWhiteSpace(s) || s[0] != '/') { return(false); } string[] words = s.Split(WS_CHARS, StringSplitOptions.RemoveEmptyEntries); var cmdRegex = new Regex(@"/(?<cmd>\w+)(@(?<name>\w+))?"); var match = cmdRegex.Match(words.First()); if (!match.Success) { return(false); } string cmd = match.Groups["cmd"].Captures[0].Value; string username = match.Groups["name"].Captures.Count > 0 ? match.Groups["name"].Captures[0].Value : null; string[] parameters = words.Skip(1).ToArray(); result = new CommandString(cmd, username, parameters); return(true); }