Esempio n. 1
0
    /// <summary>
    /// Starting the role deletion assistant
    /// </summary>
    /// <param name="commandContextContainer">Current command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    private async Task RunDeleteAssistantAsync(CommandContextContainer commandContextContainer)
    {
        var roleId = await SelectRoleAsync(commandContextContainer, null).ConfigureAwait(false);

        if (roleId != null)
        {
            var checkEmoji = DiscordEmojiService.GetCheckEmoji(commandContextContainer.Client);
            var crossEmoji = DiscordEmojiService.GetCrossEmoji(commandContextContainer.Client);

            var message = await commandContextContainer.Channel
                          .SendMessageAsync(LocalizationGroup.GetText("DeleteRolePrompt", "Are you sure you want to delete the role?"))
                          .ConfigureAwait(false);

            var userReactionTask = commandContextContainer.Client
                                   .GetInteractivity()
                                   .WaitForReactionAsync(message, commandContextContainer.User);

            await message.CreateReactionAsync(checkEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(crossEmoji).ConfigureAwait(false);

            var userReaction = await userReactionTask.ConfigureAwait(false);

            if (userReaction.TimedOut == false)
            {
                using (var dbFactory = RepositoryFactory.CreateInstance())
                {
                    dbFactory.GetRepository <RaidRoleRepository>()
                    .Refresh(obj => obj.Id == roleId.Value,
                             obj => obj.IsDeleted = true);
                }
            }
        }
    }
Esempio n. 2
0
    /// <summary>
    /// Editing a sub role
    /// </summary>
    /// <param name="commandContextContainer">Current command context</param>
    /// <param name="mainRoleId">Id of the role</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    private async Task RunEditSubRoleAssistantAsync(CommandContextContainer commandContextContainer, long mainRoleId)
    {
        var roleId = await SelectRoleAsync(commandContextContainer, mainRoleId).ConfigureAwait(false);

        if (roleId != null)
        {
            var builder = new DiscordEmbedBuilder();
            builder.WithTitle(LocalizationGroup.GetText("RoleEditTitle", "Raid role configuration"));

            var descriptionEmoji = DiscordEmojiService.GetEditEmoji(commandContextContainer.Client);
            var emojiEmoji       = DiscordEmojiService.GetEmojiEmoji(commandContextContainer.Client);
            var cancelEmoji      = DiscordEmojiService.GetCrossEmoji(commandContextContainer.Client);

            var commands = new StringBuilder();
            commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditEditDescriptionCommand", "{0} Edit description", descriptionEmoji));
            commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditEditEmojiCommand", "{0} Edit emoji", emojiEmoji));
            commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantCancelCommand", "{0} Cancel", cancelEmoji));

            builder.AddField(LocalizationGroup.GetText("AssistantCommandsField", "Commands"), commands.ToString());

            var message = await commandContextContainer.Channel
                          .SendMessageAsync(builder)
                          .ConfigureAwait(false);

            var userReactionTask = commandContextContainer.Client
                                   .GetInteractivity()
                                   .WaitForReactionAsync(message, commandContextContainer.User);

            await message.CreateReactionAsync(descriptionEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(emojiEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(cancelEmoji).ConfigureAwait(false);

            var userReaction = await userReactionTask.ConfigureAwait(false);

            if (userReaction.TimedOut == false)
            {
                if (userReaction.Result.Emoji.Id == descriptionEmoji.Id)
                {
                    await RunEditDescriptionAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
                else if (userReaction.Result.Emoji.Id == emojiEmoji.Id)
                {
                    await RunEditEmojiAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
            }
        }
    }
Esempio n. 3
0
 public async Task ImportItems(CommandContext commandContext)
 {
     if (await ItemsService.ImportItems()
         .ConfigureAwait(false))
     {
         await commandContext.Message
         .CreateReactionAsync(DiscordEmojiService.GetCheckEmoji(commandContext.Client))
         .ConfigureAwait(false);
     }
     else
     {
         await commandContext.Message
         .CreateReactionAsync(DiscordEmojiService.GetCrossEmoji(commandContext.Client))
         .ConfigureAwait(false);
     }
 }
Esempio n. 4
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        if (_reactions == null)
        {
            _reactions = new List <ReactionData <bool> >
            {
                new ()
                {
                    Emoji       = DiscordEmojiService.GetAddEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("AddCommand", "{0} Add schedule", DiscordEmojiService.GetAddEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var data = await DialogHandler.RunForm <CreateCalendarScheduleData>(CommandContext, false)
                                   .ConfigureAwait(false);

                        using (var dbFactory = RepositoryFactory.CreateInstance())
                        {
                            var level = new CalendarAppointmentScheduleEntity
                            {
                                DiscordServerId = CommandContext.Guild.Id,
                                Description     = data.Description,
                                CalendarAppointmentTemplateId = data.TemplateId,
                                Type           = data.Schedule.Type,
                                AdditionalData = data.Schedule.AdditionalData
                            };

                            dbFactory.GetRepository <CalendarAppointmentScheduleRepository>()
                            .Add(level);
                        }

                        return(true);
                    }
                }
            };

            if (GetSchedules().Count > 0)
            {
                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("EditCommand", "{0} Edit schedule", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <CalendarScheduleSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("CalendarScheduleId", levelId);

                        bool repeat;

                        do
                        {
                            repeat = await RunSubElement <CalendarScheduleEditDialogElement, bool>().ConfigureAwait(false);
                        }while (repeat);

                        return(true);
                    }
                });

                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("DeleteCommand", "{0} Delete schedule", DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <CalendarScheduleSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("CalendarScheduleId", levelId);

                        return(await RunSubElement <CalendarScheduleDeletionDialogElement, bool>().ConfigureAwait(false));
                    }
                });
            }

            _reactions.Add(new ReactionData <bool>
            {
                Emoji       = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func        = () => Task.FromResult(false)
            });
        }

        return(_reactions);
    }
