Ejemplo n.º 1
0
        public static Task <IUserMessage> EmbedAsync(this IMessageChannel channel, string message, EmbedBuilder embedBuilder, IGuild guild = null, ContextMessageOption options = ContextMessageOption.None, IUser replyUser = null, RetryMode retryMode = RetryMode.AlwaysRetry)
        {
            if (false == embedBuilder?.Color.HasValue)
            {
                embedBuilder = embedBuilder.WithOkColour(guild);
            }

            var error       = options.Has(ContextMessageOption.Error);
            var replyToUser = options.Has(ContextMessageOption.ReplyUser);

            return(channel.EmbedAsync
                   (
                       embedBuilder ?? new EmbedBuilder()
            {
                Description = string.Format("{0}{1}{2}",
                                            error ? "💢 " : "",
                                            replyToUser ? $"{replyUser?.Mention} " : "",
                                            message
                                            ),
                Color = (error ? Bot.Ditto.Cache.Db.EmbedErrorColour(guild)
                        : Bot.Ditto.Cache.Db.EmbedColour(guild)
                         )
            },
                       embedBuilder == null ? string.Empty : message,
                       new RequestOptions()
            {
                RetryMode = retryMode
            }
                   ));
        }
Ejemplo n.º 2
0
        public async Task H([Leftover] CommandInfo com = null)
        {
            var channel = ctx.Channel;

            if (com == null)
            {
                IMessageChannel ch = channel is ITextChannel
                    ? await((IGuildUser)ctx.User).GetOrCreateDMChannelAsync().ConfigureAwait(false)
                    : channel;

                try
                {
                    var(plainText, helpEmbed) = await GetHelpStringEmbed();

                    await ch.EmbedAsync(helpEmbed, msg : plainText ?? "").ConfigureAwait(false);
                }
                catch (Exception)
                {
                    await ReplyErrorLocalizedAsync("cant_dm").ConfigureAwait(false);
                }
                return;
            }

            var embed = _service.GetCommandHelp(com, ctx.Guild);
            await channel.EmbedAsync(embed).ConfigureAwait(false);
        }
Ejemplo n.º 3
0
        private async Task InternalHentai(IMessageChannel channel, string tag, bool noError)
        {
            var rng  = new NadekoRandom();
            var arr  = Enum.GetValues(typeof(DapiSearchType));
            var type = (DapiSearchType)arr.GetValue(new NadekoRandom().Next(2, arr.Length));
            ImageCacherObject img;

            try
            {
                img = await Service.DapiSearch(tag, type, Context.Guild?.Id, true).ConfigureAwait(false);
            }
            catch (TagBlacklistedException)
            {
                await ReplyErrorLocalized("blacklisted_tag").ConfigureAwait(false);

                return;
            }

            if (img == null)
            {
                if (!noError)
                {
                    await ReplyErrorLocalized("not_found").ConfigureAwait(false);
                }
                return;
            }

            await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                     .WithImageUrl(img.FileUrl)
                                     .WithDescription($"[{GetText("tag")}: {tag}]({img})"))
            .ConfigureAwait(false);
        }
Ejemplo n.º 4
0
        private async Task InternalHentai(IMessageChannel channel, string tag)
        {
            // create a random number generator
            var rng = new NadekoRandom();

            // get all of the DAPI search types, except first 3
            // which are safebooru (not nsfw), and 2 furry ones 🤢
            var listOfProviders = Enum.GetValues(typeof(DapiSearchType))
                                  .Cast <DapiSearchType>()
                                  .Skip(3)
                                  .ToList();

            // now try to get an image, if it fails return an error,
            // keep trying for each provider until one of them is successful, or until
            // we run out of providers. If we run out, then return an error
            ImageCacherObject img;

            do
            {
                // random index of the providers
                var num = rng.Next(0, listOfProviders.Count);
                // get the type
                var type = listOfProviders[num];
                // remove it
                listOfProviders.RemoveAt(num);
                try
                {
                    // get the image
                    img = await _service.DapiSearch(tag, type, Context.Guild?.Id, true).ConfigureAwait(false);
                }
                catch (TagBlacklistedException)
                {
                    await ReplyErrorLocalized("blacklisted_tag").ConfigureAwait(false);

                    return;
                }
                // if i can't find the image and i ran out of providers
                // return the error
                if (img == null && !listOfProviders.Any())
                {
                    await ReplyErrorLocalized("not_found").ConfigureAwait(false);

                    return;
                }
            } while (img == null);

            await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                     .WithImageUrl(img.FileUrl)
                                     .WithDescription($"[{GetText("tag")}: {tag}]({img})"))
            .ConfigureAwait(false);
        }
