public async Task AddZoneAlias(string zoneName, string alias) { IZone zone = await this.GetZoneOrReplyAsync(zoneName); if (zone.IsValid()) { alias = ZoneUtilities.GetFullName(alias); if (zone.GetFullName().Equals(alias, StringComparison.OrdinalIgnoreCase) || zone.Aliases.Contains(alias, StringComparer.OrdinalIgnoreCase)) { // The zone already has the given name/alias. await ReplyWarningAsync($"{zone.GetFullName().ToBold()} already has this name."); } else if ((await Db.GetZoneAsync(alias)).IsValid()) { // Another zone already has the given name/alias. await ReplyErrorAsync($"There is already a zone named {alias.ToBold()}."); } else { zone.Aliases.Add(alias); await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"{alias.ToBold()} was successfully added as an alias for {zone.GetFullName().ToBold()}."); } } }
public async Task SetZoneName(string oldZoneName, string newZoneName) { IZone zone = await this.GetZoneOrReplyAsync(oldZoneName); if (zone.IsValid()) { oldZoneName = zone.GetFullName(); newZoneName = ZoneUtilities.GetFullName(newZoneName); if ((await Db.GetZoneAsync(newZoneName)).IsValid()) { // The given name cannot be the name of an existing zone. await ReplyErrorAsync($"There is already a zone named {newZoneName.ToBold()}."); } else { if (oldZoneName.Equals(newZoneName, System.StringComparison.OrdinalIgnoreCase)) { await ReplyWarningAsync($"{zone.GetFullName().ToBold()} already has this name."); } else { zone.Name = newZoneName; await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"{oldZoneName.ToBold()} was successfully renamed to {newZoneName.ToBold()}."); } } } }
public async Task SetParentZone(string zoneName, string parentZoneName) { IZone zone = await Db.GetZoneAsync(zoneName); IZone parent = await Db.GetZoneAsync(parentZoneName); if (await BotUtils.ReplyValidateZoneAsync(Context, zone) && await BotUtils.ReplyValidateZoneAsync(Context, parent)) { if (zone.Id == parent.Id) { await BotUtils.ReplyAsync_Error(Context, "A zone cannot be its own parent."); } else if (parent.ParentId == zone.Id) { await BotUtils.ReplyAsync_Error(Context, "A zone cannot have its child as its parent."); } else if (zone.ParentId == parent.Id) { await BotUtils.ReplyAsync_Warning(Context, string.Format("The parent zone of **{0}** is already **{1}**.", zone.GetFullName(), parent.GetFullName())); } else { zone.ParentId = parent.Id; await Db.UpdateZoneAsync(zone); await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully set the parent zone of **{0}** to **{1}**.", zone.GetFullName(), parent.GetFullName())); } } }
public async Task SetZoneType(string zoneName, string zoneType) { IZone zone = await Db.GetZoneAsync(zoneName); IZoneType type = await Db.GetZoneTypeAsync(zoneType); if (await BotUtils.ReplyValidateZoneAsync(Context, zone) && await BotUtils.ReplyValidateZoneTypeAsync(Context, type)) { zone.TypeId = type.Id; await Db.UpdateZoneAsync(zone); await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully set the type of {0}**{1}** to **{2}**.", zone.GetFullName().StartsWith("Zone") ? string.Empty : "zone ", zone.GetFullName(), type.Name)); } }
public async Task SetZoneDescription(string zoneName, string description) { // Get the zone from the database. IZone zone = await this.GetZoneOrReplyAsync(zoneName); if (zone.IsValid()) { // Update the description for the zone. zone.Description = description; await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"Successfully updated the description for {zone.GetFullName().ToBold()}."); } }
// Private members private async Task <IEnumerable <string> > GetEmptyZoneIdeasAsync() { // Checks for empty zones List <string> ideas = new List <string>(); using (SQLiteCommand cmd = new SQLiteCommand("SELECT * FROM Zones WHERE id NOT IN (SELECT zone_id FROM SpeciesZones)")) { foreach (DataRow row in await Db.GetRowsAsync(cmd)) { IZone zone = await Db.CreateZoneFromDataRowAsync(row, GetZoneOptions.Fast); if (!zone.Flags.HasFlag(ZoneFlags.Retired)) { ideas.Add($"{zone.GetFullName().ToBold()} does not contain any species yet. Why not make one?"); } } } return(ideas); }
public async Task Bulk([Remainder] string operationString) { // Instantiate the bulk operation and get the query results. Taxa.IBulkOperation bulkOperation = new Taxa.BulkOperation(operationString); ISearchResult queryResult = await Db.GetSearchResultsAsync(SearchContext, bulkOperation.Query); if (queryResult.TotalResults() <= 0) { await ReplyInfoAsync("No species matching this query could be found."); } else { // Perform the requested operation. switch (bulkOperation.OperationName) { case "addto": { // Move the species into the given zone. if (bulkOperation.Arguments.Count() != 1) { throw new Exception(string.Format("This operation requires **{0}** argument(s), but was given **{1}**.", 1, bulkOperation.Arguments.Count())); } string zoneName = bulkOperation.Arguments.First(); IZone zone = await Db.GetZoneAsync(zoneName); if (await BotUtils.ReplyValidateZoneAsync(Context, zone, zoneName)) { IPaginatedMessage message = new PaginatedMessage(string.Format("**{0}** species will be added to **{1}**. Is this OK?", queryResult.TotalResults(), zone.GetFullName())) { Restricted = true }; message.AddReaction(PaginatedMessageReactionType.Yes, async(args) => { foreach (ISpecies species in await queryResult.GetResultsAsync()) { await Db.AddZonesAsync(species, new IZone[] { zone }); } await ReplySuccessAsync("Operation completed successfully."); }); await ReplyAsync(message); } } break; default: await ReplyErrorAsync($"Unknown operation {bulkOperation.OperationName.ToBold()}."); break; } } }
private async Task ShowZoneAsync(IZone zone) { if (await this.ReplyValidateZoneAsync(zone)) { // Get all species living in this zone. List <ISpecies> speciesList = new List <ISpecies>((await Db.GetSpeciesAsync(zone)).Where(species => !species.IsExtinct())); speciesList.Sort((lhs, rhs) => TaxonFormatter.GetString(lhs, false).CompareTo(TaxonFormatter.GetString(rhs, false))); // Starting building a paginated message. // The message will have a paginated species list, and a toggle button to display the species sorted by role. string description = zone.GetDescriptionOrDefault(); if (!speciesList.Any()) { description += "\n\nThis zone does not contain any species."; } List <IEmbed> embedPages = new List <IEmbed>(); if (zone.Fields.Any()) { embedPages.Add(new Embed()); foreach (IZoneField field in zone.Fields) { if (!string.IsNullOrWhiteSpace(field.GetName()) && !string.IsNullOrWhiteSpace(field.GetValue())) { embedPages.Last().AddField(field.GetName(), field.GetValue(), true); } } embedPages.Last().Description = description; } embedPages.AddRange(EmbedUtilities.CreateEmbedPages(string.Format("Extant species in this zone ({0}):", speciesList.Count()), speciesList, formatter: TaxonFormatter)); // Add title, decription, etc., to all pages. if (!embedPages.Any()) { embedPages.Add(new Embed()); } IZoneType type = await Db.GetZoneTypeAsync(zone.TypeId) ?? new ZoneType(); string aliases = zone.Aliases.Any() ? string.Format("({0})", string.Join(", ", zone.Aliases.Select(alias => alias.ToTitle()))) : string.Empty; string title = string.Format("{0} {1} {2}", type.Icon, zone.GetFullName(), aliases).Trim(); System.Drawing.Color color = type.Color; foreach (IEmbed page in embedPages) { page.Title = title; page.ThumbnailUrl = zone.Pictures.FirstOrDefault()?.Url; page.Color = color; // Add the zone description to all pages if the zone doesn't have any fields (because the info page will be missing). if (!zone.Fields.Any()) { page.Description = description; } } IPaginatedMessage message = new PaginatedMessage(embedPages); message.AddPageNumbers(); // This page will have species organized by role. // Only bother with the role page if species actually exist in this zone. if (speciesList.Count() > 0) { IEmbed rolesPage = new Embed { Title = title, ThumbnailUrl = zone.GetPictureUrl(), Color = color }; Dictionary <string, List <ISpecies> > rolesMap = new Dictionary <string, List <ISpecies> >(); foreach (ISpecies species in speciesList) { IEnumerable <Common.Roles.IRole> roles_list = await Db.GetRolesAsync(species); if (roles_list.Count() <= 0) { if (!rolesMap.ContainsKey("no role")) { rolesMap["no role"] = new List <ISpecies>(); } rolesMap["no role"].Add(species); continue; } foreach (Common.Roles.IRole role in roles_list) { if (!rolesMap.ContainsKey(role.GetName())) { rolesMap[role.GetName()] = new List <ISpecies>(); } rolesMap[role.GetName()].Add(species); } } // Sort the list of species belonging to each role. foreach (List <ISpecies> i in rolesMap.Values) { i.Sort((lhs, rhs) => TaxonFormatter.GetString(lhs, false).CompareTo(TaxonFormatter.GetString(rhs, false))); } // Create a sorted list of keys so that the roles are in order. List <string> sorted_keys = new List <string>(rolesMap.Keys); sorted_keys.Sort(); foreach (string i in sorted_keys) { StringBuilder lines = new StringBuilder(); foreach (ISpecies j in rolesMap[i]) { lines.AppendLine(TaxonFormatter.GetString(j)); } rolesPage.AddField(string.Format("{0}s ({1})", StringUtilities.ToTitleCase(i), rolesMap[i].Count()), lines.ToString(), inline: true); } // Add the page to the builder. message.AddReaction("🇷", async(args) => { if (args.Emoji != "🇷") { return; } args.Message.PaginationEnabled = !args.ReactionAdded; if (args.ReactionAdded) { args.Message.CurrentPage = new Message() { Embed = rolesPage } } ; else { args.Message.CurrentPage = null; } await Task.CompletedTask; }); } await ReplyAsync(message); } }
public async Task RemoveZoneFlag(string zoneName, params string[] flagNames) { IZone zone = await this.GetZoneOrReplyAsync(zoneName); if (zone.IsValid()) { ZoneFlags parsedFlags = ParseZoneFlags(flagNames); IEnumerable <string> parsedFlagNames = Enum.GetValues(typeof(ZoneFlags)).Cast <ZoneFlags>() .Where(value => value != ZoneFlags.None) .Where(value => parsedFlags.HasFlag(value)) .Select(flag => flag.ToString()); if (parsedFlags == ZoneFlags.None) { await ReplyErrorAsync("No valid flags were specified."); } else { zone.Flags &= ~parsedFlags; await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"Flag(s) {StringUtilities.ConjunctiveJoin(parsedFlagNames.Select(name => name.ToBold()))} successfully unset for {zone.GetFullName().ToBold()}."); } } }
public async Task RemoveZoneField(string zoneName, string fieldName) { IZone zone = await this.GetZoneOrReplyAsync(zoneName); if (zone.IsValid()) { IZoneField existingField = zone.Fields .Where(field => field.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (existingField != null) { zone.Fields.Remove(existingField); await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"The field {fieldName.ToTitle().ToBold()} was successfully removed from {zone.GetFullName().ToBold()}."); } else { await ReplyWarningAsync($"No field named {fieldName.ToTitle()} exists."); } } }
public async Task AddZoneField(string zoneName, string fieldName, string fieldValue) { IZone zone = await this.GetZoneOrReplyAsync(zoneName); if (zone.IsValid()) { IZoneField existingField = zone.Fields .Where(field => field.Name.Equals(fieldName, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (existingField != null) { existingField.Value = fieldValue; await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"The value for field {existingField.GetName().ToBold()} was successfully updated."); } else { IZoneField field = new ZoneField(fieldName, fieldValue); zone.Fields.Add(field); await Db.UpdateZoneAsync(zone); await ReplySuccessAsync($"Field {field.GetName().ToBold()} was successfully added to {zone.GetFullName().ToBold()}."); } } }
public async Task SetZonePic(string zone, string imageUrl) { // Make sure that the given zone exists. IZone z = await Db.GetZoneAsync(zone); if (!await BotUtils.ReplyValidateZoneAsync(Context, z)) { return; } // Make sure the image URL is valid. if (!await BotUtils.ReplyIsImageUrlValidAsync(Context, imageUrl)) { return; } // Update the zone. using (SQLiteCommand cmd = new SQLiteCommand("UPDATE Zones SET pics=$pics WHERE id=$id;")) { cmd.Parameters.AddWithValue("$pics", imageUrl); cmd.Parameters.AddWithValue("$id", z.Id); await Db.ExecuteNonQueryAsync(cmd); } await BotUtils.ReplyAsync_Success(Context, string.Format("Successfully updated the picture for **{0}**.", z.GetFullName())); }