small fix+ codestyle change

This commit is contained in:
Master Kwoth 2016-04-06 21:19:29 +02:00
parent 5471012504
commit df32d2cf13
3 changed files with 100 additions and 56 deletions

3
.gitmodules vendored
View File

@ -1,6 +1,3 @@
[submodule "discord.net"] [submodule "discord.net"]
path = discord.net path = discord.net
url = git://github.com/rogueexception/discord.net.git url = git://github.com/rogueexception/discord.net.git
[submodule "Discord.Net"]
path = Discord.Net
url = https://github.com/RogueException/Discord.Net

View File

@ -1,4 +1,5 @@
using NadekoBot.Extensions; using NadekoBot.Classes.JSONModels;
using NadekoBot.Extensions;
using Newtonsoft.Json; using Newtonsoft.Json;
using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq;
using System; using System;
@ -10,34 +11,41 @@ using System.Net.Http;
using System.Security.Authentication; using System.Security.Authentication;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using System.Threading.Tasks; using System.Threading.Tasks;
using NadekoBot.Classes.JSONModels;
namespace NadekoBot.Classes { namespace NadekoBot.Classes
public enum RequestHttpMethod { {
public enum RequestHttpMethod
{
Get, Get,
Post Post
} }
public static class SearchHelper { public static class SearchHelper
{
private static DateTime lastRefreshed = DateTime.MinValue; private static DateTime lastRefreshed = DateTime.MinValue;
private static string token { get; set; } = ""; private static string token { get; set; } = "";
public static async Task<Stream> GetResponseStreamAsync(string url, public static async Task<Stream> GetResponseStreamAsync(string url,
IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get) { IEnumerable<KeyValuePair<string, string>> headers = null, RequestHttpMethod method = RequestHttpMethod.Get)
{
if (string.IsNullOrWhiteSpace(url)) if (string.IsNullOrWhiteSpace(url))
throw new ArgumentNullException(nameof(url)); throw new ArgumentNullException(nameof(url));
var httpClient = new HttpClient(); var httpClient = new HttpClient();
switch (method) { switch (method)
{
case RequestHttpMethod.Get: case RequestHttpMethod.Get:
if (headers != null) { if (headers != null)
foreach (var header in headers) { {
foreach (var header in headers)
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value); httpClient.DefaultRequestHeaders.TryAddWithoutValidation(header.Key, header.Value);
} }
} }
return await httpClient.GetStreamAsync(url); return await httpClient.GetStreamAsync(url);
case RequestHttpMethod.Post: case RequestHttpMethod.Post:
FormUrlEncodedContent formContent = null; FormUrlEncodedContent formContent = null;
if (headers != null) { if (headers != null)
{
formContent = new FormUrlEncodedContent(headers); formContent = new FormUrlEncodedContent(headers);
} }
var message = await httpClient.PostAsync(url, formContent); var message = await httpClient.PostAsync(url, formContent);
@ -49,14 +57,17 @@ namespace NadekoBot.Classes {
public static async Task<string> GetResponseStringAsync(string url, public static async Task<string> GetResponseStringAsync(string url,
IEnumerable<KeyValuePair<string, string>> headers = null, IEnumerable<KeyValuePair<string, string>> headers = null,
RequestHttpMethod method = RequestHttpMethod.Get) { RequestHttpMethod method = RequestHttpMethod.Get)
{
using (var streamReader = new StreamReader(await GetResponseStreamAsync(url, headers, method))) { using (var streamReader = new StreamReader(await GetResponseStreamAsync(url, headers, method)))
{
return await streamReader.ReadToEndAsync(); return await streamReader.ReadToEndAsync();
} }
} }
public static async Task<AnimeResult> GetAnimeData(string query) { public static async Task<AnimeResult> GetAnimeData(string query)
{
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query)); throw new ArgumentNullException(nameof(query));
@ -77,7 +88,8 @@ namespace NadekoBot.Classes {
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content)); return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
} }
public static async Task<MangaResult> GetMangaData(string query) { public static async Task<MangaResult> GetMangaData(string query)
{
if (string.IsNullOrWhiteSpace(query)) if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query)); throw new ArgumentNullException(nameof(query));
@ -98,10 +110,12 @@ namespace NadekoBot.Classes {
return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(content)); return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(content));
} }
private static async Task RefreshAnilistToken() { private static async Task RefreshAnilistToken()
{
if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29)) if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29))
lastRefreshed = DateTime.Now; lastRefreshed = DateTime.Now;
else { else
{
return; return;
} }
var headers = new Dictionary<string, string> { var headers = new Dictionary<string, string> {
@ -115,13 +129,15 @@ namespace NadekoBot.Classes {
token = JObject.Parse(content)["access_token"].ToString(); token = JObject.Parse(content)["access_token"].ToString();
} }
public static async Task<bool> ValidateQuery(Discord.Channel ch, string query) { public static async Task<bool> ValidateQuery(Discord.Channel ch, string query)
{
if (!string.IsNullOrEmpty(query.Trim())) return true; if (!string.IsNullOrEmpty(query.Trim())) return true;
await ch.Send("Please specify search parameters."); await ch.Send("Please specify search parameters.");
return false; return false;
} }
public static async Task<string> FindYoutubeUrlByKeywords(string keywords) { public static async Task<string> FindYoutubeUrlByKeywords(string keywords)
{
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
throw new InvalidCredentialException("Google API Key is missing."); throw new InvalidCredentialException("Google API Key is missing.");
if (string.IsNullOrWhiteSpace(keywords)) if (string.IsNullOrWhiteSpace(keywords))
@ -131,7 +147,8 @@ namespace NadekoBot.Classes {
//maybe it is already a youtube url, in which case we will just extract the id and prepend it with youtube.com?v= //maybe it is already a youtube url, in which case we will just extract the id and prepend it with youtube.com?v=
var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords); var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords);
if (match.Length > 1) { if (match.Length > 1)
{
return $"http://www.youtube.com?v={match.Groups["id"].Value}"; return $"http://www.youtube.com?v={match.Groups["id"].Value}";
} }
var response = var response =
@ -144,7 +161,8 @@ namespace NadekoBot.Classes {
return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString(); return "http://www.youtube.com/watch?v=" + obj.items[0].id.videoId.ToString();
} }
public static async Task<string> GetPlaylistIdByKeyword(string query) { public static async Task<string> GetPlaylistIdByKeyword(string query)
{
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
throw new ArgumentNullException(nameof(query)); throw new ArgumentNullException(nameof(query));
@ -159,8 +177,10 @@ namespace NadekoBot.Classes {
return obj.items[0].id.playlistId.ToString(); return obj.items[0].id.playlistId.ToString();
} }
public static async Task<IEnumerable<string>> GetVideoIDs(string playlist, int number = 30) { public static async Task<IEnumerable<string>> GetVideoIDs(string playlist, int number = 30)
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) { {
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
{
throw new ArgumentNullException(nameof(playlist)); throw new ArgumentNullException(nameof(playlist));
} }
if (number < 1 || number > 100) if (number < 1 || number > 100)
@ -178,7 +198,8 @@ namespace NadekoBot.Classes {
} }
public static async Task<string> GetDanbooruImageLink(string tag) { public static async Task<string> GetDanbooruImageLink(string tag)
{
var rng = new Random(); var rng = new Random();
if (tag == "loli") //loli doesn't work for some reason atm if (tag == "loli") //loli doesn't work for some reason atm
@ -236,7 +257,8 @@ namespace NadekoBot.Classes {
} }
internal static async Task<string> GetE621ImageLink(string tags) { internal static async Task<string> GetE621ImageLink(string tags)
{
var rng = new Random(); var rng = new Random();
var url = $"https://e621.net/post/index/{rng.Next(0, 5)}/{Uri.EscapeUriString(tags)}"; var url = $"https://e621.net/post/index/{rng.Next(0, 5)}/{Uri.EscapeUriString(tags)}";
var webpage = await GetResponseStringAsync(url); // first extract the post id and go to that posts page var webpage = await GetResponseStringAsync(url); // first extract the post id and go to that posts page
@ -244,16 +266,19 @@ namespace NadekoBot.Classes {
return matches[rng.Next(0, matches.Count)].Groups["url"].Value; return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
} }
public static async Task<string> ShortenUrl(string url) { public static async Task<string> ShortenUrl(string url)
{
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) return url; if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey)) return url;
try { try
{
var httpWebRequest = var httpWebRequest =
(HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" + (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url?key=" +
NadekoBot.Creds.GoogleAPIKey); NadekoBot.Creds.GoogleAPIKey);
httpWebRequest.ContentType = "application/json"; httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST"; httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync())) { using (var streamWriter = new StreamWriter(await httpWebRequest.GetRequestStreamAsync()))
{
var json = "{\"longUrl\":\"" + url + "\"}"; var json = "{\"longUrl\":\"" + url + "\"}";
streamWriter.Write(json); streamWriter.Write(json);
} }
@ -262,11 +287,14 @@ namespace NadekoBot.Classes {
if (httpResponse == null) return "HTTP_RESPONSE_ERROR"; if (httpResponse == null) return "HTTP_RESPONSE_ERROR";
var responseStream = httpResponse.GetResponseStream(); var responseStream = httpResponse.GetResponseStream();
if (responseStream == null) return "RESPONSE_STREAM ERROR"; if (responseStream == null) return "RESPONSE_STREAM ERROR";
using (var streamReader = new StreamReader(responseStream)) { using (var streamReader = new StreamReader(responseStream))
{
var responseText = await streamReader.ReadToEndAsync(); var responseText = await streamReader.ReadToEndAsync();
return Regex.Match(responseText, @"""id"": ?""(?<id>.+)""").Groups["id"].Value; return Regex.Match(responseText, @"""id"": ?""(?<id>.+)""").Groups["id"].Value;
} }
} catch (Exception ex) { }
catch (Exception ex)
{
Console.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString());
return url; return url;
} }

View File

@ -1,25 +1,30 @@
using System; using Discord.Commands;
using Discord.Modules; using Discord.Modules;
using Discord.Commands;
using Newtonsoft.Json.Linq;
using NadekoBot.Classes; using NadekoBot.Classes;
using Newtonsoft.Json.Linq;
using System;
namespace NadekoBot.Modules { namespace NadekoBot.Modules
internal class NSFW : DiscordModule { {
internal class NSFW : DiscordModule
{
private readonly Random rng = new Random(); private readonly Random rng = new Random();
public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.NSFW; public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.NSFW;
public override void Install(ModuleManager manager) { public override void Install(ModuleManager manager)
manager.CreateCommands("", cgb => { {
manager.CreateCommands("", cgb =>
{
cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance); cgb.AddCheck(Classes.Permissions.PermissionChecker.Instance);
cgb.CreateCommand(Prefix + "hentai") cgb.CreateCommand(Prefix + "hentai")
.Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing") .Description("Shows a random NSFW hentai image from gelbooru and danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~hentai yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink("rating%3Aexplicit+" + tag)); await e.Channel.SendMessage(":heart: Gelbooru: " + await SearchHelper.GetGelbooruImageLink("rating%3Aexplicit+" + tag));
await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink("rating%3Aexplicit+" + tag)); await e.Channel.SendMessage(":heart: Danbooru: " + await SearchHelper.GetDanbooruImageLink("rating%3Aexplicit+" + tag));
@ -27,62 +32,76 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(Prefix + "danbooru") cgb.CreateCommand(Prefix + "danbooru")
.Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing") .Description("Shows a random hentai image from danbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~danbooru yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag)); await e.Channel.SendMessage(await SearchHelper.GetDanbooruImageLink(tag));
}); });
cgb.CreateCommand(Prefix + "gelbooru") cgb.CreateCommand(Prefix + "gelbooru")
.Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing") .Description("Shows a random hentai image from gelbooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag)); await e.Channel.SendMessage(await SearchHelper.GetGelbooruImageLink(tag));
}); });
cgb.CreateCommand(Prefix + "safebooru") cgb.CreateCommand(Prefix + "safebooru")
.Description("Shows a random image from safebooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing") .Description("Shows a random image from safebooru with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~safebooru yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetSafebooruImageLink(tag)); await e.Channel.SendMessage(await SearchHelper.GetSafebooruImageLink(tag));
}); });
cgb.CreateCommand(Prefix + "rule34") cgb.CreateCommand(Prefix + "rule34")
.Description("Shows a random image from rule34.xx with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing") .Description("Shows a random image from rule34.xx with a given tag. Tag is optional but preffered. (multiple tags are appended with +)\n**Usage**: ~gelbooru yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetRule34ImageLink(tag)); await e.Channel.SendMessage(await SearchHelper.GetRule34ImageLink(tag));
}); });
cgb.CreateCommand(Prefix + "e621") cgb.CreateCommand(Prefix + "e621")
.Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri+kissing") .Description("Shows a random hentai image from e621.net with a given tag. Tag is optional but preffered. Use spaces for multiple tags.\n**Usage**: ~e621 yuri+kissing")
.Parameter("tag", ParameterType.Unparsed) .Parameter("tag", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
var tag = e.GetArg("tag")?.Trim() ?? ""; var tag = e.GetArg("tag")?.Trim() ?? "";
await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag)); await e.Channel.SendMessage(await SearchHelper.GetE621ImageLink(tag));
}); });
cgb.CreateCommand(Prefix + "cp") cgb.CreateCommand(Prefix + "cp")
.Description("We all know where this will lead you to.") .Description("We all know where this will lead you to.")
.Parameter("anything", ParameterType.Unparsed) .Parameter("anything", ParameterType.Unparsed)
.Do(async e => { .Do(async e =>
{
await e.Channel.SendMessage("http://i.imgur.com/MZkY1md.jpg"); await e.Channel.SendMessage("http://i.imgur.com/MZkY1md.jpg");
}); });
cgb.CreateCommand(Prefix + "boobs") cgb.CreateCommand(Prefix + "boobs")
.Description("Real adult content.") .Description("Real adult content.")
.Do(async e => { .Do(async e =>
try { {
try
{
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}"))[0]; var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.oboobs.ru/boobs/{rng.Next(0, 9380)}"))[0];
await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }"); await e.Channel.SendMessage($"http://media.oboobs.ru/{ obj["preview"].ToString() }");
} catch (Exception ex) { }
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 {ex.Message}"); await e.Channel.SendMessage($"💢 {ex.Message}");
} }
}); });
cgb.CreateCommand(Prefix + "butts") cgb.CreateCommand(Prefix + "butts")
.Alias(Prefix + "ass", Prefix + "butt") .Alias(Prefix + "ass", Prefix + "butt")
.Description("Real adult content.") .Description("Real adult content.")
.Do(async e => { .Do(async e =>
try { {
try
{
var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}"))[0]; var obj = JArray.Parse(await SearchHelper.GetResponseStringAsync($"http://api.obutts.ru/butts/{rng.Next(0, 3373)}"))[0];
await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }"); await e.Channel.SendMessage($"http://media.obutts.ru/{ obj["preview"].ToString() }");
} catch (Exception ex) { }
catch (Exception ex)
{
await e.Channel.SendMessage($"💢 {ex.Message}"); await e.Channel.SendMessage($"💢 {ex.Message}");
} }
}); });