Ejemplo n.º 5
0
        public async Task H([Remainder] CommandInfo com = null)
        {
            var channel = Context.Channel;

            if (com == null)
            {
                IMessageChannel ch = channel is ITextChannel?await((IGuildUser)Context.User).GetOrCreateDMChannelAsync() : channel;

                await ch.EmbedAsync(GetHelpStringEmbed()).ConfigureAwait(false);

                return;
            }

            var embed = _service.GetCommandHelp(com, Context.Guild);
            await channel.EmbedAsync(embed).ConfigureAwait(false);
        }
Ejemplo n.º 6
0
        private async Task InternalHentai(IMessageChannel channel, string tag, bool noError)
        {
            tag = tag?.Trim() ?? "";

            tag = "rating%3Aexplicit+" + tag;

            var           rng      = new NadekoRandom();
            Task <string> provider = Task.FromResult("");

            switch (rng.Next(0, 4))
            {
            case 0:
                provider = GetDanbooruImageLink(tag);
                break;

            case 1:
                provider = GetGelbooruImageLink(tag);
                break;

            case 2:
                provider = GetKonachanImageLink(tag);
                break;

            case 3:
                provider = GetYandereImageLink(tag);
                break;

            default:
                break;
            }
            var link = await provider.ConfigureAwait(false);

            if (string.IsNullOrWhiteSpace(link))
            {
                if (!noError)
                {
                    await channel.SendErrorAsync("No results found.").ConfigureAwait(false);
                }
                return;
            }

            await channel.EmbedAsync(new EmbedBuilder().WithOkColor()
                                     .WithImageUrl(link)
                                     .WithDescription("Tag: " + tag))
            .ConfigureAwait(false);
        }
        public async Task StartAsync()
        {
            await _verificationService.InvokeVerificationStepAsync(this, VerificationStep.Started).ConfigureAwait(false);

            UserChannel = await GuildUser.CreateDMChannelAsync().ConfigureAwait(false);

            var eb = new EmbedBuilder().WithOkColor();

            //verification process intro
            eb.AddField(GetText("welcome_to_verification_title"), GetText("welcome_to_verification_text", AbortString));
            eb.AddField(GetText("why_do_we_need_verification_title"), GetText("why_do_we_need_verification_text"));

            //Step 1 - forum name input
            eb.AddField(GetText("write_your_forumname_title"), GetText("write_your_forumname_text"));

            await UserChannel.EmbedAsync(eb).ConfigureAwait(false);

            _client.MessageReceived += Step1_ReceiveForumNameAsync;
        }
        private async Task SendGreetMessage(IGuild guild, IUser user, IMessageChannel channel, string messageText, int autoDeleteTimer)
        {
            if (channel != null)
            {
                var rep = new ReplacementBuilder()
                          .WithDefault(user, channel, guild, _client)
                          .Build();

                if (CREmbed.TryParse(messageText, out var embedData))
                {
                    rep.Replace(embedData);
                    try {
                        var toDelete = await channel.EmbedAsync(embedData.ToEmbedBuilder(), embedData.PlainText?.SanitizeMentions() ?? "").ConfigureAwait(false);

                        if (autoDeleteTimer > 0)
                        {
                            toDelete.DeleteAfter(autoDeleteTimer);
                        }
                    } catch (Exception ex) {
                        _log.Warn(ex);
                    }
                }
                else
                {
                    var msg = rep.Replace(messageText);

                    if (!string.IsNullOrWhiteSpace(msg))
                    {
                        try {
                            var toDelete = await channel.SendMessageAsync(msg.SanitizeMentions()).ConfigureAwait(false);

                            if (autoDeleteTimer > 0)
                            {
                                toDelete.DeleteAfter(autoDeleteTimer);
                            }
                        } catch (Exception ex) {
                            _log.Warn(ex);
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
0
        public async Task H([Remainder] CommandInfo com = null)
        {
            var channel = Context.Channel;
            await Context.Channel.TriggerTypingAsync().ConfigureAwait(false);

            if (com == null)
            {
                IMessageChannel ch = channel is ITextChannel
                    ? await((IGuildUser)Context.User).GetOrCreateDMChannelAsync()
                    : channel;

                await ch.EmbedAsync(GetHelpStringEmbed()).ConfigureAwait(false);

                await Context.Channel.EmbedAsync(
                    new EmbedBuilder().WithOkColor()
                    .WithDescription($"" + Context.User.Mention + " Okaaay! Check your new message!~ 	(^◡^)")).ConfigureAwait(false);

                return;
            }

            var embed = _service.GetCommandHelp(com, Context.Guild);
            await channel.EmbedAsync(embed).ConfigureAwait(false);
        }
        /// <summary>
        /// danny kamisama
        /// </summary>
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, DiscordSocketClient client, int currentPage, Func <int, Task <EmbedBuilder> > pageFunc, int totalElements, int itemsPerPage, bool addPaginatedFooter = true)
        {
            var embed = await pageFunc(currentPage).ConfigureAwait(false);

            var lastPage = (totalElements - 1) / itemsPerPage;

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, lastPage);
            }

            var msg = await channel.EmbedAsync(embed) as IUserMessage;

            if (lastPage == 0)
            {
                return;
            }

            await msg.AddReactionAsync(arrow_left).ConfigureAwait(false);

            await msg.AddReactionAsync(arrow_right).ConfigureAwait(false);

            await Task.Delay(2000).ConfigureAwait(false);

            Action <SocketReaction> changePage = async r =>
            {
                try
                {
                    if (r.Emote.Name == arrow_left.Name)
                    {
                        if (currentPage == 0)
                        {
                            return;
                        }
                        var toSend = await pageFunc(--currentPage).ConfigureAwait(false);

                        if (addPaginatedFooter)
                        {
                            toSend.AddPaginatedFooter(currentPage, lastPage);
                        }
                        await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                    }
                    else if (r.Emote.Name == arrow_right.Name)
                    {
                        if (lastPage > currentPage)
                        {
                            var toSend = await pageFunc(++currentPage).ConfigureAwait(false);

                            if (addPaginatedFooter)
                            {
                                toSend.AddPaginatedFooter(currentPage, lastPage);
                            }
                            await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception)
                {
                    //ignored
                }
            };

            using (msg.OnReaction(client, changePage, changePage))
            {
                await Task.Delay(30000).ConfigureAwait(false);
            }

            await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
        }
Ejemplo n.º 11
0
        public static async Task SendListDialogue(this IMessageChannel channel, string headerMessage, string[] options, IDiscordClient discordClient, int timeout = 30000)
        {
            int seconds = timeout / 1000;
            //var embedFields = new List<EmbedFieldBuilder>();
            string description = "";

            if (options != null)
            {
                for (int i = 0; i < options.Length; i++)
                {
                    /*
                     * embedFields.Add(new EmbedFieldBuilder()
                     * {
                     *  //Name = string.Format("__**`{0}`**__", i+1),
                     *  Name =  "`" + i.ToString() + "`",
                     *  Value = options[i],
                     *  IsInline = false
                     * });
                     */
                    description += $"`{i}` {options[i]}\n\n";
                }
            }

            var embedBuilder = new EmbedBuilder()
            {
                Title = string.Format("{0}\n{1}\n", headerMessage, Globals.Character.HiddenSpace),
                //Fields = embedFields,
                Description = description,
                Footer      = new EmbedFooterBuilder()
                {
                    Text = string.Format("{0} {1} seconds left", Globals.Character.Clock, seconds)
                },
                Color = Bot.Ditto.Cache.Db.EmbedColour((channel as ITextChannel)?.Guild)
            };
            var message = await channel.EmbedAsync(embedBuilder);

            var tokenSource = new CancellationTokenSource();

            try
            {
                await Task.Run(async() =>
                {
                    while (seconds > 0)
                    {
                        await Task.Run(() =>
                        {
                            message.ModifyAsync((m) =>
                            {
                                embedBuilder.Footer.Text = string.Format("{0} {1} second{2} left", Globals.Character.Clock, seconds--, seconds > 1 ? "s" : "");
                                m.Embed = new Optional <Embed>(embedBuilder.Build());
                            });
                        }).ConfigureAwait(false);
                        await Task.Delay(1000, tokenSource.Token).ConfigureAwait(false);
                    }
                }, tokenSource.Token);
            }
            catch (TaskCanceledException) { }
            //try { await Task.Delay(timeout, tokenSource.Token).ConfigureAwait(false); } catch(TaskCanceledException) { }

            await Task.Run(() =>
            {
                Task.Run(async() =>
                {
                    await Task.Delay(1000).ConfigureAwait(false);
                    await message.DeleteAsync().ConfigureAwait(false);
                });
            }).ConfigureAwait(false);
        }
Ejemplo n.º 12
0
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, DiscordSocketClient client, int currentPage, Func <int, Task <EmbedBuilder> > pageFunc, int?lastPage = null, bool addPaginatedFooter = true)
        {
            var embed = await pageFunc(currentPage).ConfigureAwait(false);

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, lastPage);
            }

            var msg = await channel.EmbedAsync(embed);

            if (lastPage == 0)
            {
                return;
            }


            await msg.AddReactionAsync(ArrowLeft).ConfigureAwait(false);

            await msg.AddReactionAsync(ArrowRight).ConfigureAwait(false);

            await Task.Delay(2000).ConfigureAwait(false);

            async void ChangePage(SocketReaction r)
            {
                try {
                    if (r.Emote.Name == ArrowLeft.Name)
                    {
                        if (currentPage == 0)
                        {
                            return;
                        }
                        var toSend = await pageFunc(--currentPage).ConfigureAwait(false);

                        if (addPaginatedFooter)
                        {
                            toSend.AddPaginatedFooter(currentPage, lastPage);
                        }
                        await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                    }
                    else if (r.Emote.Name == ArrowRight.Name)
                    {
                        if (lastPage != null && !(lastPage > currentPage))
                        {
                            return;
                        }
                        var toSend = await pageFunc(++currentPage).ConfigureAwait(false);

                        if (addPaginatedFooter)
                        {
                            toSend.AddPaginatedFooter(currentPage, lastPage);
                        }
                        await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                    }
                }
                catch (Exception) {
                    //ignored
                }
            }

            using (msg.OnReaction(client, ChangePage, ChangePage))
            {
                await Task.Delay(30000).ConfigureAwait(false);
            }

            await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// danny kamisama
        /// </summary>
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, int currentPage, Func <int, EmbedBuilder> pageFunc, int?lastPage = null, bool addPaginatedFooter = true)
        {
            lastPage += 1;
            var embed = pageFunc(currentPage);

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, lastPage);
            }

            var msg = await channel.EmbedAsync(embed) as IUserMessage;

            if (currentPage >= lastPage && lastPage == 1)
            {
                return;
            }

            await msg.AddReactionAsync(arrow_left).ConfigureAwait(false);

            await msg.AddReactionAsync(arrow_right).ConfigureAwait(false);

            await Task.Delay(2000).ConfigureAwait(false);

            Action <SocketReaction> changePage = async r =>
            {
                try
                {
                    if (r.Emoji.Name == arrow_left)
                    {
                        if (currentPage == 1)
                        {
                            return;
                        }
                        var toSend = pageFunc(--currentPage);
                        if (addPaginatedFooter)
                        {
                            toSend.AddPaginatedFooter(currentPage, lastPage);
                        }
                        await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                    }
                    else if (r.Emoji.Name == arrow_right)
                    {
                        if (lastPage == null || lastPage > currentPage)
                        {
                            var toSend = pageFunc(++currentPage);
                            if (addPaginatedFooter)
                            {
                                toSend.AddPaginatedFooter(currentPage, lastPage);
                            }
                            await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                        }
                    }
                }
                catch (Exception ex) { Console.WriteLine(ex); }
            };

            using (msg.OnReaction(changePage, changePage))
            {
                await Task.Delay(30000).ConfigureAwait(false);
            }

            await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
        }
        /// <summary>
        /// Creates a paginated confirm embed.
        /// </summary>
        /// <param name="channel">Channel to embed in.</param>
        /// <param name="client">DiscordSocketClient instance</param>
        /// <param name="currentPage">current page from 0 to lastpage</param>
        /// <param name="pageFunc">Func returning EmbedBuilder for each page</param>
        /// <param name="pageCount">Total number of pages.</param>
        /// <param name="addPaginatedFooter">whether footer with current page numbers should be added or not</param>
        /// <param name="reactUsers">additional users which can change pages</param>
        /// <param name="pageChangeAllowedWithPermissions">overturn reactUsers if certain permission is available</param>
        /// <returns></returns>
        public static async Task SendPaginatedConfirmAsync(this IMessageChannel channel, DiscordSocketClient client, int currentPage, Func <int, Task <EmbedBuilder> > pageFunc, int?pageCount = null, bool addPaginatedFooter = true, IGuildUser[] reactUsers = null, Func <GuildPermissions, bool> pageChangeAllowedWithPermissions = null)
        {
            reactUsers ??= new IGuildUser[0];
            if (pageChangeAllowedWithPermissions == null)
            {
                pageChangeAllowedWithPermissions = gp => gp.ManageMessages;
            }

            var embed = await pageFunc(currentPage).ConfigureAwait(false);

            if (addPaginatedFooter)
            {
                embed.AddPaginatedFooter(currentPage, pageCount);
            }

            var msg = await channel.EmbedAsync(embed);

            if (pageCount == 0)
            {
                return;
            }

            var _ = Task.Run(async() => {
                await msg.AddReactionAsync(ArrowLeft).ConfigureAwait(false);
                await msg.AddReactionAsync(ArrowRight).ConfigureAwait(false);

                await Task.Delay(ReactionStartDelay).ConfigureAwait(false);

                async void ChangePage(SocketReaction r)
                {
                    try {
                        if (!r.User.IsSpecified || r.User.Value is IGuildUser gu && reactUsers.All(u => u.Id != r.UserId) && !pageChangeAllowedWithPermissions.Invoke(gu.GuildPermissions) && !gu.GuildPermissions.Administrator)
                        {
                            return;
                        }

                        if (r.Emote.Name == ArrowLeft.Name)
                        {
                            if (currentPage != 0)
                            {
                                var toSend = await pageFunc(--currentPage).ConfigureAwait(false);
                                if (addPaginatedFooter)
                                {
                                    toSend.AddPaginatedFooter(currentPage, pageCount);
                                }
                                await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                            }
                        }
                        else if (r.Emote.Name == ArrowRight.Name)
                        {
                            if (pageCount == null || currentPage < pageCount - 1)
                            {
                                var toSend = await pageFunc(++currentPage).ConfigureAwait(false);
                                if (addPaginatedFooter)
                                {
                                    toSend.AddPaginatedFooter(currentPage, pageCount);
                                }
                                await msg.ModifyAsync(x => x.Embed = toSend.Build()).ConfigureAwait(false);
                            }
                        }
                    } catch (InvalidOperationException e) {
                        LogManager.GetCurrentClassLogger().Error(e);
                    } catch { }
                }

                using (msg.OnReaction(client, ChangePage, ChangePage)) {
                    await Task.Delay(ReactionTime).ConfigureAwait(false);
                }

                await msg.RemoveAllReactionsAsync().ConfigureAwait(false);
            });
        }
 public static Task <IUserMessage> SendConfirmAsync(this IMessageChannel ch, string text, string title = null, string url = null, string footer = null)
 => ch.EmbedAsync(GetSimpleEmbedBuilder(text, title, url, footer).WithOkColor());