Esempio n. 5
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        if (_reactions == null)
        {
            _reactions = new List <ReactionData <bool> >
            {
                new ()
                {
                    Emoji       = DiscordEmojiService.GetAddEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("AddCommand", "{0} Add rank", DiscordEmojiService.GetAddEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var data = await DialogHandler.RunForm <CreateGuildSpecialRankData>(CommandContext, false)
                                   .ConfigureAwait(false);

                        using (var dbFactory = RepositoryFactory.CreateInstance())
                        {
                            var rank = new GuildSpecialRankConfigurationEntity
                            {
                                GuildId = dbFactory.GetRepository <GuildRepository>()
                                          .GetQuery()
                                          .Where(obj => obj.DiscordServerId == CommandContext.Guild.Id)
                                          .Select(obj => obj.Id)
                                          .First(),
                                Description     = data.Description,
                                DiscordRoleId   = data.DiscordRoleId,
                                MaximumPoints   = data.MaximumPoints,
                                GrantThreshold  = data.GrantThreshold,
                                RemoveThreshold = data.RemoveThreshold
                            };

                            if (dbFactory.GetRepository <GuildSpecialRankConfigurationRepository>()
                                .Add(rank))
                            {
                                DialogContext.SetValue("RankId", rank.Id);

                                bool repeat;

                                do
                                {
                                    repeat = await RunSubElement <GuildSpecialRankEditDialogElement, bool>().ConfigureAwait(false);
                                }while (repeat);
                            }
                        }

                        return(true);
                    }
                }
            };

            if (GetRanks().Count > 0)
            {
                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("EditCommand", "{0} Edit rank", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <GuildSpecialRankSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("RankId", levelId);

                        bool repeat;

                        do
                        {
                            repeat = await RunSubElement <GuildSpecialRankEditDialogElement, bool>().ConfigureAwait(false);
                        }while (repeat);

                        return(true);
                    }
                });

                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("DeleteCommand", "{0} Delete rank", DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var rankId = await RunSubElement <GuildSpecialRankSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("RankId", rankId);

                        return(await RunSubElement <GuildSpecialRankDeletionDialogElement, bool>().ConfigureAwait(false));
                    }
                });
            }

            _reactions.Add(new ReactionData <bool>
            {
                Emoji       = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func        = () => Task.FromResult(false)
            });
        }

        return(_reactions);
    }
Esempio n. 6
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        return(_reactions ??= new List <ReactionData <bool> >
        {
            new ()
            {
                Emoji = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("EditApiKeyCommand", "{0} Edit api key", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                Func = async() =>
                {
                    var success = false;

                    var apiKey = await RunSubElement <AccountApiKeyDialogElement, string>().ConfigureAwait(false);

                    apiKey = apiKey?.Trim();

                    if (string.IsNullOrWhiteSpace(apiKey) == false)
                    {
                        try
                        {
                            var connector = new GuidWars2ApiConnector(apiKey);
                            await using (connector.ConfigureAwait(false))
                            {
                                var tokenInformation = await connector.GetTokenInformationAsync()
                                                       .ConfigureAwait(false);

                                if (tokenInformation?.Permissions != null &&
                                    tokenInformation.Permissions.Contains(TokenInformation.Permission.Account) &&
                                    tokenInformation.Permissions.Contains(TokenInformation.Permission.Characters) &&
                                    tokenInformation.Permissions.Contains(TokenInformation.Permission.Progression))
                                {
                                    var accountInformation = await connector.GetAccountInformationAsync()
                                                             .ConfigureAwait(false);

                                    if (accountInformation.Name == DialogContext.GetValue <string>("AccountName"))
                                    {
                                        using (var dbFactory = RepositoryFactory.CreateInstance())
                                        {
                                            var user = await CommandContext.GetCurrentUser()
                                                       .ConfigureAwait(false);

                                            if (dbFactory.GetRepository <AccountRepository>()
                                                .Refresh(obj => obj.UserId == user.Id &&
                                                         obj.Name == accountInformation.Name,
                                                         obj =>
                                            {
                                                obj.ApiKey = apiKey;
                                                obj.Permissions = GuildWars2ApiPermissionConverter.ToPermission(tokenInformation.Permissions);
                                            }))
                                            {
                                                success = true;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        await CommandContext.Channel
                                        .SendMessageAsync(LocalizationGroup.GetText("AccountNameMismatch", "The provided api key doesn't match the current account name."))
                                        .ConfigureAwait(false);
                                    }
                                }
                                else
                                {
                                    await CommandContext.Channel
                                    .SendMessageAsync(LocalizationGroup.GetText("InvalidToken", "The provided token is invalid or doesn't have the required permissions."))
                                    .ConfigureAwait(false);
                                }
                            }
                        }
                        catch (HttpRequestException ex) when(ex.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
                        {
                            await CommandContext.Channel
                            .SendMessageAsync(LocalizationGroup.GetText("InvalidToken", "The provided token is invalid or doesn't have the required permissions."))
                            .ConfigureAwait(false);
                        }
                    }

                    return success;
                }
            },
            new ()
            {
                Emoji = DiscordEmojiService.GetEdit2Emoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("EditDpsReportUserTokenCommand", "{0} Edit dps report user token", DiscordEmojiService.GetEdit2Emoji(CommandContext.Client)),
                Func = async() =>
                {
                    var token = await RunSubElement <AccountDpsReportUserTokenDialogElement, string>()
                                .ConfigureAwait(false);

                    using (var dbFactory = RepositoryFactory.CreateInstance())
                    {
                        var accountName = DialogContext.GetValue <string>("AccountName");

                        var user = await CommandContext.GetCurrentUser()
                                   .ConfigureAwait(false);

                        dbFactory.GetRepository <AccountRepository>()
                        .Refresh(obj => obj.UserId == user.Id &&
                                 obj.Name == accountName,
                                 obj => obj.DpsReportUserToken = token);
                    }

                    return true;
                }
            },
            new ()
            {
                Emoji = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func = () => Task.FromResult(false)
            }
        });
Esempio n. 7
0
    /// <summary>
    /// Editing the embedded message
    /// </summary>
    /// <param name="builder">Builder</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public override async Task EditMessage(DiscordEmbedBuilder builder)
    {
        builder.WithTitle(LocalizationGroup.GetText("ChooseCommandTitle", "Account configuration"));
        builder.WithDescription(LocalizationGroup.GetText("ChooseCommandDescription", "With this assistant you are able to configure your Guild Wars 2 account configuration."));

        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var name = DialogContext.GetValue <string>("AccountName");

            var data = await dbFactory.GetRepository <AccountRepository>()
                       .GetQuery()
                       .Where(obj => obj.User.DiscordAccounts.Any(obj2 => obj2.Id == CommandContext.User.Id) &&
                              obj.Name == name)
                       .Select(obj => new
            {
                obj.Name,
                IsApiKeyAvailable = obj.ApiKey != null,
                obj.DpsReportUserToken,
            })
                       .FirstAsync()
                       .ConfigureAwait(false);

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"{Formatter.InlineCode(LocalizationGroup.GetText("Name", "Name"))}: {data.Name}");
            stringBuilder.AppendLine($"{Formatter.InlineCode(LocalizationGroup.GetText("IsApiKeyAvailable", "Api Key"))}: {(data.IsApiKeyAvailable ? DiscordEmojiService.GetCheckEmoji(CommandContext.Client) : DiscordEmojiService.GetCrossEmoji(CommandContext.Client))}");
            stringBuilder.AppendLine($"{Formatter.InlineCode(LocalizationGroup.GetText("DpsReportUserToken", "dps.report user token"))}: {(string.IsNullOrWhiteSpace(data.DpsReportUserToken) ? DiscordEmojiService.GetCrossEmoji(CommandContext.Client) : data.DpsReportUserToken)}");

            builder.AddField(LocalizationGroup.GetText("Data", "Data"), stringBuilder.ToString());
        }
    }
Esempio n. 8
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        if (_reactions == null)
        {
            _reactions = new List <ReactionData <bool> >
            {
                new ()
                {
                    Emoji       = DiscordEmojiService.GetAddEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("AddCommand", "{0} Add template", DiscordEmojiService.GetAddEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var data = await DialogHandler.RunForm <CreateRaidTemplateFormData>(CommandContext, false)
                                   .ConfigureAwait(false);

                        using (var dbFactory = RepositoryFactory.CreateInstance())
                        {
                            dbFactory.GetRepository <RaidDayTemplateRepository>()
                            .Add(new RaidDayTemplateEntity
                            {
                                AliasName   = data.AliasName,
                                Title       = data.Title,
                                Description = data.Description,
                                Thumbnail   = data.Thumbnail
                            });
                        }

                        return(true);
                    }
                }
            };

            if (GetTemplates().Count > 0)
            {
                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("EditCommand", "{0} Edit template", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var templateId = await RunSubElement <RaidTemplateSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("TemplateId", templateId);

                        bool repeat;

                        do
                        {
                            repeat = await RunSubElement <RaidTemplateEditDialogElement, bool>().ConfigureAwait(false);
                        }while (repeat);

                        return(true);
                    }
                });

                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("DeleteCommand", "{0} Delete template", DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var templateId = await RunSubElement <RaidTemplateSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("TemplateId", templateId);

                        return(await RunSubElement <RaidTemplateDeletionElementBase, bool>().ConfigureAwait(false));
                    }
                });
            }

            _reactions.Add(new ReactionData <bool>
            {
                Emoji       = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func        = () => Task.FromResult(false)
            });
        }

        return(_reactions);
    }
