Exemplo n.º 1
0
        public BotCommandTemplate GetCommandTemplate(Type commandType)
        {
            var properties = GetBotCommandProperties(commandType);
            var template   = new BotCommandTemplate(commandType.Name, properties);

            return(template);
        }
Exemplo n.º 2
0
        public object GetValueByNameFromCustomCommand(string key, bool isList, BotCommandTemplate template, Match match)
        {
            if (!match.Groups.ContainsKey(key))
            {
                return(null);
            }
            var lowerCaseKey = key.ToLowerInvariant();
            var value        = match.Groups[key].Value.Trim();
            var argType      = template.Properties.FirstOrDefault(x => x.Name.ToLowerInvariant() == lowerCaseKey)?.Type;

            if (argType.HasValue && argType.Value == BotCommandPropertyType.Bool && !string.IsNullOrWhiteSpace(value))
            {
                return(bool.TrueString);
            }
            if (!isList)
            {
                return(value);
            }
            if (!value.Contains('\"') || value.Count(x => x == '\"') % 2 != 0)
            {
                return(value.Split(' ').ToList());
            }
            var results = value.Split('"')
                          .Where(x => !string.IsNullOrWhiteSpace(x) && !x.StartsWith(' ') && !x.EndsWith(' '))
                          .ToList();

            foreach (var toRemove in results)
            {
                value = value.Replace($"\"{toRemove}\"", string.Empty);
            }
            var otherResults = value.Split(' ').Where(x => !string.IsNullOrWhiteSpace(x)).Select(x => x.Trim());

            results.AddRange(otherResults);
            return(results);
        }
Exemplo n.º 3
0
        private IBotCommand GetFilledInstance(Type commandType, BotCommandTemplate template, Func <string, bool, object> getValueByName)
        {
            var instance = Activator.CreateInstance(commandType);

            foreach (var property in commandType.GetProperties())
            {
                var propertyType = template.Properties.FirstOrDefault(x => x.Name == property.Name)?.Type;
                var isList       = propertyType == BotCommandPropertyType.List;
                var value        = getValueByName.Invoke(property.Name, isList);
                if (value == null)
                {
                    continue;
                }
                if (isList)
                {
                    property.SetValue(instance, value);
                    continue;
                }
                if (value is string valueString && !string.IsNullOrWhiteSpace(valueString))
                {
                    var convertedType = this._botCommandPropertyConversionService.ConvertType(valueString, propertyType.Value);
                    property.SetValue(instance, convertedType);
                }
            }
            return((IBotCommand)instance);
        }
Exemplo n.º 4
0
        private IBotCommand GetFilledInstance(Type commandType, BotCommandTemplate template, Func <string, bool, object> getValueByName)
        {
            var instance = Activator.CreateInstance(commandType);

            foreach (var property in commandType.GetProperties())
            {
                var propertyType = template.Properties.First(x => x.Name == property.Name).Type;
                var isList       = propertyType == BotCommandPropertyType.List;
                var value        = getValueByName.Invoke(property.Name, isList);
                if (string.IsNullOrWhiteSpace(value as string) && !isList)
                {
                    // if we got to this point in the code, it means that property is optional (but which is not bool) and the user did not provide a value to this field, so we assign null to property. Property must be a type that takes null.
                    property.SetValue(instance, null);
                }
                if (value is List <string> valueList)
                {
                    var isEmptyList = string.IsNullOrWhiteSpace(valueList?.FirstOrDefault());
                    if (isEmptyList)
                    {
                        property.SetValue(instance, null);
                        continue;
                    }
                    property.SetValue(instance, value);
                }
                if (value is string valueString)
                {
                    var convertedType = this._botCommandPropertyConversionService.ConvertType(valueString, propertyType);
                    property.SetValue(instance, convertedType);
                }
            }
            return((IBotCommand)instance);
        }
