Skip to content

Commit

Permalink
New Command Fixes
Browse files Browse the repository at this point in the history
- Fixed the ip command input not being processed, updated the output.
- Fixed the GoodReads module not being registered.
- Fixed the news and books commands not returning results.
  • Loading branch information
CriticalFlaw committed Sep 18, 2019
1 parent 52b455c commit b07adba
Show file tree
Hide file tree
Showing 12 changed files with 159 additions and 41 deletions.
17 changes: 13 additions & 4 deletions src/FlawBOT.Core/Modules/Misc/MiscModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,23 @@ public async Task Greet(CommandContext ctx,
[Command("ip")]
[Description("Retrieve the IP address location")]
public async Task IPLocation(CommandContext ctx,
[Description("IP Address")] [RemainingText] IPAddress address)
[Description("IP Address")] string address)
{
if (address == null) return;
var results = GoogleService.GetIPLocationAsync(address).Result;
if (string.IsNullOrWhiteSpace(address) || !IPAddress.TryParse(address, out IPAddress ip)) return;
var results = GoogleService.GetIPLocationAsync(ip).Result;
if (results.Status != "success")
await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Warning);
else
await BotServices.SendEmbedAsync(ctx, results.City, EmbedType.Default);
{
var output = new DiscordEmbedBuilder()
.AddField("Location", $"{results.City}, {results.Region}, {results.Country}", true)
.AddField("ISP", results.ISP, true)
.AddField("Longitude", results.Longitude.ToString(), true)
.AddField("Latitude", results.Latitude.ToString(), true)
.WithFooter($"IP: {results.Query}")
.WithColor(new DiscordColor("#4d2f63"));
await ctx.RespondAsync(embed: output.Build());
}
}

#endregion COMMAND_IP
Expand Down
45 changes: 24 additions & 21 deletions src/FlawBOT.Core/Modules/Search/GoodReadModule.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
using System.Linq;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using DSharpPlus.Interactivity;
using FlawBOT.Core.Properties;
using FlawBOT.Framework.Models;
using FlawBOT.Framework.Services;
using FlawBOT.Framework.Services.Search;