Esempio n. 9
0
    /// <summary>
    /// Validation the guild bank
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task Check(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var guild = dbFactory.GetRepository <GuildRepository>()
                        .GetQuery()
                        .Where(obj => obj.DiscordServerId == commandContext.Guild.Id)
                        .Select(obj => new
            {
                obj.ApiKey,
                obj.GuildId
            })
                        .FirstOrDefault();

            if (string.IsNullOrWhiteSpace(guild?.ApiKey) == false)
            {
                var msg = new DiscordEmbedBuilder();
                msg.WithTitle(LocalizationGroup.GetText("BankValidation", "Guild bank validation"));
                msg.WithDescription(LocalizationGroup.GetText("BankValidationResult", "In the following message you can see the results of the bank validation."));
                msg.WithFooter("Scruffy", "https://cdn.discordapp.com/app-icons/838381119585648650/823930922cbe1e5a9fa8552ed4b2a392.png?size=64");
                msg.WithTimestamp(DateTime.Now);

                var connector = new GuidWars2ApiConnector(guild.ApiKey);
                await using (connector.ConfigureAwait(false))
                {
                    var vault = await connector.GetGuildVault(guild.GuildId)
                                .ConfigureAwait(false);

                    foreach (var stash in vault)
                    {
                        var slots = new List <(int ItemId, int X, int Y)>();
                        var i     = 0;

                        foreach (var slot in stash.Slots)
                        {
                            if (slot != null &&
                                slot.Count < 250)
                            {
                                slots.Add((slot.ItemId, (i % 10) + 1, (i / 10) + 1));
                            }

                            i++;
                        }

                        var stringBuilder = new StringBuilder();

                        foreach (var group in slots.ToLookup(obj => obj.ItemId, obj => (obj.X, obj.Y))
                                 .Where(obj => obj.Count() > 1))
                        {
                            var item = await connector.GetItem(group.Key)
                                       .ConfigureAwait(false);

                            stringBuilder.AppendLine(item.Name);

                            foreach (var(x, y) in group.OrderBy(obj => obj.X)
                                     .ThenBy(obj => obj.Y))
                            {
                                stringBuilder.AppendLine($" - " + Formatter.InlineCode($"({x}/{y})"));
                            }
                        }

                        if (stringBuilder.Length > 0)
                        {
                            stringBuilder.Insert(0, Formatter.Bold(LocalizationGroup.GetText("DuplicationCheck", "Duplication check")) + " \u200B " + DiscordEmojiService.GetCrossEmoji(commandContext.Client) + "\n");
                        }
                        else
                        {
                            stringBuilder.AppendLine(Formatter.Bold(LocalizationGroup.GetText("DuplicationCheck", "Duplication check")) + " \u200B " + DiscordEmojiService.GetCheckEmoji(commandContext.Client));
                        }

                        if (stash.Coins != 0 && stash.Coins % 10000 != 0)
                        {
                            var goldCoins   = stash.Coins / 10000;
                            var silverCoins = (stash.Coins - (goldCoins * 10000)) / 100;
                            var copperCoins = stash.Coins % 100;

                            stringBuilder.AppendLine(Formatter.Bold(LocalizationGroup.GetText("CoinCheck", "Coins check")) + " \u200B " + DiscordEmojiService.GetCrossEmoji(commandContext.Client));
                            stringBuilder.AppendLine($"{goldCoins} {DiscordEmojiService.GetGuildWars2GoldEmoji(commandContext.Client)} {silverCoins} {DiscordEmojiService.GetGuildWars2SilverEmoji(commandContext.Client)} {copperCoins} {DiscordEmojiService.GetGuildWars2CopperEmoji(commandContext.Client)}");
                        }
                        else
                        {
                            stringBuilder.AppendLine(Formatter.Bold(LocalizationGroup.GetText("CoinCheck", "Coins check")) + " \u200B " + DiscordEmojiService.GetCheckEmoji(commandContext.Client));
                        }

                        stringBuilder.Append("\u200B");

                        msg.AddField(stash.Note ?? "Stash", stringBuilder.ToString());
                    }
                }

                await commandContext.Channel
                .SendMessageAsync(msg)
                .ConfigureAwait(false);
            }
            else
            {
                await commandContext.Channel
                .SendMessageAsync(LocalizationGroup.GetText("NoApiKey", "The guild ist not configured."))
                .ConfigureAwait(false);
            }
        }
    }
