Exemple #1
0
        private async Task HandleCommandResultAsync(Optional <CommandInfo> command, ICommandContext context, IResult result)
        {
            _commandScopes.TryRemove(context, out var commandScope);

            using (commandScope)
            {
                if (!result.IsSuccess)
                {
                    var error = $"{result.Error}: {result.ErrorReason}";

                    if (!string.Equals(result.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                    {
                        Log.LogWarning(error);
                    }
                    else
                    {
                        Log.LogError(error);
                    }

                    if (result.Error != CommandError.Exception)
                    {
                        await _commandErrorHandler.AssociateError(context.Message, error);
                    }
                    else
                    {
                        var sanitizedReason = FormatUtilities.SanitizeEveryone(result.ErrorReason);
                        await context.Channel.SendMessageAsync($"Error: {sanitizedReason}");
                    }
                }
            }
        }
Exemple #2
0
        /// <inheritdoc />
        public async Task UseTagAsync(ulong guildId, ulong channelId, string name)
        {
            AuthorizationService.RequireClaims(AuthorizationClaim.UseTag);

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("The tag name cannot be blank or whitespace.", nameof(name));
            }

            name = name.Trim().ToLower();

            using (var transaction = await TagRepository.BeginUseTransactionAsync())
            {
                var tag = await TagRepository.ReadSummaryAsync(guildId, name);

                if (tag is null)
                {
                    throw new InvalidOperationException($"The tag '{name}' does not exist.");
                }

                var channel = await DiscordClient.GetChannelAsync(channelId);

                if (!(channel is IMessageChannel messageChannel))
                {
                    throw new InvalidOperationException($"The channel '{channel.Name}' is not a message channel.");
                }

                var sanitizedContent = FormatUtilities.SanitizeEveryone(tag.Content);

                try
                {
                    await messageChannel.SendMessageAsync(sanitizedContent);
                }
                finally
                {
                    await TagRepository.TryIncrementUsesAsync(guildId, name);
                }

                transaction.Commit();
            }
        }
Exemple #3
0
        /// <inheritdoc />
        public async Task HandleNotificationAsync(MessageReceivedNotification notification, CancellationToken cancellationToken = default)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!(notification.Message is IUserMessage userMessage) ||
                (userMessage.Author is null))
            {
                return;
            }

            if (!(userMessage.Author is IGuildUser author) ||
                (author.Guild is null) ||
                author.IsBot ||
                author.IsWebhook)
            {
                return;
            }

            var argPos = 0;

            if (!userMessage.HasCharPrefix('!', ref argPos) && !userMessage.HasMentionPrefix(DiscordClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (userMessage.Content.Length <= 1)
            {
                return;
            }

            var commandContext = new CommandContext(DiscordClient, userMessage);

            await AuthorizationService.OnAuthenticatedAsync(author);

            IResult commandResult = null;
            var     commandTimer  = Stopwatch.StartNew();

            try
            {
                commandResult = await CommandService.ExecuteAsync(commandContext, argPos, ServiceProvider);
            }
            finally
            {
                commandTimer.Stop();
                var duration = commandTimer.ElapsedMilliseconds;

                if (!(_stats is null) && (commandResult.IsSuccess || !string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase)))
                {
                    var commandInfo = CommandService.Search(commandContext, argPos).Commands.FirstOrDefault();
                    var name        = commandInfo.Command?.Name.ToLowerInvariant();

                    _stats?.Timer("command_duration_ms", duration,
                                  tags: new[] { $"guild:{commandContext.Guild.Name}", $"success:{commandResult.IsSuccess}", $"command:{name}" });
                }
            }

            if (!commandResult.IsSuccess)
            {
                var error = $"{commandResult.Error}: {commandResult.ErrorReason}";

                if (string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                {
                    Log.Error(error);
                }
                else
                {
                    Log.Warning(error);
                }

                if (commandResult.Error == CommandError.Exception)
                {
                    await commandContext.Channel.SendMessageAsync($"Error: {FormatUtilities.SanitizeEveryone(commandResult.ErrorReason)}");
                }
                else
                {
                    await CommandErrorHandler.AssociateError(userMessage, error);
                }
            }

            stopwatch.Stop();
            Log.Information($"Command took {stopwatch.ElapsedMilliseconds}ms to process: {commandContext.Message}");
        }
        /// <inheritdoc />
        public async Task HandleNotificationAsync(MessageReceivedNotification notification, CancellationToken cancellationToken = default)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            if (!(notification.Message is IUserMessage userMessage) ||
                (userMessage.Author is null))
            {
                return;
            }

            if (!(userMessage.Author is IGuildUser author) ||
                (author.Guild is null) ||
                author.IsBot ||
                author.IsWebhook)
            {
                return;
            }

            var argPos = 0;

            if (!userMessage.HasCharPrefix('!', ref argPos) && !userMessage.HasMentionPrefix(DiscordClient.CurrentUser, ref argPos))
            {
                return;
            }

            if (userMessage.Content.Length <= 1)
            {
                return;
            }

            var commandContext = new CommandContext(DiscordClient, userMessage);

            await AuthorizationService.OnAuthenticatedAsync(author);

            var commandResult = await CommandService.ExecuteAsync(commandContext, argPos, ServiceProvider);

            if (!commandResult.IsSuccess)
            {
                var error = $"{commandResult.Error}: {commandResult.ErrorReason}";

                if (string.Equals(commandResult.ErrorReason, "UnknownCommand", StringComparison.OrdinalIgnoreCase))
                {
                    Log.Error(error);
                }
                else
                {
                    Log.Warning(error);
                }

                if (commandResult.Error == CommandError.Exception)
                {
                    await commandContext.Channel.SendMessageAsync($"Error: {FormatUtilities.SanitizeEveryone(commandResult.ErrorReason)}");
                }
                else
                {
                    await CommandErrorHandler.AssociateError(userMessage, error);
                }
            }

            stopwatch.Stop();
            Log.Information($"Command took {stopwatch.ElapsedMilliseconds}ms to process: {commandContext.Message}");
        }