protected virtual async Task ReplyInteractiveAsync(ServiceResponse response, string titleSuccess)
        {
            var messageBuilder = new StringBuilder();

            messageBuilder.AppendLine(response.Message);
            var callbackCounter = 1;

            foreach (var resultInterActiveCallback in response.InterActiveCallbacks)
            {
                var emoji = EmojiService.Get(callbackCounter);
                messageBuilder.AppendLine(emoji.Name + " " + resultInterActiveCallback.Key);
                callbackCounter++;
            }
            var embed = BuildEmbed(LocalizationService.Get(typeof(i18n), "Base_Messages_Reply_Interactive"), messageBuilder.ToString(), Color.Orange);
            var reply = new ReactionCallbackData(string.Empty, embed, TimeSpan.FromSeconds(30));

            callbackCounter = 1;
            foreach (var resultInterActiveCallback in response.InterActiveCallbacks)
            {
                var emoji = EmojiService.Get(callbackCounter);
                reply.WithCallback(emoji, c => ReplyWithInteractive(resultInterActiveCallback.Value, titleSuccess));
                callbackCounter++;
            }
            await InlineReactionReplyAsync(reply);
        }
예제 #2
0
        private static ReactionCallbackData GenerateColorRole(ColorRole colorRole)
        {
            var embedBuilder = new EmbedBuilder()
                               .WithTitle($"Color Role")
                               .WithColor(new Color(colorRole.r, colorRole.g, colorRole.b))
                               .WithDescription(
                $"Do you like this color? HEX: {colorRole.HexColor.ToUpper()} / RGB: {colorRole.r}, {colorRole.g}, {colorRole.b}" + Environment.NewLine
                + "React with your choice."
                );

            var rcbd = new ReactionCallbackData("", embedBuilder.Build(), true, true, reactDuration, async c => await ReactionEndedAsync(c, colorRole).ConfigureAwait(false));

            foreach (IEmote answerEmoji in colorRole.Answers.Select(x => x.AnswerEmoji))
            {
                _ = rcbd.WithCallback(answerEmoji, (c, r) => ColorPicker(r, colorRole));
            }
            return(rcbd);
        }
        public async Task Test_OptionsReply(int count)
        {
            string[] numbers      = new[] { "0⃣", "1⃣", "2⃣", "3⃣", "4⃣", "5⃣", "6⃣", "7⃣", "8⃣", "9⃣" };
            var      numberEmojis = new List <Emoji>();

            for (int i = 0; i < numbers.Length; i++)
            {
                numberEmojis.Add(new Emoji(numbers[i]));
            }

            var one = new Emoji("1?");

            var reply = new ReactionCallbackData("Option Count: " + count);

            for (int i = 1; i <= count; i++)
            {
                var counter = i;
                reply.WithCallback(numberEmojis[counter], c => c.Channel.SendMessageAsync("You have choosen option: " + counter));
            }

            await InlineReactionReplyAsync(reply);
        }
예제 #4
0
        private static ReactionCallbackData GeneratePoll(Poll poll)
        {
            string answers = string.Join(Environment.NewLine, poll.Answers.Select(x => $"{x.AnswerEmoji} {x.Answer}"));

            var embedBuilder = new EmbedBuilder()
                               .WithTitle($"New Poll: {poll.Question}")
                               .WithColor(new Color(20, 20, 20))
                               .WithDescription(
                "- Pick an option by clicking on the corresponding Emoji" + Environment.NewLine
                + "- Only your first pick counts!" + Environment.NewLine
                + $"- You have {pollDuration.Humanize()} to cast your vote"
                )
                               .AddField("Pick one", answers);

            var rcbd = new ReactionCallbackData("", embedBuilder.Build(), false, true, true, pollDuration, async c => await PollEndedAsync(c, poll).ConfigureAwait(false));

            foreach (var answerEmoji in poll.Answers.Select(x => x.AnswerEmoji))
            {
                rcbd.WithCallback(answerEmoji, (c, r) => AddVoteCount(r, poll));
            }
            return(rcbd);
        }