Esempio n. 10
0
    /// <summary>
    /// Validation the guild bank
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task CheckUnlocksDyes(CommandContextContainer commandContext)
    {
        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var guild = dbFactory.GetRepository <GuildRepository>()
                        .GetQuery()
                        .Where(obj => obj.DiscordServerId == commandContext.Guild.Id)
                        .Select(obj => new
            {
                obj.ApiKey,
                obj.GuildId
            })
                        .FirstOrDefault();

            if (string.IsNullOrWhiteSpace(guild?.ApiKey) == false)
            {
                var user = await commandContext.GetCurrentUser()
                           .ConfigureAwait(false);

                var apiKeys = dbFactory.GetRepository <AccountRepository>()
                              .GetQuery()
                              .Where(obj => obj.UserId == user.Id)
                              .Select(obj => new
                {
                    obj.ApiKey,
                    obj.Name
                })
                              .ToList();

                if (apiKeys.Count > 0)
                {
                    var guildConnector = new GuidWars2ApiConnector(guild.ApiKey);
                    await using (guildConnector.ConfigureAwait(false))
                    {
                        var vault = await guildConnector.GetGuildVault(guild.GuildId)
                                    .ConfigureAwait(false);

                        var itemIds = vault.SelectMany(obj => obj.Slots)
                                      .Where(obj => obj != null)
                                      .Select(obj => (int?)obj.ItemId)
                                      .Distinct()
                                      .ToList();

                        var items = await guildConnector.GetItems(itemIds)
                                    .ConfigureAwait(false);

                        foreach (var apiKey in apiKeys)
                        {
                            var accountConnector = new GuidWars2ApiConnector(apiKey.ApiKey);
                            await using (accountConnector.ConfigureAwait(false))
                            {
                                var dyes = await accountConnector.GetDyes()
                                           .ConfigureAwait(false);

                                var builder = new DiscordEmbedBuilder().WithTitle(LocalizationGroup.GetFormattedText("DyeUnlocksTitle", "Dye unlocks {0}", apiKey.Name))
                                              .WithColor(DiscordColor.Green)
                                              .WithFooter("Scruffy", "https://cdn.discordapp.com/app-icons/838381119585648650/823930922cbe1e5a9fa8552ed4b2a392.png?size=64")
                                              .WithTimestamp(DateTime.Now);

                                var fieldBuilder = new StringBuilder();
                                var fieldCounter = 1;

                                foreach (var item in items.Where(obj => obj.Type == "Consumable" &&
                                                                 obj.Details?.Type == "Unlock" &&
                                                                 obj.Details?.UnlockType == "Dye")
                                         .OrderBy(obj => obj.Name))
                                {
                                    var currentLine = dyes.Contains(item.Details.ColorId ?? 0)
                                                          ? $"{DiscordEmojiService.GetCheckEmoji(commandContext.Client)} {item.Name}"
                                                          : $"{DiscordEmojiService.GetCrossEmoji(commandContext.Client)} {item.Name}";

                                    if (fieldBuilder.Length + currentLine.Length > 1024)
                                    {
                                        builder.AddField(LocalizationGroup.GetFormattedText("DyesFields", "Dyes #{0}", fieldCounter), fieldBuilder.ToString(), true);

                                        fieldBuilder = new StringBuilder();
                                        fieldCounter++;
                                    }

                                    fieldBuilder.AppendLine(currentLine);
                                }

                                builder.AddField(LocalizationGroup.GetFormattedText("DyesFields", "Dyes #{0}", fieldCounter), fieldBuilder.ToString(), true);

                                await commandContext.Message
                                .RespondAsync(builder)
                                .ConfigureAwait(false);
                            }
                        }
                    }
                }
                else
                {
                    await commandContext.Channel
                    .SendMessageAsync(LocalizationGroup.GetText("NoAccountApiKey", "You don't have any api keys configured."))
                    .ConfigureAwait(false);
                }
            }
            else
            {
                await commandContext.Channel
                .SendMessageAsync(LocalizationGroup.GetText("NoApiKey", "The guild ist not configured."))
                .ConfigureAwait(false);
            }
        }
    }
