Example #1
0
        public async Task <RuntimeResult> ChangeGuildIconAsync(Uri url = null)
        {
            if (url == null)
            {
                await ReplyAsync("", embed : EmbedHelper.FromInfo("New icon", "Please upload your new server icon.").Build()).ConfigureAwait(false);

                var response = await InteractiveService.NextMessageAsync(Context, timeout : TimeSpan.FromMinutes(5)).ConfigureAwait(false);

                if (response == null)
                {
                    return(CommandRuntimeResult.FromError("You did not upload your picture in time."));
                }
                if (!Uri.TryCreate(response.Content, UriKind.RelativeOrAbsolute, out url))
                {
                    var attachment = response.Attachments.FirstOrDefault();
                    if (attachment?.Height != null)
                    {
                        url = new Uri(response.Attachments.FirstOrDefault().Url);
                    }
                    else
                    {
                        return(CommandRuntimeResult.FromError("You did not upload any valid pictures."));
                    }
                }
            }
            using (var image = await WebHelper.GetFileStreamAsync(HttpClient, url).ConfigureAwait(false))
            {
                // ReSharper disable once AccessToDisposedClosure
                await Context.Guild.ModifyAsync(x => x.Icon = new Image(image)).ConfigureAwait(false);
            }
            return(CommandRuntimeResult.FromSuccess("The server icon has been changed!"));
        }