Exemplo n.º 5
0
        public bool AreDefaultCommandArgumentsCorrect(BotCommandTemplate template, IEnumerable <DiscordRequestArgument> arguments)
        {
            var argsAndValues = arguments
                                .Select(arg => new KeyValuePair <string, string>(arg.Name, arg.Value))
                                .ToList();

            this.CheckQuotationMarksInListsAndTexts(template.Properties, argsAndValues);
            return(this.ComparePropertiesToArgsAndValues(template.Properties, argsAndValues));
        }
Exemplo n.º 6
0
        public IBotCommand ParseCustomTemplate(Type commandType, BotCommandTemplate template, Regex customTemplate, string input)
        {
            var match = customTemplate.Match(input);

            if (!this.CustomTemplateIsValid(match, template))
            {
                Log.Warning("Custom template {customTemplate} is not valid for {commandName}", customTemplate, template.CommandName);
                return(null);
            }
            var result = this.GetFilledInstance(commandType, template, (key, isList) => this._botCommandsRequestValueGetterService.GetValueByNameFromCustomCommand(key, isList, template, match));

            return(result);
        }
Exemplo n.º 7
0
        public bool IsDefaultCommand(BotCommandTemplate template, IEnumerable <DiscordRequestArgument> arguments, bool isCommandMatchedWithCustom)
        {
            var requiredProperties = template.Properties.Where(x => !x.IsOptional);

            if (requiredProperties.Any(property => arguments.All(arg => property.Name.ToLowerInvariant() != arg.Name?.ToLowerInvariant())))
            {
                return(false);
            }
            if (!isCommandMatchedWithCustom)
            {
                return(true);
            }
            return(this.AreAllGivenArgsForCommandKnown(template.Properties, arguments));
        }
        public string RenderTextTemplate(BotCommandTemplate template)
        {
            var output = new StringBuilder();

            output.Append($"{{{{prefix}}}}[[{template.CommandName}]]");
            foreach (var commandProperty in template.Properties)
            {
                output.Append($" {{{{prefix}}}}[[{commandProperty.Name}]] (({Enum.GetName(typeof(BotCommandPropertyType), commandProperty.Type)}))");
                if (commandProperty.IsOptional)
                {
                    output.Append("<<optional>>");
                }
            }
            return(output.ToString());
        }
 public bool IsMatchedWithCommand(DiscordRequest request, BotCommandTemplate template)
 {
     if (!request.IsCommandForBot)
     {
         return false;
     }
     if (request.Name.ToLowerInvariant() != template.NormalizedCommandName)
     {
         return false;
     }
     if (!this.CompareArgumentsToProperties(request.Arguments.ToList(), template.Properties.ToList()))
     {
         return false;
     }
     return true;
 }
Exemplo n.º 10
0
        public bool AreCustomCommandArgumentsCorrect(BotCommandTemplate template, Regex customTemplate, string input)
        {
            var matchGroups        = customTemplate.Match(input).Groups;
            var requiredProperties = template.Properties.Where(x => !x.IsOptional);

            if (requiredProperties.Any(x => !matchGroups.ContainsKey(x.Name)))
            {
                Log.Warning("Custom template {customTemplate} is not valid for {commandName}", customTemplate, template.CommandName);
                throw new InvalidArgumentsException();
            }
            var argsAndValues = matchGroups.Keys
                                .Where(arg => !arg.All(char.IsDigit))
                                .Select(arg => new KeyValuePair <string, string>(arg, matchGroups[arg].Value.Trim()))
                                .ToList();

            this.CheckQuotationMarksInListsAndTexts(template.Properties, argsAndValues, isCommandMatchedWithCustom: true);
            return(this.ComparePropertiesToArgsAndValues(template.Properties, argsAndValues));
        }