예제 #5
0
        public async Task GetInfo([Remainder, Name("termi")] string query)
        {
            var normalized = StringUtils.NormalizeQuery(query);

            if (normalized == null)
            {
                await ReplyAsync($"Termi **{query}** nuk u gjet.");

                return;
            }

            var obj = JsonUtils.LookupObject(Data, normalized);

            if (obj != null)
            {
                await ReplyAsync(
                    $"Informatat për **{query}**",
                    embed : JsonUtils.EmbedObject(obj));

                return;
            }

            const int threshold = 8;
            const int count     = 3;

            // No match, try finding suggestions.
            var matches = JsonUtils.FindClosest(Data, normalized, threshold, count);

            if (matches.Length != 0)
            {
                var emojis = new[] { "\u0031\u20E3", "\u0032\u20E3", "\u0033\u20E3" };

                // Give suggestions and listen for reactions.
                var text = $"Termi **{query}** nuk u gjet.\n\n"
                           + "Mos keni menduar për ndonjërën nga:\n"
                           + matches.Select((match, i) => i + 1 + ") " + match["_label"]).Join("\n");

                var callback = new ReactionCallbackData(
                    text,
                    embed: null,
                    expiresAfterUse: true,
                    singleUsePerUser: true,
                    timeout: TimeSpan.FromSeconds(30d));

                for (var i = 0; i < matches.Length; i++)
                {
                    var term = matches[i]["_label"].ToString();
                    callback.WithCallback(
                        new Emoji(emojis[i]), async(c, r) =>
                    {
                        var newObj = TryLookup(term);
                        if (newObj != null)
                        {
                            await c.Channel.SendMessageAsync(
                                $"Informatat për **{term}**",
                                embed: JsonUtils.EmbedObject(newObj));
                        }
                        else
                        {
                            await c.Channel.SendMessageAsync("Fatkeqësisht ka ndodhur një gabim. Ju lutem provoni përsëri.");
                        }
                    });
                }

                await InlineReactionReplyAsync(callback, fromSourceUser : true);
            }
            else
            {
                // No suggestions.
                await ReplyAsync($"Termi **{query}** nuk u gjet.");
            }
        }
예제 #6
0
        public async Task HelpCommand()
        {
            var timeoutSeconds = 60;
            var embed          = new EmbedBuilder()
                                 .WithColor(Color.Orange)
                                 .WithTitle("❓ User Guide")
                                 .WithDescription("Here is the list of command modules.\n" +
                                                  "A module is a catergory for a group of related commands.\n" +
                                                  $"Press the corresponding emote or enter `{prefix}help <module>` to view the commands in a module.\n")
                                 .WithFooter($"Press the respective emote to expand the module list (expire in {timeoutSeconds} seconds).");

            var moduleEmoteOrders = commands.Modules
                                    .OrderBy(x => x.Remarks ?? "Module Z")
                                    .Zip(EmojiPresets.Numbers.Skip(1), (x, y) => new KeyValuePair <Emoji, ModuleInfo>(y, x));

            embed.Fields = getOriginalFields();

            IUserMessage msg = default;
            var          reactionCallbacksData = new ReactionCallbackData(string.Empty, embed.Build(), false, false, TimeSpan.FromSeconds(timeoutSeconds), c => onExpire());

            foreach (var item in moduleEmoteOrders)
            {
                reactionCallbacksData = reactionCallbacksData.WithCallback(item.Key, (c, r) =>
                {
                    embed.Description = $"Enter `{prefix}help {prefix}<command>` to view the details of a command";
                    embed.Fields      = getOriginalFields();
                    embed.Fields.Single(x => x.Name.Contains(item.Value.Name)).Value = GetCommnadListFormatted(moduleEmoteOrders.Single(x => x.Key.Name == r.Emote.Name).Value);
                    modifyHelp(c, r.MessageId, embed.Build(), r);
                    return(Task.CompletedTask);
                });
            }
            msg = await InlineReactionReplyAsync(reactionCallbacksData);

            List <EmbedFieldBuilder> getOriginalFields()
            => moduleEmoteOrders.Select(x => new EmbedFieldBuilder()
                                        .WithName($"{x.Key.Name} {x.Value.Name}")
                                        .WithValue(x.Value.Summary ?? "In Development".MarkdownCodeBlock()))
            .ToList();

            async Task onExpire()
            {
                var expireEmbed = Context.Channel.GetMessageAsync(msg.Id).Result.Embeds.First()
                                  .ToEmbedBuilder()
                                  .WithFooter("Emote interactive expired");

                expireEmbed.Description = expireEmbed.Description.Replace("Press the corresponding emote or e", "E");
                _ = msg.RemoveAllReactionsAsync();
                await msg.ModifyAsync(x => x.Embed = expireEmbed.Build());
            }

            void modifyHelp(SocketCommandContext modifyingContext, ulong messageId, Embed expandedEmbed, SocketReaction reaction)
            {
                var reactionMsg = (IUserMessage)modifyingContext.Channel.GetMessageAsync(messageId).Result;

                reactionMsg.RemoveReactionAsync(reaction.Emote, reaction.User.Value);
                reactionMsg.ModifyAsync(x =>
                {
                    x.Embed = expandedEmbed;
                });
            }
        }