Example #2
0
        /// <summary>
        ///     Post-command execution handling.
        /// </summary>
        private async Task OnCommandExecutedAsync(Optional <CommandInfo> commandInfo, ICommandContext context, IResult result)
        {
            // Bails if the generic result doesn't have an error reason, or if it's an unknown command error.
            if (string.IsNullOrEmpty(result.ErrorReason) || result.Error == CommandError.UnknownCommand)
            {
                return;
            }
            var embed = new EmbedBuilder();

            switch (result)
            {
            case CommandRuntimeResult customResult:
                switch (customResult.Type)
                {
                case ResultType.Unknown:
                    break;

                case ResultType.Info:
                    embed = EmbedHelper.FromInfo(description: customResult.Reason);
                    break;

                case ResultType.Warning:
                    embed = EmbedHelper.FromWarning(description: customResult.Reason);
                    break;

                case ResultType.Error:
                    embed = EmbedHelper.FromError(description: customResult.Reason);
                    break;

                case ResultType.Success:
                    embed = EmbedHelper.FromSuccess(description: customResult.Reason);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                break;

            default:
                embed = EmbedHelper.FromError(description: result.ErrorReason);
                break;
            }
            await context.Channel.SendMessageAsync("", embed : embed.Build()).ConfigureAwait(false);

            if (commandInfo.IsSpecified)
            {
                _loggingService.Log(
                    $"{context.User} executed \"{commandInfo.Value.Aliases.FirstOrDefault()}\" in {context.Message.GetPostedAt()}." +
                    Environment.NewLine +
                    $"Result: {result.ErrorReason}" +
                    Environment.NewLine +
                    $"Result Type: {result.GetType().Name}",
                    LogSeverity.Verbose);
            }
        }
Example #3
0
        private async Task HandlePostCommandExecutionAsync(Optional <CommandInfo> commandInfo, ICommandContext context,
                                                           IResult result)
        {
            if (result.Error == CommandError.UnknownCommand)
            {
                return;
            }
            if (!string.IsNullOrEmpty(result.ErrorReason))
            {
                Embed embed;
                switch (result)
                {
                case CommonResult commonResult:
                    switch (commonResult.CommonResultType)
                    {
                    default:
                        embed = EmbedHelper.FromInfo(description: commonResult.Reason);
                        break;

                    case CommonResultType.Warning:
                        embed = EmbedHelper.FromWarning(description: commonResult.Reason);
                        break;

                    case CommonResultType.Error:
                        embed = EmbedHelper.FromError(description: commonResult.Reason);
                        break;

                    case CommonResultType.Success:
                        embed = EmbedHelper.FromSuccess(description: commonResult.Reason);
                        break;
                    }

                    break;

                default:
                    embed = EmbedHelper.FromError(description: result.ErrorReason);
                    break;
                }

                var message = await context.Channel.SendMessageAsync("", embed : embed).ConfigureAwait(false);

                if (result.Error.HasValue)
                {
                    _ = Task.Delay(TimeSpan.FromSeconds(5))
                        .ContinueWith(_ => message?.DeleteAsync().ConfigureAwait(false));
                }
            }
        }
Example #4
0
        public async Task <RuntimeResult> AvatarConfigureAsync()
        {
            await ReplyAsync("", embed : EmbedHelper.FromInfo(description : "Please upload the new avatar.").Build()).ConfigureAwait(false);

            var message = await InteractiveService.NextMessageAsync(Context,
                                                                    new EnsureFromUserCriterion(Context.User.Id), TimeSpan.FromMinutes(5)).ConfigureAwait(false);

            Uri imageUri = null;

            if (!string.IsNullOrEmpty(message.Content))
            {
                var image = await WebHelper.GetImageUriAsync(HttpClient, message.Content).ConfigureAwait(false);

                if (image != null)
                {
                    imageUri = image;
                }
            }
            var attachment = message.Attachments.FirstOrDefault();

            if (attachment?.Height != null)
            {
                Uri.TryCreate(attachment.Url, UriKind.RelativeOrAbsolute, out imageUri);
            }
            if (imageUri == null)
            {
                return(CommandRuntimeResult.FromError("No valid images were detected."));
            }
            var imageStream = await WebHelper.GetFileStreamAsync(HttpClient, imageUri).ConfigureAwait(false);

            try
            {
                // ReSharper disable once AccessToDisposedClosure
                await Context.Client.CurrentUser.ModifyAsync(x => x.Avatar = new Image(imageStream)).ConfigureAwait(false);
            }
            finally
            {
                imageStream.Dispose();
            }
            return(CommandRuntimeResult.FromSuccess("Successfully changed avatar."));
        }
Example #5
0
        public async Task <RuntimeResult> LocationLookupAsync([Remainder] string location)
        {
            var geocodeResults = (await Geocoding.GeocodeAsync(location).ConfigureAwait(false)).ToList();

            if (!geocodeResults.Any())
            {
                return(CommandRuntimeResult.FromError("No results found."));
            }

            var embed = EmbedHelper.FromInfo();

            foreach (var geocodeResult in geocodeResults)
            {
                if (embed.Fields.Count > 10)
                {
                    break;
                }
                embed.AddField(geocodeResult.FormattedAddress, geocodeResult.Coordinates);
            }
            await ReplyAsync("", embed : embed.Build()).ConfigureAwait(false);

            return(CommandRuntimeResult.FromSuccess());
        }
Example #6
0
        public async Task <RuntimeResult> ReportIncidentAsync()
        {
            // #1, query guild from user.
            var guilds = Context.Client.Guilds.Where(guild => guild.Users.Any(user => user.Id == Context.User.Id))
                         .ToList();
            var guildBuilder = new StringBuilder("Which guild would you like to report to? (Choose by number)\n\n");
            int guildCount   = 0;

            foreach (var guild in guilds)
            {
                guildBuilder.AppendLine($"{guildCount}. {guild.Name}");
                guildCount++;
            }
            await ReplyAsync("",
                             embed : EmbedHelper.FromInfo(EmbedTitle, guildBuilder.ToString().Truncate(2000)).Build()).ConfigureAwait(false);

            var selectionMessage = await InteractiveService.NextMessageAsync(Context, timeout : _responseTimeout).ConfigureAwait(false);

            if (selectionMessage == null)
            {
                return(CommandRuntimeResult.FromError($"You did not reply in {_responseTimeout.Humanize()}."));
            }
            if (!int.TryParse(_numberRegex.Match(selectionMessage.Content)?.Value, out int selection) ||
                selection > guilds.Count)
            {
                return(CommandRuntimeResult.FromError("You did not pick a valid selection."));
            }

            // #2, query report from user.
            // TODO: Allow users to upload more than one image.
            await ReplyAsync("",
                             embed : EmbedHelper.FromInfo(EmbedTitle,
                                                          "Please describe the incident in details, preferably with evidence.").Build()).ConfigureAwait(false);

            var reportMessage = await InteractiveService.NextMessageAsync(Context, timeout : _responseTimeout).ConfigureAwait(false);

            if (reportMessage == null)
            {
                return(CommandRuntimeResult.FromError($"You did not reply in {_responseTimeout.Humanize()}."));
            }
            string reportContent = reportMessage.Content;

            if (reportContent.Length > 2048)
            {
                return(CommandRuntimeResult.FromError("Your report was too long. Please start over."));
            }

            // #2.1, confirm report from user.
            var reportEmbed = new EmbedBuilder
            {
                Author = new EmbedAuthorBuilder
                {
                    Name    = $"A new report has been filed by {Context.User}...",
                    IconUrl = Context.User.GetAvatarUrlOrDefault()
                },
                Description  = reportContent,
                ThumbnailUrl = Config.Icons.Warning,
                Color        = Color.Red
            };

            if (reportMessage.Attachments.Any())
            {
                reportEmbed.AddField("Attachments", string.Join(", ", reportMessage.Attachments.Select(x => x.Url)));
            }
            reportEmbed.AddField("Report time", DateTimeOffset.UtcNow);
            await ReplyAsync("Please review your report. Enter Y to confirm.", embed : reportEmbed.Build()).ConfigureAwait(false);

            var confirmMessage = await InteractiveService.NextMessageAsync(Context, timeout : _responseTimeout).ConfigureAwait(false);

            if (confirmMessage == null)
            {
                return(CommandRuntimeResult.FromError($"You did not reply in {_responseTimeout.Humanize()}."));
            }
            if (!confirmMessage.Content.ToLower().Contains("y"))
            {
                return(CommandRuntimeResult.FromInfo("Dropping report..."));
            }

            // #3, send the report.
            var reportChannel = await GetReportChannelAsync(guilds[selection]).ConfigureAwait(false);

            var reportRoles = await GetModeratorRolesAsync(guilds[selection]).ConfigureAwait(false);

            await reportChannel.SendMessageAsync(
                string.Join(", ", reportRoles.Select(x => x.Mention)) ?? "New report has been filed.",
                embed : reportEmbed.Build()).ConfigureAwait(false);

            return(CommandRuntimeResult.FromSuccess("Your report has been sent."));
        }