Exemplo n.º 11
0
        private bool CustomTemplateIsValid(Match match, BotCommandTemplate template)
        {
            if (!match.Success)
            {
                return(false);
            }
            var requiredProperties = template.Properties.Where(x => !x.IsOptional).ToList();

            if (match.Groups.Count - 1 < requiredProperties.Count)
            {
                return(false);
            }
            if (requiredProperties.Any(x => !match.Groups.ContainsKey(x.Name)))
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 12
0
        public object GetValueByNameFromCustomCommand(string key, bool isList, BotCommandTemplate template, Match match)
        {
            var value   = match.Groups[key].Value.Trim();
            var argType = template.Properties.First(x => x.Name.ToLowerInvariant() == key.ToLowerInvariant()).Type;

            if (argType == BotCommandPropertyType.Bool)
            {
                return(string.IsNullOrWhiteSpace(value) ? bool.FalseString : bool.TrueString);
            }
            if (argType == BotCommandPropertyType.SingleWord)
            {
                return(value.Split().First().Trim('\"'));
            }
            if (argType == BotCommandPropertyType.Text)
            {
                return(value.Trim('\"'));
            }
            if (!isList)
            {
                return(value);
            }

            if (!value.Contains('\"'))
            {
                return(value.Split().Where(x => !string.IsNullOrEmpty(x))
                       .ToList());
            }
            var splittedResults = value.Split('"').Where(x => !string.IsNullOrWhiteSpace(x));
            var results         = new List <string>();

            foreach (var toRemove in splittedResults)
            {
                if (value.Contains($"\"{toRemove}\""))
                {
                    // here we're adding text with quotation marks to the results, but texts without quotation marks are added later
                    results.Add(toRemove);
                }
                value = value.Replace($"\"{toRemove}\"", string.Empty);
            }
            var otherResultsWithoutQuote = value.Split().Where(x => !string.IsNullOrWhiteSpace(x));

            results.AddRange(otherResultsWithoutQuote);
            return(results);
        }
Exemplo n.º 13
0
 public T ParseRequestToCommand <T>(DiscordRequest request, BotCommandTemplate template) where T : IBotCommand
 {
     return((T)this.ParseRequestToCommand(typeof(T), request, template));
 }
Exemplo n.º 14
0
 public string RenderTextTemplate(BotCommandTemplate template)
 {
     return(this.botCommandsTemplateRenderingService.RenderTextTemplate(template));
 }
Exemplo n.º 15
0
 public bool IsMatchedWithCommand(DiscordRequest request, BotCommandTemplate template)
 {
     return(this.botCommandMatchingService.IsMatchedWithCommand(request, template));
 }
Exemplo n.º 16
0
        public IBotCommand ParseCustomTemplate(Type commandType, BotCommandTemplate template, Regex customTemplate, string input)
        {
            var match = customTemplate.Match(input);

            return(this.GetFilledInstance(commandType, template, (key, isList) => this._botCommandsRequestValueGetterService.GetValueByNameFromCustomCommand(key, isList, template, match)));
        }
Exemplo n.º 17
0
 public IBotCommand ParseRequestToCommand(Type commandType, DiscordRequest request, BotCommandTemplate template)
 {
     return(this.GetFilledInstance(commandType, template, (key, isList) => this._botCommandsRequestValueGetterService.GetValueByName(key, isList, request, template)));
 }
Exemplo n.º 18
0
        private IBotCommand CreateBotCommand(bool isThereDefaultCommandWithGivenName, BotCommandTemplate template, Type commandInParameterType, DiscordRequest request, Regex customTemplate, bool isCommandMatchedWithCustom)
        {
            var isDefaultCommand = isThereDefaultCommandWithGivenName && this._botCommandsService.IsDefaultCommand(template, request.Arguments, isCommandMatchedWithCustom);

            if (isDefaultCommand && this._botCommandsService.AreDefaultCommandArgumentsCorrect(template, request.Arguments))
            {
                return(this._botCommandsService.ParseRequestToCommand(commandInParameterType, request, template));
            }
            else if (isCommandMatchedWithCustom && this._botCommandsService.AreCustomCommandArgumentsCorrect(template, customTemplate, request.OriginalMessage))
            {
                return(this._botCommandsService.ParseCustomTemplate(commandInParameterType, template, customTemplate, request.OriginalMessage));
            }
            else
            {
                throw new InvalidArgumentsException();
            }
        }
Exemplo n.º 19
0
        public object GetValueByName(string key, bool isList, DiscordRequest request, BotCommandTemplate template)
        {
            var result = request.Arguments.FirstOrDefault(a => a.Name.ToLowerInvariant() == key.ToLowerInvariant());

            if (result == null)
            {
                return(null);
            }
            var argType = template.Properties.FirstOrDefault(x => x.Name.ToLowerInvariant() == key.ToLowerInvariant())
                          ?.Type;

            if (argType.HasValue && argType.Value == BotCommandPropertyType.Bool)
            {
                return(result.Value ?? bool.TrueString);
            }
            if (!isList)
            {
                return(result.Value);
            }
            var argumentsList = request.Arguments.ToList();
            var indexOf       = argumentsList.IndexOf(result);
            var nextResults   = argumentsList.Skip(indexOf + 1).TakeWhile(x => x.Name == null);
            var list          = new List <string> {
                result.Value
            };

            list.AddRange(nextResults.Select(x => x.Value));
            return(list);
        }
Exemplo n.º 20
0
 public bool AreCustomCommandArgumentsCorrect(BotCommandTemplate template, Regex customTemplate, string input)
 {
     return(this.botCommandMatchingService.AreCustomCommandArgumentsCorrect(template, customTemplate, input));
 }
Exemplo n.º 21
0
 public IBotCommand ParseRequestToCommand(Type commandType, DiscordRequest request, BotCommandTemplate template)
 {
     return(this.botCommandParsingService.ParseRequestToCommand(commandType, request, template));
 }
Exemplo n.º 22
0
        public object GetValueByName(string key, bool isList, DiscordRequest request, BotCommandTemplate template)
        {
            var argType = template.Properties.First(x => x.Name.ToLowerInvariant() == key.ToLowerInvariant()).Type;
            var result  = request.Arguments.FirstOrDefault(a => a.Name?.ToLowerInvariant() == key.ToLowerInvariant());

            if (argType == BotCommandPropertyType.Bool)
            {
                return(result == null ? bool.FalseString : bool.TrueString);
            }
            if (result == null)
            {
                return(null);
            }
            if (argType == BotCommandPropertyType.Text)
            {
                return(result.Value.Trim('\"'));
            }
            if (!isList)
            {
                return(result.Value);
            }
            var indexOf = request.Arguments.ToList().IndexOf(result);
            var list    = request.Arguments
                          .Skip(indexOf)
                          .TakeWhile(x => x.Name == result.Name || x.Name == null)
                          .Select(x => x.Value)
                          .ToList();

            return(list);
        }
Exemplo n.º 23
0
 public IBotCommand ParseCustomTemplate(Type commandType, BotCommandTemplate template, Regex customTemplate, string input)
 {
     return(this.botCommandParsingService.ParseCustomTemplate(commandType, template, customTemplate, input));
 }
Exemplo n.º 24
0
 public bool IsDefaultCommand(BotCommandTemplate template, IEnumerable <DiscordRequestArgument> arguments, bool isCommandMatchedWithCustom)
 {
     return(this.botCommandMatchingService.IsDefaultCommand(template, arguments, isCommandMatchedWithCustom));
 }
Exemplo n.º 25
0
 public bool AreDefaultCommandArgumentsCorrect(BotCommandTemplate template, IEnumerable <DiscordRequestArgument> arguments)
 {
     return(this.botCommandMatchingService.AreDefaultCommandArgumentsCorrect(template, arguments));
 }
Exemplo n.º 26
0
        public IBotCommand ParseRequestToCommand(Type commandType, DiscordRequest request, BotCommandTemplate template)
        {
            var instance = Activator.CreateInstance(commandType);

            foreach (var property in commandType.GetProperties())
            {
                var value         = request.Arguments.First(x => x.Name.ToLowerInvariant() == property.Name.ToLowerInvariant()).Value;
                var propertyType  = template.Properties.First(x => x.Name == property.Name).Type;
                var convertedType = botCommandPropertyConversionService.ConvertType(value, propertyType);
                property.SetValue(instance, convertedType);
            }
            return((IBotCommand)instance);
        }