예제 #7
0
        public async Task GetQuestion(int id = -100)
        {
            // question which will be fetch from server database
            Question question = null;

            // if question was already seen
            bool wasSeen = false;

            // Get server informations
            Guild guild = Guilds.GetGuild(Context.Guild.Id);

            // Get user account
            UserAccount userAccount = UserAccounts.GetUserAccount(Context.User.Id, guild.UserAccounts, guild.Categories);

            // check if question id is valid
            if (id >= 0)
            {
                // check if user already seen this question
                if (userAccount.SeenQuestionsIds.Contains(id))
                {
                    wasSeen = true;
                }

                // get question with id from database
                question = Questions.GetQuestion(id, guild.Categories);
            }
            else
            {
                Random          random       = new Random(DateTime.Now.Millisecond);
                List <Question> allQuestions = new List <Question>();

                // Get maximum question id
                foreach (Category category in guild.Categories)
                {
                    allQuestions.AddRange(category.Questions); // and all questions as well
                }

                // get all unseen questions
                IEnumerable <Question> unseenQuestions = from q in allQuestions
                                                         where !userAccount.SeenQuestionsIds.Contains(q.Id)
                                                         select q;

                int unseenQuestionsCount = unseenQuestions.ToList().Count;

                // if list of unseen questions is empty
                if (unseenQuestionsCount == 0)
                {
                    // send random question
                    wasSeen  = true;
                    question = allQuestions.ElementAt(random.Next(0, allQuestions.Count));
                }
                else
                {
                    // send unseen question
                    question = unseenQuestions.ElementAt(random.Next(0, unseenQuestionsCount));
                }

                id = question.Id;
            }

            // Create embed for message with question
            EmbedBuilder embedBuild = new EmbedBuilder
            {
                Title       = $"Pytanie #{question.Id}",
                Description = question.Description
            };

            // add possible answers
            for (int i = 0; i < question.PossibleAnswers.Count; i++)
            {
                embedBuild.AddField(Util.AnswersEmojis.ToList()[i].Name, question.PossibleAnswers[i], true);
            }

            // add image
            if (question.ImageURL != null)
            {
                embedBuild.ImageUrl = question.ImageURL;
            }

            // build embed
            Embed embed = embedBuild.Build();

            // ReactionCallbackData(message content, embed, expires after first use, if command should react to only one answer from 1 user,
            //                                                                                          command timeout, what to do if command expires)
            ReactionCallbackData reactionData = new ReactionCallbackData("", embed, true, true, TimeSpan.FromSeconds(120), (c) => Timeout(c.Channel));

            // Iterate all possible answers and add answer placeholder
            for (int i = 0; i < question.PossibleAnswers.Count; i++)
            {
                // check if this iteration answer is right
                if (i == question.RightAnswer)
                {
                    // Add answer placecholder with information what if user select this answer
                    // reactionData.WithCallback(answer emoji, what to do if user select answer)
                    // CheckScore(if question was seen, is this good answer, question id, question category, user account, source channel)
                    reactionData.WithCallback(Util.AnswersEmojis.ToList()[i], (c, r) => CheckScore(wasSeen, true, id, GetCategoryContainingQuestionId(id, guild.Categories), userAccount, c.Channel));
                }
                else
                {
                    reactionData.WithCallback(Util.AnswersEmojis.ToList()[i], (c, r) => CheckScore(wasSeen, false, id, GetCategoryContainingQuestionId(id, guild.Categories), userAccount, c.Channel));
                }
            }

            // Send quiz message and await user selection
            await InlineReactionReplyAsync(reactionData, true);
        }