Esempio n. 11
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        if (_reactions == null)
        {
            _reactions = new List <ReactionData <bool> >
            {
                new ()
                {
                    Emoji       = DiscordEmojiService.GetAddEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("AddCommand", "{0} Add level", DiscordEmojiService.GetAddEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var data = await DialogHandler.RunForm <CreateRaidExperienceLevelData>(CommandContext, false)
                                   .ConfigureAwait(false);

                        using (var dbFactory = RepositoryFactory.CreateInstance())
                        {
                            var level = new RaidExperienceLevelEntity
                            {
                                SuperiorExperienceLevelId = data.SuperiorExperienceLevelId,
                                Description   = data.Description,
                                DiscordEmoji  = data.DiscordEmoji,
                                DiscordRoleId = data.DiscordRoleId,
                            };

                            if (dbFactory.GetRepository <RaidExperienceLevelRepository>()
                                .Add(level))
                            {
                                if (dbFactory.GetRepository <RaidExperienceLevelRepository>()
                                    .RefreshRange(obj => obj.SuperiorExperienceLevelId == data.SuperiorExperienceLevelId &&
                                                  obj.Id != level.Id,
                                                  obj => obj.SuperiorExperienceLevelId = level.Id))
                                {
                                    dbFactory.GetRepository <RaidExperienceLevelRepository>()
                                    .RefreshRanks();
                                }
                            }
                        }

                        return(true);
                    }
                }
            };

            if (GetLevels().Count > 0)
            {
                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("EditCommand", "{0} Edit level", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <RaidExperienceLevelSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("ExperienceLevelId", levelId);

                        bool repeat;

                        do
                        {
                            repeat = await RunSubElement <RaidExperienceLevelEditDialogElement, bool>().ConfigureAwait(false);
                        }while (repeat);

                        return(true);
                    }
                });

                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("DeleteCommand", "{0} Delete level", DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <RaidExperienceLevelSelectionDialogElement, long>().ConfigureAwait(false);

                        DialogContext.SetValue("ExperienceLevelId", levelId);

                        return(await RunSubElement <RaidExperienceLevelDeletionDialogElement, bool>().ConfigureAwait(false));
                    }
                });
            }

            _reactions.Add(new ReactionData <bool>
            {
                Emoji       = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func        = () => Task.FromResult(false)
            });
        }

        return(_reactions);
    }
Esempio n. 12
0
    /// <summary>
    /// Returns the reactions which should be added to the message
    /// </summary>
    /// <returns>Reactions</returns>
    public override IReadOnlyList <ReactionData <bool> > GetReactions()
    {
        if (_reactions == null)
        {
            _reactions = new List <ReactionData <bool> >
            {
                new ()
                {
                    Emoji       = DiscordEmojiService.GetAddEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("AddCommand", "{0} Add rank", DiscordEmojiService.GetAddEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var data = await DialogHandler.RunForm <CreateGuildRankFormData>(CommandContext, false)
                                   .ConfigureAwait(false);

                        using (var dbFactory = RepositoryFactory.CreateInstance())
                        {
                            var rank = new GuildRankEntity
                            {
                                GuildId = dbFactory.GetRepository <GuildRepository>()
                                          .GetQuery()
                                          .Where(obj => obj.DiscordServerId == CommandContext.Guild.Id)
                                          .Select(obj => obj.Id)
                                          .First(),
                                DiscordRoleId = data.DiscordRoleId,
                                InGameName    = data.InGameName,
                                Percentage    = data.Percentage,
                                Order         = data.SuperiorId != null
                                                                           ? dbFactory.GetRepository <GuildRankRepository>()
                                                .GetQuery()
                                                .Where(obj => obj.Id == data.SuperiorId)
                                                .Select(obj => obj.Order)
                                                .First() + 1
                                                                           : 0,
                            };

                            if (dbFactory.GetRepository <GuildRankRepository>()
                                .Add(rank))
                            {
                                var order = rank.Order + 1;

                                foreach (var currentRankId in dbFactory.GetRepository <GuildRankRepository>()
                                         .GetQuery()
                                         .Where(obj => obj.Order >= rank.Order)
                                         .OrderBy(obj => obj.Order)
                                         .Select(obj => obj.Id))
                                {
                                    dbFactory.GetRepository <GuildRankRepository>()
                                    .Refresh(obj => obj.Id == currentRankId,
                                             obj => obj.Order = order);
                                    order++;
                                }

                                DialogContext.SetValue("RankId", rank.Id);

                                bool repeat;

                                do
                                {
                                    repeat = await RunSubElement <GuildRankEditDialogElement, bool>().ConfigureAwait(false);
                                }while (repeat);
                            }
                        }

                        return(true);
                    }
                }
            };

            if (GetRanks().Count > 0)
            {
                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetEditEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("EditCommand", "{0} Edit rank", DiscordEmojiService.GetEditEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var levelId = await RunSubElement <GuildRankSelectionDialogElement, int>().ConfigureAwait(false);

                        DialogContext.SetValue("RankId", levelId);

                        bool repeat;

                        do
                        {
                            repeat = await RunSubElement <GuildRankEditDialogElement, bool>().ConfigureAwait(false);
                        }while (repeat);

                        return(true);
                    }
                });

                _reactions.Add(new ReactionData <bool>
                {
                    Emoji       = DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client),
                    CommandText = LocalizationGroup.GetFormattedText("DeleteCommand", "{0} Delete rank", DiscordEmojiService.GetTrashCanEmoji(CommandContext.Client)),
                    Func        = async() =>
                    {
                        var rankId = await RunSubElement <GuildRankSelectionDialogElement, int>().ConfigureAwait(false);

                        DialogContext.SetValue("RankId", rankId);

                        return(await RunSubElement <GuildRankDeletionDialogElement, bool>().ConfigureAwait(false));
                    }
                });
            }

            _reactions.Add(new ReactionData <bool>
            {
                Emoji       = DiscordEmojiService.GetCrossEmoji(CommandContext.Client),
                CommandText = LocalizationGroup.GetFormattedText("CancelCommand", "{0} Cancel", DiscordEmojiService.GetCrossEmoji(CommandContext.Client)),
                Func        = () => Task.FromResult(false)
            });
        }

        return(_reactions);
    }