Ejemplo n.º 16
0
        public static async Task SendPagedMessageAsync(this IMessageChannel channel,
                                                       IDiscordClient discordClient,
                                                       EmbedBuilder embedBuilder,
                                                       Func <IUserMessage, int, EmbedBuilder> onPageChange, // message, page
                                                       int pageCount              = int.MaxValue,
                                                       bool displayPage           = true,
                                                       int timeout                = 30000,
                                                       int addedTimeoutOnReaction = 30000)
        {
            int      page           = 1;
            var      reactionEmotes = _optionsEmojiPaging;
            DateTime expireDate     = DateTime.Now + TimeSpan.FromMilliseconds(timeout);
            var      tokenSource    = new CancellationTokenSource();

            embedBuilder.WithFooter(new EmbedFooterBuilder().WithText($"{Globals.Character.Clock} expires at {expireDate:t} | {page}/{pageCount}"));
            embedBuilder.Color = Bot.Ditto.Cache.Db.EmbedColour((channel as ITextChannel)?.Guild);
            var message = await channel.EmbedAsync(embedBuilder).ConfigureAwait(false);

            foreach (var reaction in reactionEmotes)
            {
                await Task.Run(() =>
                {
                    message.AddReactionAsync(reaction,
                                             DiscordHelper.GetRequestOptions(true).SetRetryMode(RetryMode.AlwaysRetry)
                                             );
                }).ConfigureAwait(false);
            }

            // onChanged event, either for adding or removing a reaction
            var onChanged = new Func <SocketReaction, Task>(async r =>
            {
                if (r.UserId != discordClient.CurrentUser.Id)
                {
                    var option = reactionEmotes.Select((Value, Index) => new { Value, Index }).FirstOrDefault(a => a.Value.Name == r.Emote.Name);
                    if (option != null && option.Value != null)
                    {
                        var execute = false;
                        if (option.Value == _optionsEmojiPaging.ElementAt(0) && page > 1)
                        {
                            execute = true;
                            page--;
                        }
                        else if (option.Value == _optionsEmojiPaging.ElementAt(1) && page < pageCount)
                        {
                            execute = true;
                            page++;
                        }

                        expireDate += TimeSpan.FromMilliseconds(addedTimeoutOnReaction);
                        if (execute)
                        {
                            embedBuilder = onPageChange?.Invoke(message, page);
                            embedBuilder.WithFooter(new EmbedFooterBuilder().WithText($"{Globals.Character.Clock} expires at {expireDate:t}{(displayPage ? $" | {page}/{pageCount}" : "")}"));
                            embedBuilder.Color = Bot.Ditto.Cache.Db.EmbedColour((channel as ITextChannel)?.Guild);
                            try
                            {
                                await message.ModifyAsync((m) => m.Embed = new Optional <Embed>(embedBuilder.Build()),
                                                          new RequestOptions()
                                {
                                    RetryMode = RetryMode.AlwaysRetry, Timeout = 500
                                }
                                                          ).ConfigureAwait(false);
                            }
                            catch { }
                        }
                    }
                }
            });

            Bot.Ditto.ReactionHandler.Add(message, onChanged, onChanged, null);

            // Wait until date >= expireDate
            try
            {
                await Task.Run(async() =>
                {
                    while (DateTime.Now < expireDate)
                    {
                        await Task.Delay(500, tokenSource.Token).ConfigureAwait(false);
                    }
                }, tokenSource.Token);
            }
            catch (OperationCanceledException) { }

            // Clear reactions and remove the footer
            Bot.Ditto.ReactionHandler.Remove(message);
            await message.RemoveAllReactionsAsync().ConfigureAwait(false);

            try
            {
                await message.ModifyAsync((m) =>
                {
                    embedBuilder.Footer = new EmbedFooterBuilder();
                    m.Embed             = new Optional <Embed>(embedBuilder.Build());
                },
                                          new RequestOptions()
                {
                    RetryMode = RetryMode.AlwaysRetry
                }).ConfigureAwait(false);
            }
            catch { }
        }
