/// <summary> /// Setting the notification channel /// </summary> /// <param name="commandContext">Command context</param> /// <param name="type">Type</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task SetNotificationChannel(CommandContextContainer commandContext, GuildChannelConfigurationType type) { using (var dbFactory = RepositoryFactory.CreateInstance()) { var guildId = dbFactory.GetRepository <GuildRepository>() .GetQuery() .Where(obj => obj.DiscordServerId == commandContext.Guild.Id) .Select(obj => obj.Id) .FirstOrDefault(); if (guildId > 0) { dbFactory.GetRepository <GuildChannelConfigurationRepository>() .AddOrRefresh(obj => obj.GuildId == guildId && obj.Type == type, obj => { obj.Type = type; obj.DiscordChannelId = commandContext.Channel.Id; }); } } await commandContext.Message.DeleteAsync() .ConfigureAwait(false); }
/// <summary> /// Setting up the calendar /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task SetupMotd(CommandContextContainer commandContext) { var message = await commandContext.Channel .SendMessageAsync(LocalizationGroup.GetText("MotdBuilding", "The message of the day will be build with the next refresh.")) .ConfigureAwait(false); using (var dbFactory = RepositoryFactory.CreateInstance()) { var guildId = dbFactory.GetRepository <GuildRepository>() .GetQuery() .Where(obj => obj.DiscordServerId == commandContext.Guild.Id) .Select(obj => obj.Id) .FirstOrDefault(); if (guildId > 0) { if (dbFactory.GetRepository <GuildChannelConfigurationRepository>() .AddOrRefresh(obj => obj.GuildId == guildId && obj.Type == GuildChannelConfigurationType.CalendarMessageOfTheDay, obj => { obj.Type = GuildChannelConfigurationType.CalendarMessageOfTheDay; obj.DiscordChannelId = commandContext.Channel.Id; obj.DiscordMessageId = message.Id; })) { await _calendarScheduleService.CreateAppointments(commandContext.Guild.Id) .ConfigureAwait(false); await _calendarMessageBuilderService.RefreshMotds(commandContext.Guild.Id) .ConfigureAwait(false); } } } }
/// <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); } } } }
/// <summary> /// Adding a one time event /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task AddOneTimeEvent(CommandContextContainer commandContext) { var data = await DialogHandler.RunForm <CreateOneTimeEventFormData>(commandContext, false) .ConfigureAwait(false); if (data != null) { using (var dbFactory = RepositoryFactory.CreateInstance()) { var appointmentTime = dbFactory.GetRepository <CalendarAppointmentTemplateRepository>() .GetQuery() .Where(obj => obj.Id == data.TemplateId) .Select(obj => obj.AppointmentTime) .First(); if (dbFactory.GetRepository <CalendarAppointmentRepository>() .Add(new CalendarAppointmentEntity { CalendarAppointmentScheduleId = null, CalendarAppointmentTemplateId = data.TemplateId, TimeStamp = data.Day.Add(appointmentTime) })) { await _messageBuilder.RefreshMessages(commandContext.Guild.Id) .ConfigureAwait(false); } } } }
/// <summary> /// Constructor /// </summary> /// <param name="commandContext">Command context</param> public DialogHandler(CommandContextContainer commandContext) { _commandContext = commandContext; _serviceProvider = GlobalServiceProvider.Current.GetServiceProvider(); DialogContext = new DialogContext(); }
/// <summary> /// Set template /// </summary> /// <param name="commandContext">Command context</param> /// <param name="appointmentId">Id of the appointment</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <bool> SetTemplate(CommandContextContainer commandContext, long appointmentId) { var success = false; var dialogHandler = new DialogHandler(commandContext); await using (dialogHandler.ConfigureAwait(false)) { var templateId = await dialogHandler.Run <RaidTemplateSelectionDialogElement, long>() .ConfigureAwait(false); if (templateId > 0) { using (var dbFactory = RepositoryFactory.CreateInstance()) { success = dbFactory.GetRepository <RaidAppointmentRepository>() .Refresh(obj => obj.Id == appointmentId, obj => obj.TemplateId = templateId); if (success) { await RefreshAppointment(appointmentId).ConfigureAwait(false); } } } } return(success); }
/// <summary> /// Join /// </summary> /// <param name="commandContext">Command context</param> /// <param name="arguments">Arguments</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task Join(CommandContextContainer commandContext, IEnumerable <string> arguments) { return(EvaluateRegistrationArguments(commandContext, arguments, async e => { var user = await commandContext.GetCurrentUser() .ConfigureAwait(false); using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <FractalRegistrationRepository>() .AddOrRefresh(obj => obj.ConfigurationId == e.ConfigurationId && obj.AppointmentTimeStamp == e.AppointmentTimeStamp && obj.UserId == user.Id, obj => { obj.ConfigurationId = e.ConfigurationId; obj.AppointmentTimeStamp = e.AppointmentTimeStamp; obj.UserId = user.Id; obj.RegistrationTimeStamp = DateTime.Now; }); } })); }
/// <summary> /// Managing the templates /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task RunAssistantAsync(CommandContextContainer commandContext) { bool repeat; do { repeat = await DialogHandler.Run <CalendarTemplateSetupDialogElement, bool>(commandContext).ConfigureAwait(false); }while (repeat); }
/// <summary> /// Editing a existing account /// </summary> /// <param name="commandContext">Command context</param> /// <param name="name">Name</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task Edit(CommandContextContainer commandContext, string name) { bool repeat; do { repeat = await DialogHandler.Run <AccountEditDialogElement, bool>(commandContext, dialogContext => dialogContext.SetValue("AccountName", name)) .ConfigureAwait(false); }while (repeat); }
/// <summary> /// Remove /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task <bool> Remove(CommandContextContainer commandContext) { return(Task.Run(() => { using (var dbFactory = RepositoryFactory.CreateInstance()) { return dbFactory.GetRepository <GameChannelRepository>() .Remove(obj => obj.DiscordChannelId == commandContext.Channel.Id && obj.Type == GameType.Counter); } })); }
/// <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); } } } }
/// <summary> /// Setting up the calendar /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task SetupCalendar(CommandContextContainer commandContext) { var data = await DialogHandler.RunForm <SetGuildCalendarFormData>(commandContext, true) .ConfigureAwait(false); if (data != null) { var message = await commandContext.Channel .SendMessageAsync(LocalizationGroup.GetText("CalendarBuilding", "The calendar will be build with the next refresh.")) .ConfigureAwait(false); using (var dbFactory = RepositoryFactory.CreateInstance()) { var guildId = dbFactory.GetRepository <GuildRepository>() .GetQuery() .Where(obj => obj.DiscordServerId == commandContext.Guild.Id) .Select(obj => obj.Id) .FirstOrDefault(); if (guildId > 0) { if (dbFactory.GetRepository <GuildChannelConfigurationRepository>() .AddOrRefresh(obj => obj.GuildId == guildId && obj.Type == GuildChannelConfigurationType.CalendarOverview, obj => { obj.DiscordChannelId = commandContext.Channel.Id; obj.DiscordMessageId = message.Id; obj.AdditionalData = JsonConvert.SerializeObject(new AdditionalCalendarChannelData { Title = data.Title, Description = data.Description }); })) { await _calendarScheduleService.CreateAppointments(commandContext.Guild.Id) .ConfigureAwait(false); await _calendarMessageBuilderService.RefreshMessages(commandContext.Guild.Id) .ConfigureAwait(false); await _calendarMessageBuilderService.RefreshMotds(commandContext.Guild.Id) .ConfigureAwait(false); } } } } }
/// <summary> /// Add /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task <bool> Add(CommandContextContainer commandContext) { return(Task.Run(() => { using (var dbFactory = RepositoryFactory.CreateInstance()) { return dbFactory.GetRepository <GameChannelRepository>() .AddOrRefresh(obj => obj.DiscordChannelId == commandContext.Channel.Id, obj => { obj.DiscordChannelId = commandContext.Channel.Id; obj.Type = GameType.Counter; }); } })); }
/// <summary> /// Execution one dialog element /// </summary> /// <typeparam name="T">Type of the element</typeparam> /// <typeparam name="TData">Type of the element result</typeparam> /// <param name="commandContext">Current command context</param> /// <param name="onInitialize">Initialization</param> /// <returns>Result</returns> public static async Task <TData> Run <T, TData>(CommandContextContainer commandContext, Action <DialogContext> onInitialize = null) where T : DialogElementBase <TData> { var serviceProvider = GlobalServiceProvider.Current.GetServiceProvider(); await using (serviceProvider.ConfigureAwait(false)) { var service = serviceProvider.GetService <T>(); var dialogContext = new DialogContext(); onInitialize?.Invoke(dialogContext); service.Initialize(commandContext, serviceProvider, dialogContext); return(await service.Run() .ConfigureAwait(false)); } }
/// <summary> /// Set group count /// </summary> /// <param name="commandContext">Command context</param> /// <param name="appointmentId">Id of the appointment</param> /// <param name="groupCount">Group count</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <bool> SetGroupCount(CommandContextContainer commandContext, long appointmentId, int groupCount) { var success = false; using (var dbFactory = RepositoryFactory.CreateInstance()) { success = dbFactory.GetRepository <RaidAppointmentRepository>() .Refresh(obj => obj.Id == appointmentId, obj => obj.GroupCount = groupCount); if (success) { await RefreshAppointment(appointmentId).ConfigureAwait(false); } } return(success); }
/// <summary> /// Exporting login data /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task ExportLoginActivityLog(CommandContextContainer commandContext) { using (var dbFactory = RepositoryFactory.CreateInstance()) { var dateLimit = DateTime.Today.AddDays(-7); var entries = await dbFactory.GetRepository <AccountDailyLoginCheckRepository>() .GetQuery() .Where(obj => obj.Date >= dateLimit) .Select(obj => new { obj.Account.Name }) .Distinct() .ToListAsync() .ConfigureAwait(false); var memoryStream = new MemoryStream(); await using (memoryStream.ConfigureAwait(false)) { var writer = new StreamWriter(memoryStream); await using (writer.ConfigureAwait(false)) { await writer.WriteLineAsync("AccountName") .ConfigureAwait(false); foreach (var entry in entries) { await writer.WriteLineAsync($"{entry.Name};") .ConfigureAwait(false); } await writer.FlushAsync() .ConfigureAwait(false); memoryStream.Position = 0; await commandContext.Channel .SendMessageAsync(new DiscordMessageBuilder().WithFile("activity_log.csv", memoryStream)) .ConfigureAwait(false); } } } }
/// <summary> /// Assigning roles /// </summary> /// <param name="commandContext">Command context</param> /// <param name="registrationId">Id of the registration</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task AssignRoles(CommandContextContainer commandContext, long registrationId) { var dialogHandler = new DialogHandler(commandContext); await using (dialogHandler.ConfigureAwait(false)) { using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <RaidRegistrationRoleAssignmentRepository>() .RemoveRange(obj => obj.RegistrationId == registrationId); do { var mainRole = await dialogHandler.Run <RaidRoleSelectionDialogElement, long?>(new RaidRoleSelectionDialogElement(_localizationService, null)) .ConfigureAwait(false); if (mainRole != null) { var subRole = await dialogHandler.Run <RaidRoleSelectionDialogElement, long?>(new RaidRoleSelectionDialogElement(_localizationService, mainRole)) .ConfigureAwait(false); dbFactory.GetRepository <RaidRegistrationRoleAssignmentRepository>() .AddOrRefresh(obj => obj.RegistrationId == registrationId && obj.MainRoleId == mainRole.Value && obj.SubRoleId == subRole, obj => { obj.RegistrationId = registrationId; obj.MainRoleId = mainRole.Value; obj.SubRoleId = subRole; }); } else { break; } }while (await dialogHandler.Run <RaidRoleSelectionNextDialogElement, bool>(new RaidRoleSelectionNextDialogElement(_localizationService, false)) .ConfigureAwait(false)); await dialogHandler.DeleteMessages() .ConfigureAwait(false); } } }
/// <summary> /// Exporting guild roles /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task ExportGuildRoles(CommandContextContainer commandContext) { var members = new List <(string Role, string User)>(); foreach (var user in await commandContext.Guild .GetAllMembersAsync() .ConfigureAwait(false)) { foreach (var role in user.Roles) { members.Add((role.Name, user.TryGetDisplayName())); } } var memoryStream = new MemoryStream(); await using (memoryStream.ConfigureAwait(false)) { var writer = new StreamWriter(memoryStream); await using (writer.ConfigureAwait(false)) { await writer.WriteLineAsync("Role;User") .ConfigureAwait(false); foreach (var(role, user) in members.OrderBy(obj => obj.Role) .ThenBy(obj => obj.User)) { await writer.WriteLineAsync($"{role};{user}") .ConfigureAwait(false); } await writer.FlushAsync() .ConfigureAwait(false); memoryStream.Position = 0; await commandContext.Channel .SendMessageAsync(new DiscordMessageBuilder().WithFile("roles.csv", memoryStream)) .ConfigureAwait(false); } } }
/// <summary> /// Editing a existing account /// </summary> /// <param name="commandContextContainer">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task Edit(CommandContextContainer commandContextContainer) { if (commandContextContainer.Message.Channel.IsPrivate == false) { await commandContextContainer.Message .RespondAsync(LocalizationGroup.GetText("SwitchToPrivate", "I answered your command as a private message.")) .ConfigureAwait(false); } await commandContextContainer.SwitchToDirectMessageContext() .ConfigureAwait(false); using (var dbFactory = RepositoryFactory.CreateInstance()) { var names = dbFactory.GetRepository <AccountRepository>() .GetQuery() .Where(obj => obj.User.DiscordAccounts.Any(obj2 => obj2.Id == commandContextContainer.User.Id)) .Select(obj => obj.Name) .Take(2) .ToList(); if (names.Count == 0) { if (await DialogHandler.Run <AccountWantToAddDialogElement, bool>(commandContextContainer).ConfigureAwait(false)) { await Add(commandContextContainer).ConfigureAwait(false); } } else { var name = names.Count == 1 ? names.First() : await DialogHandler.Run <AccountSelectionDialogElement, string>(commandContextContainer) .ConfigureAwait(false); if (string.IsNullOrWhiteSpace(name) == false) { await Edit(commandContextContainer, name).ConfigureAwait(false); } } } }
/// <summary> /// Create a new guild configuration /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task CreateGuildConfiguration(CommandContextContainer commandContext) { var data = await DialogHandler.RunForm <CreateGuildFormData>(commandContext, true) .ConfigureAwait(false); if (data != null) { using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <GuildRepository>() .AddOrRefresh(obj => obj.DiscordServerId == commandContext.Guild.Id, obj => { obj.ApiKey = data.ApiKey; obj.GuildId = data.GuildId; obj.DiscordServerId = commandContext.Guild.Id; }); } } }
/// <summary> /// Editing the emoji of the role /// </summary> /// <param name="commandContextContainer">Current command context</param> /// <param name="roleId">Id of the role</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task RunEditEmojiAssistantAsync(CommandContextContainer commandContextContainer, long roleId) { var message = await commandContextContainer.Channel .SendMessageAsync(LocalizationGroup.GetText("ReactWithEmojiPrompt", "Please react with emoji which should be assigned to the role.")) .ConfigureAwait(false); var response = await commandContextContainer.Client .GetInteractivity() .WaitForReactionAsync(message, commandContextContainer.Member) .ConfigureAwait(false); if (response.TimedOut == false) { using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <RaidRoleRepository>() .Refresh(obj => obj.Id == roleId, obj => obj.DiscordEmojiId = response.Result.Emoji.Id); } } }
/// <summary> /// Editing the description of the role /// </summary> /// <param name="commandContextContainer">Current command context</param> /// <param name="roleId">Id of the role</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private async Task RunEditDescriptionAssistantAsync(CommandContextContainer commandContextContainer, long roleId) { await commandContextContainer.Channel .SendMessageAsync(LocalizationGroup.GetText("DescriptionPrompt", "Please enter the description of the role.")) .ConfigureAwait(false); var response = await commandContextContainer.Client .GetInteractivity() .WaitForMessageAsync(obj => obj.ChannelId == commandContextContainer.Channel.Id && obj.Author.Id == commandContextContainer.Member.Id) .ConfigureAwait(false); if (response.TimedOut == false) { using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <RaidRoleRepository>() .Refresh(obj => obj.Id == roleId, obj => obj.Description = response.Result.Content); } } }
/// <summary> /// Editing a new 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 RunAddSubRoleAssistantAsync(CommandContextContainer commandContextContainer, long mainRoleId) { var interactivity = commandContextContainer.Client.GetInteractivity(); var currentBotMessage = await commandContextContainer.Channel .SendMessageAsync(LocalizationGroup.GetText("ReactWithEmojiPrompt", "Please react with emoji which should be assigned to the role.")) .ConfigureAwait(false); var reaction = await interactivity.WaitForReactionAsync(currentBotMessage, commandContextContainer.User) .ConfigureAwait(false); if (reaction.TimedOut == false && reaction.Result.Emoji.Id > 0) { var subRoleData = new RaidRoleEntity { MainRoleId = mainRoleId, 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) { subRoleData.Description = currentUserResponse.Result.Content; using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <RaidRoleRepository>() .Add(subRoleData); } } } }
/// <summary> /// Posting a random Quaggan /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task PostRandomQuaggan(CommandContextContainer commandContext) { var connector = new GuidWars2ApiConnector(null); await using (connector.ConfigureAwait(false)) { var quaggans = await connector.GetQuaggans() .ConfigureAwait(false); var quagganName = quaggans[new Random(DateTime.Now.Millisecond).Next(0, quaggans.Count - 1)]; var quagganData = await connector.GetQuaggan(quagganName) .ConfigureAwait(false); await commandContext.Message .DeleteAsync() .ConfigureAwait(false); await commandContext.Channel .SendMessageAsync(quagganData.Url) .ConfigureAwait(false); } }
/// <summary> /// Editing the participants /// </summary> /// <param name="commandContext">Command Context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task EditParticipants(CommandContextContainer commandContext) { var dialogHandler = new DialogHandler(commandContext); await using (dialogHandler.ConfigureAwait(false)) { var appointmentId = await dialogHandler.Run <CalendarAppointmentSelectionDialogElement, long>() .ConfigureAwait(false); bool repeat; var participants = new AppointmentParticipantsContainer { AppointmentId = appointmentId }; do { repeat = await dialogHandler.Run <CalendarParticipantsEditDialogElement, bool>(new CalendarParticipantsEditDialogElement(_localizationService, _userManagementService, participants)) .ConfigureAwait(false); }while (repeat); } }
/// <summary> /// Setup assistant /// </summary> /// <param name="commandContext">Command context</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task RunSetupAssistant(CommandContextContainer commandContext) { var dialogHandler = new DialogHandler(commandContext); await using (dialogHandler.ConfigureAwait(false)) { var creationData = await dialogHandler.RunForm <FractalLfgCreationFormData>() .ConfigureAwait(false); var entry = new FractalLfgConfigurationEntity { Title = creationData.Title, Description = creationData.Description, AliasName = creationData.AliasName, DiscordChannelId = commandContext.Channel.Id, DiscordMessageId = (await commandContext.Channel.SendMessageAsync(LocalizationGroup.GetText("BuildingProgress", "Building...")).ConfigureAwait(false)).Id }; using (var dbFactory = RepositoryFactory.CreateInstance()) { dbFactory.GetRepository <FractalLfgConfigurationRepository>() .Add(entry); } await _messageBuilder.RefreshMessageAsync(entry.Id).ConfigureAwait(false); var currentBotMessage = await commandContext.Channel .SendMessageAsync(LocalizationGroup.GetText("CreationCompletedMessage", "Creation completed! All creation messages will be deleted in 30 seconds.")).ConfigureAwait(false); dialogHandler.DialogContext.Messages.Add(currentBotMessage); await Task.Delay(TimeSpan.FromSeconds(30)).ConfigureAwait(false); await dialogHandler.DeleteMessages() .ConfigureAwait(false); } }
/// <summary> /// Execution one dialog element /// </summary> /// <typeparam name="TData">Type of the element result</typeparam> /// <param name="commandContext">Current command context</param> /// <param name="deleteMessages">Should the creation message be deleted?</param> /// <returns>Result</returns> public static async Task <TData> RunForm <TData>(CommandContextContainer commandContext, bool deleteMessages) where TData : new() { var serviceProvider = GlobalServiceProvider.Current.GetServiceProvider(); await using (serviceProvider.ConfigureAwait(false)) { var data = new TData(); var dialogContext = new DialogContext(); foreach (var property in data.GetType().GetProperties()) { var attribute = property.GetCustomAttributes(typeof(DialogElementAssignmentAttribute), false) .OfType <DialogElementAssignmentAttribute>() .FirstOrDefault(); if (attribute != null) { var service = (DialogElementBase)serviceProvider.GetService(attribute.DialogElementType); service.Initialize(commandContext, serviceProvider, dialogContext); property.SetValue(data, await service.InternalRun().ConfigureAwait(false)); } } if (deleteMessages) { dialogContext.Messages.Add(commandContext.Message); await commandContext.Channel .DeleteMessagesAsync(dialogContext.Messages) .ConfigureAwait(false); } return(data); } }
/// <summary> /// Joining a appointment /// </summary> /// <param name="commandContext">Command context</param> /// <param name="appointmentId">Id of the appointment</param> /// <param name="discordUserId">User id</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public async Task <long?> Join(CommandContextContainer commandContext, long appointmentId, ulong discordUserId) { long?registrationId = null; using (var dbFactory = RepositoryFactory.CreateInstance()) { var isAlreadyRegistered = false; var user = await _userManagementService.GetUserByDiscordAccountId(discordUserId) .ConfigureAwait(false); if (dbFactory.GetRepository <RaidAppointmentRepository>() .GetQuery() .Any(obj => obj.Id == appointmentId && obj.RaidDayTemplate.RaidExperienceAssignments.Any(obj2 => obj2.RaidExperienceLevel.Rank >= user.ExperienceLevelRank))) { if (dbFactory.GetRepository <RaidRegistrationRepository>() .AddOrRefresh(obj => obj.AppointmentId == appointmentId && obj.UserId == user.Id, obj => { if (obj.Id == 0) { obj.AppointmentId = appointmentId; obj.UserId = user.Id; obj.RegistrationTimeStamp = DateTime.Now; } else { isAlreadyRegistered = true; } }, obj => registrationId = obj.Id)) { if (registrationId != null && isAlreadyRegistered == false) { var registration = dbFactory.GetRepository <RaidRegistrationRepository>() .GetQuery() .Where(obj => obj.Id == registrationId) .Select(obj => new { IsDeadlineReached = obj.RaidAppointment.Deadline < obj.RegistrationTimeStamp, Registrations = obj.RaidAppointment .RaidRegistrations .Count(obj2 => obj2.LineupExperienceLevelId == obj.User.RaidExperienceLevelId), AvailableSlots = obj.RaidAppointment .RaidDayTemplate .RaidExperienceAssignments .Where(obj2 => obj2.ExperienceLevelId == obj.User.RaidExperienceLevelId) .Select(obj2 => (int?)obj2.Count) .FirstOrDefault(), obj.User.RaidExperienceLevelId }) .FirstOrDefault(); if (registration?.IsDeadlineReached == false) { if (registration.AvailableSlots != null && registration.AvailableSlots > registration.Registrations) { dbFactory.GetRepository <RaidRegistrationRepository>() .Refresh(obj => obj.Id == registrationId, obj => obj.LineupExperienceLevelId = registration.RaidExperienceLevelId); } else { await RefreshAppointment(appointmentId).ConfigureAwait(false); } } } } } else { await commandContext.Message .RespondAsync(LocalizationGroup.GetText("RequiredExperienceLevelMissing", "You don't have the required experience level.")) .ConfigureAwait(false); } } return(registrationId); }
/// <summary> /// Execution /// </summary> /// <param name="commandContext">Original command context</param> /// <param name="action">Action</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> protected async Task InvokeAsync(CommandContext commandContext, Func <CommandContextContainer, Task> action) { var commandContextContainer = new CommandContextContainer(commandContext, UserManagementService); try { await action(commandContextContainer).ConfigureAwait(false); } catch (TimeoutException) { } catch (OperationCanceledException) { } catch (ScruffyException ex) { await commandContextContainer.Channel .SendMessageAsync(ex.GetLocalizedMessage()) .ConfigureAwait(false); } catch (Exception ex) { var logEntryId = LoggingService.AddCommandLogEntry(LogEntryLevel.CriticalError, commandContext.Command?.QualifiedName, commandContextContainer.LastUserMessage?.Content, ex.Message, ex.ToString()); var client = HttpClientFactory.CreateClient(); using (var response = await client.GetAsync("https://g.tenor.com/v1/search?q=funny%20cat&key=RXM3VE2UGRU9&limit=50&contentfilter=high&ar_range=all") .ConfigureAwait(false)) { var jsonResult = await response.Content .ReadAsStringAsync() .ConfigureAwait(false); var searchResult = JsonConvert.DeserializeObject <SearchResultRoot>(jsonResult); var tenorEntry = searchResult.Results[new Random(DateTime.Now.Millisecond).Next(0, searchResult.Results.Count - 1)]; var gifUrl = tenorEntry.Media[0].Gif.Size < 8_388_608 ? tenorEntry.Media[0].Gif.Url : tenorEntry.Media[0].MediumGif.Size < 8_388_608 ? tenorEntry.Media[0].MediumGif.Url : tenorEntry.Media[0].NanoGif.Url; using (var downloadResponse = await client.GetAsync(gifUrl) .ConfigureAwait(false)) { var stream = await downloadResponse.Content .ReadAsStreamAsync() .ConfigureAwait(false); await using (stream.ConfigureAwait(false)) { var internalLocalizationGroup = LocalizationService.GetGroup(nameof(LocatedCommandModuleBase)); var builder = new DiscordMessageBuilder().WithContent(internalLocalizationGroup.GetFormattedText("CommandFailedMessage", "The command could not be executed. But I have an error code ({0}) and funny cat picture.", logEntryId ?? -1)) .WithFile("cat.gif", stream); await commandContextContainer.Channel .SendMessageAsync(builder) .ConfigureAwait(false); } } } } }
/// <summary> /// Initializing /// </summary> /// <param name="commandContext">Command context</param> /// <param name="serviceProvider">Service provider</param> /// <param name="dialogContext">Dialog context</param> internal void Initialize(CommandContextContainer commandContext, IServiceProvider serviceProvider, DialogContext dialogContext) { CommandContext = commandContext; ServiceProvider = serviceProvider; DialogContext = dialogContext; }