Esempio n. 13
0
    /// <summary>
    /// Starting the roles assistant
    /// </summary>
    /// <param name="commandContextContainer">Current command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task RunAssistantAsync(CommandContextContainer commandContextContainer)
    {
        var builder = new DiscordEmbedBuilder();

        builder.WithTitle(LocalizationGroup.GetText("AssistantTitle", "Raid role configuration"));
        builder.WithDescription(LocalizationGroup.GetText("AssistantDescription", "With this assistant you are able to configure the raid roles. The following roles are already created:"));

        var areRolesAvailable = false;

        using (var dbFactory = RepositoryFactory.CreateInstance())
        {
            var mainRoles = dbFactory.GetRepository <RaidRoleRepository>()
                            .GetQuery()
                            .Where(obj => obj.MainRoleId == null &&
                                   obj.IsDeleted == false)
                            .Select(obj => new
            {
                obj.DiscordEmojiId,
                obj.Description,
                SubRoles = obj.SubRaidRoles
                           .Where(obj2 => obj2.IsDeleted == false)
                           .Select(obj2 => new
                {
                    obj2.DiscordEmojiId,
                    obj2.Description
                })
            })
                            .OrderBy(obj => obj.Description)
                            .ToList();

            if (mainRoles.Count > 0)
            {
                areRolesAvailable = true;

                foreach (var role in mainRoles)
                {
                    var roles = new StringBuilder(1024, 1024);

                    foreach (var subRole in role.SubRoles)
                    {
                        roles.Append("> ");
                        roles.Append(DiscordEmojiService.GetGuildEmoji(commandContextContainer.Client, subRole.DiscordEmojiId));
                        roles.Append(' ');
                        roles.Append(subRole.Description);
                        roles.Append('\n');
                    }

                    roles.Append('\n');

                    builder.AddField($"{DiscordEmojiService.GetGuildEmoji(commandContextContainer.Client, role.DiscordEmojiId)} {role.Description}", roles.ToString());
                }
            }
        }

        var addEmoji    = DiscordEmojiService.GetAddEmoji(commandContextContainer.Client);
        var editEmoji   = DiscordEmojiService.GetEditEmoji(commandContextContainer.Client);
        var deleteEmoji = DiscordEmojiService.GetTrashCanEmoji(commandContextContainer.Client);
        var cancelEmoji = DiscordEmojiService.GetCrossEmoji(commandContextContainer.Client);

        var commands = new StringBuilder();

        commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantAddCommand", "{0} Add role", addEmoji));

        if (areRolesAvailable)
        {
            commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantEditCommand", "{0} Edit role", editEmoji));
            commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantDeleteCommand", "{0} Delete role", deleteEmoji));
        }

        commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantCancelCommand", "{0} Cancel", cancelEmoji));

        builder.AddField(LocalizationGroup.GetText("AssistantCommandsField", "Commands"), commands.ToString());

        var message = await commandContextContainer.Channel
                      .SendMessageAsync(builder)
                      .ConfigureAwait(false);

        var userReactionTask = commandContextContainer.Client
                               .GetInteractivity()
                               .WaitForReactionAsync(message, commandContextContainer.User);

        await message.CreateReactionAsync(addEmoji).ConfigureAwait(false);

        await message.CreateReactionAsync(editEmoji).ConfigureAwait(false);

        if (areRolesAvailable)
        {
            await message.CreateReactionAsync(deleteEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(cancelEmoji).ConfigureAwait(false);
        }

        var userReaction = await userReactionTask.ConfigureAwait(false);

        if (userReaction.TimedOut == false)
        {
            if (userReaction.Result.Emoji.Id == addEmoji.Id)
            {
                await RunAddAssistantAsync(commandContextContainer).ConfigureAwait(false);
            }
            else if (userReaction.Result.Emoji.Id == editEmoji.Id && areRolesAvailable)
            {
                await RunEditAssistantAsync(commandContextContainer).ConfigureAwait(false);
            }
            else if (userReaction.Result.Emoji.Id == deleteEmoji.Id)
            {
                await RunDeleteAssistantAsync(commandContextContainer).ConfigureAwait(false);
            }
        }
    }
Esempio n. 14
0
    /// <summary>
    /// Starting the role editing assistant
    /// </summary>
    /// <param name="commandContextContainer">Current command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    private async Task RunEditAssistantAsync(CommandContextContainer commandContextContainer)
    {
        var roleId = await SelectRoleAsync(commandContextContainer, null).ConfigureAwait(false);

        if (roleId != null)
        {
            var builder = new DiscordEmbedBuilder();
            builder.WithTitle(LocalizationGroup.GetText("RoleEditTitle", "Raid role configuration"));

            var areRolesAvailable = false;

            using (var dbFactory = RepositoryFactory.CreateInstance())
            {
                var rolesFieldText = new StringBuilder();
                var roles          = dbFactory.GetRepository <RaidRoleRepository>()
                                     .GetQuery()
                                     .Where(obj => obj.Id == roleId.Value &&
                                            obj.IsDeleted == false)
                                     .Select(obj => new
                {
                    obj.DiscordEmojiId,
                    obj.Description,
                    SubRoles = obj.SubRaidRoles
                               .Where(obj2 => obj2.IsDeleted == false)
                               .Select(obj2 => new
                    {
                        obj2.DiscordEmojiId,
                        obj2.Description
                    })
                })
                                     .OrderBy(obj => obj.Description)
                                     .First();

                builder.WithDescription($"{DiscordEmoji.FromGuildEmote(commandContextContainer.Client, roles.DiscordEmojiId)} - {roles.Description}");

                if (roles.SubRoles.Any())
                {
                    areRolesAvailable = true;

                    foreach (var role in roles.SubRoles)
                    {
                        rolesFieldText.Append(DiscordEmoji.FromGuildEmote(commandContextContainer.Client, role.DiscordEmojiId));
                        rolesFieldText.Append(" - ");
                        rolesFieldText.Append(role.Description);
                        rolesFieldText.Append('\n');
                    }

                    builder.AddField(LocalizationGroup.GetText("AssistantRolesField", "Roles"), rolesFieldText.ToString());
                }
            }

            var addSubRoleEmoji    = DiscordEmojiService.GetAddEmoji(commandContextContainer.Client);
            var descriptionEmoji   = DiscordEmojiService.GetEditEmoji(commandContextContainer.Client);
            var editSubRoleEmoji   = DiscordEmojiService.GetEdit2Emoji(commandContextContainer.Client);
            var emojiEmoji         = DiscordEmojiService.GetEmojiEmoji(commandContextContainer.Client);
            var deleteSubRoleEmoji = DiscordEmojiService.GetTrashCanEmoji(commandContextContainer.Client);
            var cancelEmoji        = DiscordEmojiService.GetCrossEmoji(commandContextContainer.Client);

            var commands = new StringBuilder();
            commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditEditDescriptionCommand", "{0} Edit description", descriptionEmoji));
            commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditEditEmojiCommand", "{0} Edit emoji", emojiEmoji));
            commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditAddSubRoleCommand", "{0} Add sub role", addSubRoleEmoji));

            if (areRolesAvailable)
            {
                commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditEditSubRoleCommand", "{0} Edit sub role", editSubRoleEmoji));
                commands.AppendLine(LocalizationGroup.GetFormattedText("RoleEditDeleteSubRoleCommand", "{0} Delete sub role", deleteSubRoleEmoji));
            }

            commands.AppendLine(LocalizationGroup.GetFormattedText("AssistantCancelCommand", "{0} Cancel", cancelEmoji));

            builder.AddField(LocalizationGroup.GetText("AssistantCommandsField", "Commands"), commands.ToString());

            var message = await commandContextContainer.Channel
                          .SendMessageAsync(builder)
                          .ConfigureAwait(false);

            var userReactionTask = commandContextContainer.Client
                                   .GetInteractivity()
                                   .WaitForReactionAsync(message, commandContextContainer.User);

            await message.CreateReactionAsync(descriptionEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(emojiEmoji).ConfigureAwait(false);

            await message.CreateReactionAsync(addSubRoleEmoji).ConfigureAwait(false);

            if (areRolesAvailable)
            {
                await message.CreateReactionAsync(editSubRoleEmoji).ConfigureAwait(false);

                await message.CreateReactionAsync(deleteSubRoleEmoji).ConfigureAwait(false);
            }

            await message.CreateReactionAsync(cancelEmoji).ConfigureAwait(false);

            var userReaction = await userReactionTask.ConfigureAwait(false);

            if (userReaction.TimedOut == false)
            {
                if (userReaction.Result.Emoji.Id == addSubRoleEmoji.Id)
                {
                    await RunAddSubRoleAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
                else if (userReaction.Result.Emoji.Id == descriptionEmoji.Id)
                {
                    await RunEditDescriptionAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
                else if (userReaction.Result.Emoji.Id == editSubRoleEmoji.Id)
                {
                    await RunEditSubRoleAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
                else if (userReaction.Result.Emoji.Id == emojiEmoji.Id)
                {
                    await RunEditEmojiAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
                else if (userReaction.Result.Emoji.Id == deleteSubRoleEmoji.Id)
                {
                    await RunDeleteSubRoleAssistantAsync(commandContextContainer, roleId.Value).ConfigureAwait(false);
                }
            }
        }
    }
Esempio n. 15
0
    /// <summary>
    /// Starting the roles adding assistant
    /// </summary>
    /// <param name="commandContextContainer">Current command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    private async Task RunAddAssistantAsync(CommandContextContainer commandContextContainer)
    {
        var currentBotMessage = await commandContextContainer.Channel
                                .SendMessageAsync(LocalizationGroup.GetText("ReactWithEmojiPrompt", "Please react with emoji which should be assigned to the role."))
                                .ConfigureAwait(false);

        var interactivity = commandContextContainer.Client
                            .GetInteractivity();

        var reaction = await interactivity.WaitForReactionAsync(currentBotMessage, commandContextContainer.User)
                       .ConfigureAwait(false);

        if (reaction.TimedOut == false && reaction.Result.Emoji.Id > 0)
        {
            var roleData = new RaidRoleEntity
            {
                DiscordEmojiId = reaction.Result.Emoji.Id
            };

            currentBotMessage = await commandContextContainer.Channel
                                .SendMessageAsync(LocalizationGroup.GetText("DescriptionPrompt", "Please enter the description of the role."))
                                .ConfigureAwait(false);

            var currentUserResponse = await interactivity.WaitForMessageAsync(obj => obj.Author.Id == commandContextContainer.User.Id &&
                                                                              obj.ChannelId == commandContextContainer.Channel.Id)
                                      .ConfigureAwait(false);

            if (currentUserResponse.TimedOut == false)
            {
                roleData.Description = currentUserResponse.Result.Content;

                var continueCreation = true;
                var subRolesData     = new List <RaidRoleEntity>();
                var checkEmoji       = DiscordEmojiService.GetCheckEmoji(commandContextContainer.Client);
                var crossEmoji       = DiscordEmojiService.GetCrossEmoji(commandContextContainer.Client);

                var addSubRoles = true;
                while (addSubRoles)
                {
                    var promptText = subRolesData.Count == 0
                                         ? LocalizationGroup.GetText("AddSubRolesPrompt", "Do you want to add sub roles?")
                                         : LocalizationGroup.GetText("AddAdditionalSubRolesPrompt", "Do you want to add additional sub roles?");

                    currentBotMessage = await commandContextContainer.Channel
                                        .SendMessageAsync(promptText)
                                        .ConfigureAwait(false);

                    var userReactionTask = commandContextContainer.Client
                                           .GetInteractivity()
                                           .WaitForReactionAsync(currentBotMessage, commandContextContainer.User);

                    await currentBotMessage.CreateReactionAsync(checkEmoji).ConfigureAwait(false);

                    await currentBotMessage.CreateReactionAsync(crossEmoji).ConfigureAwait(false);

                    var userReaction = await userReactionTask.ConfigureAwait(false);

                    if (userReaction.TimedOut == false)
                    {
                        if (userReaction.Result.Emoji.Id == checkEmoji.Id)
                        {
                            currentBotMessage = await commandContextContainer.Channel
                                                .SendMessageAsync(LocalizationGroup.GetText("ReactWithEmojiPrompt", "Please react with emoji which should be assigned to the role."))
                                                .ConfigureAwait(false);

                            reaction = await interactivity.WaitForReactionAsync(currentBotMessage, commandContextContainer.User)
                                       .ConfigureAwait(false);

                            if (reaction.TimedOut == false && reaction.Result.Emoji.Id > 0)
                            {
                                var subRoleData = new RaidRoleEntity
                                {
                                    DiscordEmojiId = reaction.Result.Emoji.Id
                                };

                                currentBotMessage = await commandContextContainer.Channel
                                                    .SendMessageAsync(LocalizationGroup.GetText("DescriptionPrompt", "Please enter the description of the role."))
                                                    .ConfigureAwait(false);

                                currentUserResponse = await interactivity.WaitForMessageAsync(obj => obj.Author.Id == commandContextContainer.User.Id &&
                                                                                              obj.ChannelId == commandContextContainer.Channel.Id)
                                                      .ConfigureAwait(false);

                                if (currentUserResponse.TimedOut == false)
                                {
                                    subRoleData.Description = currentUserResponse.Result.Content;

                                    subRolesData.Add(subRoleData);
                                }
                                else
                                {
                                    continueCreation = false;
                                }
                            }
                            else
                            {
                                continueCreation = false;
                            }
                        }
                        else
                        {
                            addSubRoles = false;
                        }
                    }
                    else
                    {
                        continueCreation = false;
                    }
                }

                if (continueCreation)
                {
                    using (var dbFactory = RepositoryFactory.CreateInstance())
                    {
                        if (dbFactory.GetRepository <RaidRoleRepository>()
                            .Add(roleData))
                        {
                            foreach (var subRole in subRolesData)
                            {
                                subRole.MainRoleId = roleData.Id;

                                dbFactory.GetRepository <RaidRoleRepository>()
                                .Add(subRole);
                            }
                        }
                    }

                    await commandContextContainer.Channel
                    .SendMessageAsync(LocalizationGroup.GetText("CreationCompletedMessage", "The creation is completed."))
                    .ConfigureAwait(false);
                }
            }
        }
    }
Esempio n. 16
0
    /// <summary>
    /// Post update overview
    /// </summary>
    /// <param name="commandContext">Command context</param>
    /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
    public async Task PostUpdateOverview(CommandContextContainer commandContext)
    {
        var now = DateTime.Now;

        var builder = new DiscordEmbedBuilder()
                      .WithThumbnail("https://cdn.discordapp.com/attachments/847555191842537552/861182143987712010/gw2.png")
                      .WithTitle(LocalizationGroup.GetText("GuildWars2Updates", "Guild Wars 2 - Updates"))
                      .WithColor(DiscordColor.Green)
                      .WithFooter("Scruffy", "https://cdn.discordapp.com/app-icons/838381119585648650/823930922cbe1e5a9fa8552ed4b2a392.png?size=64")
                      .WithTimestamp(now);

        void AddField(string fieldName, NextUpdateData data)
        {
            var field = new StringBuilder();

            field.Append("> ");
            field.Append(LocalizationGroup.GetText("Release", "Release"));
            field.Append(": ");

            field.Append(Formatter.MaskedUrl(data.When.ToLocalTime()
                                             .ToString("G", LocalizationGroup.CultureInfo),
                                             new Uri("https://thatshaman.com/tools/countdown")));
            field.Append(Environment.NewLine);

            var timeSpan = data.When.ToLocalTime() - now;

            if (timeSpan > TimeSpan.Zero)
            {
                field.Append("> ");
                field.Append(LocalizationGroup.GetText("Timespan", "Timespan"));
                field.Append(": ");

                if (timeSpan.Days > 0)
                {
                    field.Append(timeSpan.Days);
                    field.Append(' ');

                    field.Append(timeSpan.Days == 1
                                     ? LocalizationGroup.GetText("Day", "Day")
                                     : LocalizationGroup.GetText("Days", "Days"));
                    field.Append(' ');
                }

                if (timeSpan.TotalHours > 0)
                {
                    field.Append(timeSpan.Hours);
                    field.Append(' ');

                    field.Append(timeSpan.Hours == 1
                                     ? LocalizationGroup.GetText("Hour", "Hour")
                                     : LocalizationGroup.GetText("Hours", "Hours"));
                    field.Append(' ');
                }

                field.Append(timeSpan.Minutes);
                field.Append(' ');

                field.Append(timeSpan.Minutes == 1
                                 ? LocalizationGroup.GetText("Minute", "Minute")
                                 : LocalizationGroup.GetText("Minutes", "Minutes"));
                field.Append(' ');

                field.Append(timeSpan.Seconds);
                field.Append(' ');

                field.Append(timeSpan.Seconds == 1
                                 ? LocalizationGroup.GetText("Second", "Second")
                                 : LocalizationGroup.GetText("Seconds", "Seconds"));
                field.Append(' ');

                field.Append('\n');
            }

            field.Append("> ");
            field.Append(LocalizationGroup.GetText("Confirmed", "Confirmed"));
            field.Append(": ");

            field.Append(data.Confirmed
                             ? DiscordEmojiService.GetCheckEmoji(commandContext.Client)
                             : DiscordEmojiService.GetCrossEmoji(commandContext.Client));

            if (data.Urls?.Count > 0)
            {
                var counter = 0;

                field.Append("\u200b (");

                if (data.Urls.Count == 1)
                {
                    field.Append(Formatter.MaskedUrl(LocalizationGroup.GetText("Source", "Source"), new Uri(data.Urls.First())));
                }
                else
                {
                    field.Append(LocalizationGroup.GetText("Sources", "Sources"));
                    field.Append(": ");
                    field.Append(string.Join(',', data.Urls.Select(obj => Formatter.MaskedUrl((++counter).ToString(), new Uri(obj)))));
                }

                field.Append(')');
            }

            field.Append(Environment.NewLine);
            field.Append('​');
            field.Append(Environment.NewLine);

            builder.AddField(fieldName, field.ToString());
        }

        AddField(LocalizationGroup.GetText("UpdateField", "General"),
                 await _thatShamanConnector.GetNextUpdate()
                 .ConfigureAwait(false));

        AddField(LocalizationGroup.GetText("EodField", "End of Dragons"),
                 await _thatShamanConnector.GetEODRelease()
                 .ConfigureAwait(false));

        await commandContext.Message
        .RespondAsync(builder)
        .ConfigureAwait(false);
    }