Esempio n. 1
0
        private CommandUsage AttemptToRunCommand(CommandReceivedEventArgs e,
                                                 IBotCommand botCommand, IChatClient chatClient1, IList <string> args)
        {
            try
            {
                _logger.LogInformation($"{e.ChatUser.DisplayName} is running the {botCommand.GetType().Name} command.");

                if (e.ChatUser.CanRunCommand(botCommand))
                {
                    if (args.Any())
                    {
                        e.Arguments.Clear();
                        foreach (string arg in args)
                        {
                            e.Arguments.Add(arg);
                        }
                    }
                    return(botCommand.Process(chatClient1, e));
                }

                chatClient1.SendMessage(
                    $"Sorry, {e.ChatUser.DisplayName}! You don't have permission to use the !{e.CommandWord} command.");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Failed to run a command.");
            }

            return(new CommandUsage(e.ChatUser.DisplayName, DateTimeOffset.UtcNow, botCommand));
        }
Esempio n. 2
0
        private void DoTheThing(CommandReceivedEventArgs e, IChatClient chatClient, IBotCommand botCommand)
        {
            CommandUsage commandUsage       = AttemptToRunCommand(e, botCommand, chatClient);
            var          commandUsageEntity = new CommandUsageEntity(e.CommandWord, botCommand.GetType().FullName,
                                                                     e.ChatUser.UserId, e.ChatUser.DisplayName, chatClient.GetType().Name);

            _repository.Create(commandUsageEntity);
            _usageTracker.RecordUsage(commandUsage);
        }
Esempio n. 3
0
        /// <summary>
        /// Проверить команду на возможность выполнения
        /// </summary>
        /// <param name="command">Команда</param>
        /// <param name="chat">Чат</param>
        /// <param name="errorMessage">Сообщение об ошибке</param>
        /// <returns>True, если команду можно выполнить; Иначе False</returns>
        private bool CanExecuteCommand(IBotCommand command, Chat chat, out string errorMessage)
        {
            var attributes = command.GetType().GetCustomAttributes(false);

            foreach (CommandChatTypeAttribute commandChatType in attributes.OfType <CommandChatTypeAttribute>())
            {
                if (commandChatType.ChatTypes.All(i => i != chat.TelegramChatType))
                {
                    errorMessage = $"Данную команду можно использовать в следующих чатах: {string.Join(',', commandChatType.ChatTypes.Select(i => i.GetFullName()))}";
                    return(false);
                }
                else
                {
                    //  ничего не делаем
                }
            }

            errorMessage = string.Empty;
            return(true);
        }
Esempio n. 4
0
        public T ParseArgs <T>(IBotCommand command, SocketUserMessage message, int argsPos)
            where T : class, new()
        {
            var commandType = command.GetType();
            var args        = message.Content.Substring(argsPos).Split(' ', StringSplitOptions.RemoveEmptyEntries).ToArray();

            if (!_parsers.TryGetValue(commandType, out var parser))
            {
                var argsDesc = commandType.GetCustomAttributes <CommandArgAttribute>().OrderBy(a => a.Order).ToList();
                _cachedAttributes.TryAdd(commandType, argsDesc);

                Expression <Func <string[], IEnumerable <CommandArgAttribute>, object> > expr = (arguments, attributes) =>
                                                                                                Parse <T>(arguments, attributes);

                _initialization.TryAdd(commandType, new ConcurrentDictionary <string, Action <object, object> >());

                foreach (var attribute in argsDesc)
                {
                    var r1     = Expression.Parameter(typeof(object));
                    var v1     = Expression.Parameter(typeof(object));
                    var member = (MemberInfo)typeof(T).GetProperty(attribute.Name) ?? typeof(T).GetField(attribute.Name);

                    var t = (member as PropertyInfo)?.PropertyType ?? (member as FieldInfo)?.FieldType;
                    if (t == null)
                    {
                        continue;
                    }

                    var c = Expression.Convert(v1, t);
                    var e = Expression.Bind(member, c).Expression;
                    var l = Expression.Lambda <Action <object, object> >(e, r1, v1).Compile();
                    _initialization[commandType].TryAdd(attribute.Name, l);
                }

                parser = expr.Compile();
                _parsers.TryAdd(commandType, parser);
            }

            return((T)parser(args, _cachedAttributes[commandType]));
        }
Esempio n. 5
0
        public bool ExecutionAllowed(IBotCommand botCommand, SocketMessage message)
        {
            var commandName = botCommand.GetType().FullName;
            var userId      = message.Author.Id;
            var guild       = message.Channel as SocketGuildChannel;
            var guildId     = guild?.Guild.Id;
            var dateTime    = DateTime.Now;


            Console.WriteLine("command policy");
            Console.WriteLine(commandName);
            if (pigBotDbContext.BlackLists.FirstOrDefault(b => b.UserId == userId) != null)
            {
                return(false);
            }

            if (guild == null)
            {
                return(true);
            }

            if (pigBotDbContext.CommandPolicies.FirstOrDefault(c => c.Allowed == false && c.GuildId == guildId && c.CommandName == commandName) != null)
            {
                return(false);
            }

            var cooldownPolicy =
                pigBotDbContext.CoolDownPolicies.FirstOrDefault(c =>
                                                                c.CommandName == commandName && c.GuildId == guildId);

            if (cooldownPolicy != null)
            {
                if (cooldownPolicy.LastExecution.AddSeconds(cooldownPolicy.CooldownSeconds) >= dateTime)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 6
0
        private CommandUsage AttemptToRunCommand(CommandReceivedEventArgs e, IBotCommand botCommand,
                                                 IChatClient chatClient1)
        {
            try
            {
                _logger.LogInformation($"{e.ChatUser.DisplayName} is running the {botCommand.GetType().Name} command.");

                if (e.ChatUser.CanRunCommand(botCommand))
                {
                    return(botCommand.Process(chatClient1, e));
                }

                chatClient1.SendMessage(
                    $"Sorry, {e.ChatUser.DisplayName}! You don't have permission to use the !{e.CommandWord} command.");
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Failed to run a command.");
            }

            return(null);
        }
 /// <summary>
 /// Получить имя команды по объекту класса
 /// </summary>
 /// <param name="botCommand">Команда бота</param>
 /// <returns>Имя команды</returns>
 public static string GetCommandName(this IBotCommand botCommand)
 {
     return botCommand.GetType().GetTypeNameAsCommand();
 }