namespace FlawBOT.Core.Modules.Search
namespace FlawBOT.Modules
{
[Cooldown(3, 5, CooldownBucketType.Channel)]
public class GoodReadModule : BaseCommandModule
{
#region COMMAND_OMDB
#region COMMAND_BOOKS

[Command("book")]
[Aliases("goodreads", "books")]
Expand All @@ -24,30 +26,31 @@ public async Task Books(CommandContext ctx,
{
if (!BotServices.CheckUserInput(query)) return;
var results = GoodReadService.GetBookDataAsync(query).Result;
if (string.IsNullOrWhiteSpace(results.Title))
if (results.Books.Count > 0)
await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_GENERIC, EmbedType.Missing);
else
{
var output = new DiscordEmbedBuilder()
.WithTitle(results.Title + $" ({results.Pages} pages)")
.WithDescription(results.Description.Length < 500 ? results.Description : results.Description.Take(500) + "...")
.AddField("Publish Date", results.PublicationDate.ToString() ?? "Unknown", true)
.AddField("Ratings", $"Average {results.AverageRating} ({results.RatingsCount} total ratings)", true)
.AddField("Publisher", results.Publisher, true)
.WithImageUrl(results.ImageUrl ?? results.SmallImageUrl)
.WithUrl(results.Url)
.WithFooter("ISBN: " + results.Isbn)
.WithColor(new DiscordColor("#372213"));
foreach (var book in results.Books)
{
// TODO: Add page count, publication, ISBN, URLs
var output = new DiscordEmbedBuilder()
.WithTitle(book.Work.Title)
.AddField("Author", book.Work.Author.Name ?? "Unknown", true)
.AddField("Publication Year", book.PublicationYear.Text ?? "Unknown", true)
.AddField("Ratings", $"Average {book.RatingAverage} ({book.RatingCount} total ratings)", true)
.WithImageUrl(book.Work.ImageUrl ?? book.Work.ImageUrlSmall)
.WithFooter("Type 'next' within 10 seconds for the next book.")
.WithColor(new DiscordColor("#372213"));
var message = await ctx.RespondAsync(embed: output.Build());

var values = new StringBuilder();
foreach (var author in results.Authors)
values.Append(author.Name + "\n");
output.AddField("Author(s)", values.ToString() ?? "Unknown", true);

await ctx.RespondAsync(embed: output.Build());
var interactivity = await ctx.Client.GetInteractivity().WaitForMessageAsync(m => m.Channel.Id == ctx.Channel.Id && m.Content.ToLowerInvariant() == "next", TimeSpan.FromSeconds(10));
if (interactivity.Result == null) break;
await BotServices.RemoveMessage(interactivity.Result);
await BotServices.RemoveMessage(message);
}
}
}

#endregion COMMAND_OMDB
#endregion COMMAND_BOOKS
}
}
7 changes: 3 additions & 4 deletions src/FlawBOT.Core/Modules/Search/GoogleModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,13 @@ public async Task News(CommandContext ctx,
foreach (var article in results.Articles)
{
var output = new DiscordEmbedBuilder()
.WithTitle(article.Title + " (Powered by News API)")
.WithAuthor(article.Author ?? "Unknown")
.WithTitle(article.Title)
.WithTimestamp(article.PublishDate)
.WithDescription(article.Description.Length < 500 ? article.Description : article.Description.Take(500) + "...")
.WithUrl(article.Url)
.WithImageUrl(article.UrlImage)
.WithFooter("Type 'next' within 10 seconds for the next article")
.WithColor(SharedData.DefaultColor);
.WithFooter("Type 'next' within 10 seconds for the next article. Powered by News API")
.WithColor(new DiscordColor("#253B80"));
var message = await ctx.RespondAsync(embed: output.Build());

var interactivity = await ctx.Client.GetInteractivity().WaitForMessageAsync(m => m.Channel.Id == ctx.Channel.Id && m.Content.ToLowerInvariant() == "next", TimeSpan.FromSeconds(10));
Expand Down
1 change: 1 addition & 0 deletions src/FlawBOT.Core/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ public async Task RunBotAsync()
Commands.RegisterCommands<PollModule>();
Commands.RegisterCommands<AmiiboModule>();
Commands.RegisterCommands<DictionaryModule>();
Commands.RegisterCommands<GoodReadModule>();
Commands.RegisterCommands<GoogleModule>();
Commands.RegisterCommands<ImgurModule>();
Commands.RegisterCommands<NASAModule>();
Expand Down
1 change: 0 additions & 1 deletion src/FlawBOT.Framework/FlawBOT.Framework.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
<PackageReference Include="DSharpPlus" Version="4.0.0-nightly-00624" />
<PackageReference Include="DSharpPlus.CommandsNext" Version="4.0.0-nightly-00624" />
<PackageReference Include="DSharpPlus.Interactivity" Version="4.0.0-nightly-00624" />
<PackageReference Include="Goodreads" Version="1.0.1" />
<PackageReference Include="Google.Apis.YouTube.v3" Version="1.41.1.1699" />
<PackageReference Include="Imgur.API" Version="4.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
Expand Down
89 changes: 89 additions & 0 deletions src/FlawBOT.Framework/Models/Search/GoodReadsData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace FlawBOT.Framework.Models
{
[XmlRoot(ElementName = "results")]
public class GoodReadsResponse
{
[XmlElement(ElementName = "work")]
public List<Book> Books { get; set; }
}

[XmlRoot(ElementName = "work")]
public class Book
{
[XmlElement(ElementName = "best_book")]
public Work Work { get; set; }

[XmlElement(ElementName = "original_publication_day")]
public PublicationDay PublicationDay { get; set; }

[XmlElement(ElementName = "original_publication_month")]
public PublicationMonth PublicationMonth { get; set; }

[XmlElement(ElementName = "original_publication_year")]
public PublicationYear PublicationYear { get; set; }

[XmlElement(ElementName = "average_rating")]
public string RatingAverage { get; set; }

[XmlElement(ElementName = "ratings_count")]
public RatingsCount RatingCount { get; set; }
}

[XmlRoot(ElementName = "best_book")]
public class Work
{
[XmlElement(ElementName = "title")]
public string Title { get; set; }

[XmlElement(ElementName = "author")]
public Author Author { get; set; }

[XmlElement(ElementName = "image_url")]
public string ImageUrl { get; set; }

[XmlElement(ElementName = "small_image_url")]
public string ImageUrlSmall { get; set; }
}

[XmlRoot(ElementName = "author")]
public class Author
{
[XmlElement(ElementName = "name")]
public string Name { get; set; }
}

[XmlRoot(ElementName = "original_publication_day")]
public class PublicationDay
{
[XmlText]
public string Text { get; set; }
}

[XmlRoot(ElementName = "original_publication_month")]
public class PublicationMonth
{
[XmlText]
public string Text { get; set; }
}

[XmlRoot(ElementName = "original_publication_year")]
public class PublicationYear
{
[XmlText]
public string Text { get; set; }
}

[XmlRoot(ElementName = "ratings_count")]
public class RatingsCount
{
[XmlText]
public string Text { get; set; }

[XmlAttribute(AttributeName = "type")]
public string Type { get; set; }
}
}
6 changes: 3 additions & 3 deletions src/FlawBOT.Framework/Models/Search/GoogleData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ public class Weather

public class NewsData
{
[JsonProperty("@status")]
[JsonProperty("status")]
public string Status { get; set; }

[JsonProperty("totalResults")]
Expand Down Expand Up @@ -173,10 +173,10 @@ public class Article

public class Source
{
[JsonProperty("@id")]
[JsonProperty("id")]
public string ID { get; set; }

[JsonProperty("@name")]
[JsonProperty("name")]
public string Name { get; set; }
}

Expand Down
9 changes: 9 additions & 0 deletions src/FlawBOT.Framework/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions src/FlawBOT.Framework/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@
<data name="API_DogPhoto" xml:space="preserve">
<value>https://dog.ceo/api/breeds/image/random</value>
</data>
<data name="API_GoodReads" xml:space="preserve">
<value>https://www.goodreads.com/search/index.xml</value>
</data>
<data name="API_Google_Geo" xml:space="preserve">
<value>https://maps.googleapis.com/maps/api/geocode/json</value>
</data>
Expand Down
16 changes: 11 additions & 5 deletions src/FlawBOT.Framework/Services/Search/GoodReadService.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
using System.Threading.Tasks;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Serialization;
using FlawBOT.Framework.Common;
using FlawBOT.Framework.Models;
using FlawBOT.Framework.Properties;
using Goodreads;
using Goodreads.Http;
using Goodreads.Models.Response;
using Newtonsoft.Json;

namespace FlawBOT.Framework.Services.Search
{
public class GoodReadService : HttpHandler
{
public static async Task<Book> GetBookDataAsync(string query)
public static async Task<GoodReadsResponse> GetBookDataAsync(string query)
{
var client = GoodreadsClient.Create(TokenHandler.Tokens.GoodReadsKey, TokenHandler.Tokens.GoodReadsSecret);
var results = await client.Books.GetByTitle(query);
return results;
var _serializer = new XmlSerializer(typeof(GoodReadsResponse));
var results = await _http.GetStreamAsync(Resources.API_GoodReads + "?key=" + TokenHandler.Tokens.GoodReadsKey + "&q=" + WebUtility.UrlEncode(query));
return (GoodReadsResponse)_serializer.Deserialize(results);
}
}
}
2 changes: 1 addition & 1 deletion src/FlawBOT.Framework/Services/Search/GoogleService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public static async Task<IPLocationData> GetIPLocationAsync(IPAddress query)

public static async Task<NewsData> GetNewsDataAsync(string query = "")
{
var results = await _http.GetStringAsync(Resources.API_News + "?q=" + query + "&apiKey=" + TokenHandler.Tokens.NewsToken);
var results = await _http.GetStringAsync(Resources.API_News + "&q=" + query + "&apiKey=" + TokenHandler.Tokens.NewsToken);
return JsonConvert.DeserializeObject<NewsData>(results);
}

Expand Down
4 changes: 2 additions & 2 deletions src/FlawBOT.Test/Search/GoodReadTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ internal class GoodReadTests
[Test]
public void GetBookData()
{
Assert.IsTrue(!string.IsNullOrWhiteSpace(GoodReadService.GetBookDataAsync("Ender's Game").Result.Title));
Assert.IsFalse(string.IsNullOrWhiteSpace(GoodReadService.GetBookDataAsync("Bender's Game").Result.Title));
Assert.IsTrue(GoodReadService.GetBookDataAsync("Ender's Game").Result.Books.Count > 0);
Assert.IsFalse(GoodReadService.GetBookDataAsync("Bender's Game").Result.Books.Count > 0);
}
}
}

0 comments on commit b07adba

Please sign in to comment.