Ejemplo n.º 17
0
        public static async Task <int> SendOptionDialogueAsync(this IMessageChannel channel,
                                                               string headerMessage,
                                                               IEnumerable <string> options,
                                                               IDiscordClient discordClient,
                                                               bool awaitSingleReaction,
                                                               IEnumerable <IEmote> reactionEmotes = null,
                                                               Action <int, string> onReaction     = null,
                                                               int timeout = 30000,
                                                               int addedTimeoutOnReaction = 30000
                                                               )
        {
            int selection = -1;
            int seconds   = timeout / 1000;

            if (reactionEmotes == null || reactionEmotes.Count() <= 0)
            {
                reactionEmotes = _OptionsEmoji;
            }

            var embedFields = new List <EmbedFieldBuilder>();

            if (options != null)
            {
                for (int i = 0; i < options.Count(); i++)
                {
                    embedFields.Add(new EmbedFieldBuilder()
                    {
                        //Name = string.Format("__**`{0}`**__", i+1),
                        Name     = reactionEmotes.ElementAt(i).Name,
                        Value    = options.ElementAt(i),
                        IsInline = true
                    });
                }
            }

            var embedBuilder = new EmbedBuilder()
            {
                Description = headerMessage,
                Footer      = new EmbedFooterBuilder()
                {
                    Text = string.Format("{0} {1} seconds left", Globals.Character.Clock, seconds)
                },
                Color = Bot.Ditto.Cache.Db.EmbedColour((channel as ITextChannel)?.Guild)
            };

            if (embedFields.Count > 0)
            {
                embedBuilder.Fields      = embedFields;
                embedBuilder.Description = string.Format("{0}\n{1}\n", headerMessage, Globals.Character.HiddenSpace);
            }

            var message = await channel.EmbedAsync(embedBuilder);

            foreach (var emote in reactionEmotes)
            {
                await Task.Run(() =>
                {
                    message.AddReactionAsync(emote, DiscordHelper.GetRequestOptions(true).SetRetryMode(RetryMode.AlwaysRetry));
                }).ConfigureAwait(false);
            }

            var tokenSource = new CancellationTokenSource();

            Bot.Ditto.ReactionHandler.Add(message, (r) =>
            {
                if (r.UserId != discordClient.CurrentUser.Id)
                {
                    var option = reactionEmotes.Select((Value, Index) => new { Value, Index }).FirstOrDefault(a => a.Value.Name == r.Emote.Name);
                    if (option != null && option.Value != null)
                    {
                        selection = option.Index + 1;
                        onReaction?.Invoke(option.Index, option.Value.Name);
                        seconds += addedTimeoutOnReaction / 1000;
                    }
                    if (awaitSingleReaction)
                    {
                        tokenSource.Cancel();
                    }
                }
                return(Task.CompletedTask);
            });

            try
            {
                await Task.Run(async() =>
                {
                    while (seconds > 0)
                    {
                        await Task.Run(() =>
                        {
                            message.ModifyAsync((m) =>
                            {
                                embedBuilder.Footer.Text = string.Format("{0} {1} second{2} left", Globals.Character.Clock, seconds--, seconds > 1 ? "s" : "");
                                m.Embed = new Optional <Embed>(embedBuilder.Build());
                            });
                        }, tokenSource.Token).ConfigureAwait(false);
                        await Task.Delay(1000, tokenSource.Token).ConfigureAwait(false);
                    }
                }, tokenSource.Token);
            }
            catch (OperationCanceledException) { }

            var __ = Task.Run(async() =>
            {
                await Task.Delay(1000).ConfigureAwait(false);
                await message.DeleteAsync().ConfigureAwait(false);
            });

            Bot.Ditto.ReactionHandler.Remove(message);
            return(selection);
        }