~# command (thanks to blaubeerwald, formatting

This commit is contained in:
Master Kwoth 2016-02-18 23:40:56 +01:00
parent e9b8084cc4
commit e1f5ba8169
3 changed files with 103 additions and 63 deletions

View File

@ -33,7 +33,8 @@ namespace NadekoBot.Classes.Music {
if (SongQueue.Count > 0) if (SongQueue.Count > 0)
await LoadNextSong(); await LoadNextSong();
} else if (CurrentSong.State == StreamState.Completed || NextSong) { }
else if (CurrentSong.State == StreamState.Completed || NextSong) {
NextSong = false; NextSong = false;
await LoadNextSong(); await LoadNextSong();
} }
@ -57,7 +58,8 @@ namespace NadekoBot.Classes.Music {
if (SongQueue.Count != 0) { if (SongQueue.Count != 0) {
CurrentSong = SongQueue[0]; CurrentSong = SongQueue[0];
SongQueue.RemoveAt(0); SongQueue.RemoveAt(0);
} else { }
else {
VoiceClient?.Disconnect(); VoiceClient?.Disconnect();
VoiceClient = null; VoiceClient = null;
return; return;
@ -71,7 +73,8 @@ namespace NadekoBot.Classes.Music {
Console.WriteLine($"Joined voicechannel [{DateTime.Now.Second}]"); Console.WriteLine($"Joined voicechannel [{DateTime.Now.Second}]");
} }
await Task.Factory.StartNew(async () => await CurrentSong?.Start(), TaskCreationOptions.LongRunning).Unwrap(); await Task.Factory.StartNew(async () => await CurrentSong?.Start(), TaskCreationOptions.LongRunning).Unwrap();
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine($"Starting failed: {ex}"); Console.WriteLine($"Starting failed: {ex}");
CurrentSong?.Stop(); CurrentSong?.Stop();
CurrentSong = null; CurrentSong = null;
@ -95,7 +98,7 @@ namespace NadekoBot.Classes.Music {
value = 0; value = 0;
if (value > 150) if (value > 150)
value = 150; value = 150;
this.Volume = value/100f; this.Volume = value / 100f;
return value; return value;
} }

View File

@ -14,7 +14,8 @@ namespace NadekoBot.Classes {
var wr = (HttpWebRequest)WebRequest.Create(v); var wr = (HttpWebRequest)WebRequest.Create(v);
try { try {
return (await (wr).GetResponseAsync()).GetResponseStream(); return (await (wr).GetResponseAsync()).GetResponseStream();
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine("error in getresponse stream " + ex); Console.WriteLine("error in getresponse stream " + ex);
return null; return null;
} }
@ -23,11 +24,9 @@ namespace NadekoBot.Classes {
public static async Task<string> GetResponseAsync(string v) => public static async Task<string> GetResponseAsync(string v) =>
await new StreamReader((await ((HttpWebRequest)WebRequest.Create(v)).GetResponseAsync()).GetResponseStream()).ReadToEndAsync(); await new StreamReader((await ((HttpWebRequest)WebRequest.Create(v)).GetResponseAsync()).GetResponseStream()).ReadToEndAsync();
public static async Task<string> GetResponseAsync(string v, IEnumerable<Tuple<string, string>> headers) { public static async Task<string> GetResponseAsync(string v, WebHeaderCollection headers) {
var wr = (HttpWebRequest)WebRequest.Create(v); var wr = (HttpWebRequest)WebRequest.Create(v);
foreach (var header in headers) { wr.Headers = headers;
wr.Headers.Add(header.Item1, header.Item2);
}
return await new StreamReader((await wr.GetResponseAsync()).GetResponseStream()).ReadToEndAsync(); return await new StreamReader((await wr.GetResponseAsync()).GetResponseStream()).ReadToEndAsync();
} }
@ -47,7 +46,8 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("anime/" + smallObj["id"]); rq = new RestSharp.RestRequest("anime/" + smallObj["id"]);
rq.AddParameter("access_token", token); rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content)); return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(cl.Execute(rq).Content));
} catch { }
catch {
return null; return null;
} }
} }
@ -66,7 +66,8 @@ namespace NadekoBot.Classes {
rq = new RestSharp.RestRequest("manga/" + smallObj["id"]); rq = new RestSharp.RestRequest("manga/" + smallObj["id"]);
rq.AddParameter("access_token", token); rq.AddParameter("access_token", token);
return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content)); return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(cl.Execute(rq).Content));
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine(ex.ToString()); Console.WriteLine(ex.ToString());
return null; return null;
} }
@ -82,7 +83,8 @@ namespace NadekoBot.Classes {
var exec = cl.Execute(rq); var exec = cl.Execute(rq);
token = JObject.Parse(exec.Content)["access_token"].ToString(); token = JObject.Parse(exec.Content)["access_token"].ToString();
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine($"Failed refreshing anilist token:\n {ex}"); Console.WriteLine($"Failed refreshing anilist token:\n {ex}");
} }
} }
@ -114,7 +116,8 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
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();
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine($"Error in findyoutubeurl: {ex.Message}"); Console.WriteLine($"Error in findyoutubeurl: {ex.Message}");
return string.Empty; return string.Empty;
} }
@ -132,7 +135,8 @@ namespace NadekoBot.Classes {
dynamic obj = JObject.Parse(await sr.ReadToEndAsync()); dynamic obj = JObject.Parse(await sr.ReadToEndAsync());
return obj.items[0].id.playlistId.ToString(); return obj.items[0].id.playlistId.ToString();
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return string.Empty; return string.Empty;
} }
@ -156,7 +160,8 @@ namespace NadekoBot.Classes {
toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId); toReturn.Add("http://www.youtube.com/watch?v=" + item.contentDetails.videoId);
} }
return toReturn; return toReturn;
} catch (Exception ex) { }
catch (Exception ex) {
Console.WriteLine($"Error in GetPlaylistId: {ex.Message}"); Console.WriteLine($"Error in GetPlaylistId: {ex.Message}");
return new List<string>(); return new List<string>();
} }
@ -174,7 +179,8 @@ namespace NadekoBot.Classes {
var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\""); var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\"");
return await $"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl(); return await $"http://danbooru.donmai.us{ matches[rng.Next(0, matches.Count)].Groups["id"].Value }".ShortenUrl();
} catch { }
catch {
return null; return null;
} }
} }
@ -190,7 +196,8 @@ namespace NadekoBot.Classes {
//now extract the image from post page //now extract the image from post page
var match = Regex.Match(webpage, "\"(?<url>http://simg4.gelbooru.com//images.*?)\""); var match = Regex.Match(webpage, "\"(?<url>http://simg4.gelbooru.com//images.*?)\"");
return match.Groups["url"].Value; return match.Groups["url"].Value;
} catch { }
catch {
return null; return null;
} }
} }
@ -201,8 +208,9 @@ namespace NadekoBot.Classes {
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 GetResponseAsync(url); // first extract the post id and go to that posts page var webpage = await GetResponseAsync(url); // first extract the post id and go to that posts page
var matches = Regex.Matches(webpage, "\"file_url\":\"(?<url>.*?)\""); var matches = Regex.Matches(webpage, "\"file_url\":\"(?<url>.*?)\"");
return matches[rng.Next(0,matches.Count)].Groups["url"].Value; return matches[rng.Next(0, matches.Count)].Groups["url"].Value;
} catch { }
catch {
return null; return null;
} }
} }
@ -225,7 +233,8 @@ namespace NadekoBot.Classes {
string MATCH_PATTERN = @"""id"": ?""(?<id>.+)"""; string MATCH_PATTERN = @"""id"": ?""(?<id>.+)""";
return Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value; return Regex.Match(responseText, MATCH_PATTERN).Groups["id"].Value;
} }
} catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; } }
catch (Exception ex) { Console.WriteLine(ex.ToString()); return url; }
} }
} }
} }

View File

@ -7,12 +7,13 @@ using Discord.Commands;
using NadekoBot.Extensions; using NadekoBot.Extensions;
using System.Collections.Generic; using System.Collections.Generic;
using NadekoBot.Classes; using NadekoBot.Classes;
using NadekoBot.Commands;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Searches : DiscordModule { class Searches : DiscordModule {
private Random _r; private Random _r;
public Searches() : base() { public Searches() : base() {
// commands.Add(new OsuCommands()); // commands.Add(new LoLCommands());
_r = new Random(); _r = new Random();
} }
@ -79,7 +80,8 @@ namespace NadekoBot.Modules {
.GetResponse() .GetResponse()
.GetResponseStream()) .GetResponseStream())
.ReadToEnd())["file"].ToString()); .ReadToEnd())["file"].ToString());
} catch { } }
catch { }
}); });
cgb.CreateCommand("~i") cgb.CreateCommand("~i")
@ -92,7 +94,8 @@ namespace NadekoBot.Modules {
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString));
await e.Send(obj["items"][0]["link"].ToString()); await e.Send(obj["items"][0]["link"].ToString());
} catch (Exception ex) { }
catch (Exception ex) {
await e.Send($"💢 {ex.Message}"); await e.Send($"💢 {ex.Message}");
} }
}); });
@ -107,7 +110,8 @@ namespace NadekoBot.Modules {
var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ _r.Next(1, 150) }&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}"; var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(e.GetArg("query"))}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ _r.Next(1, 150) }&fields=items%2Flink&key={NadekoBot.creds.GoogleAPIKey}";
var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString)); var obj = JObject.Parse(await SearchHelper.GetResponseAsync(reqString));
await e.Send(obj["items"][0]["link"].ToString()); await e.Send(obj["items"][0]["link"].ToString());
} catch (Exception ex) { }
catch (Exception ex) {
await e.Send($"💢 {ex.Message}"); await e.Send($"💢 {ex.Message}");
} }
}); });
@ -130,10 +134,9 @@ namespace NadekoBot.Modules {
return; return;
} }
await e.Channel.SendIsTyping(); await e.Channel.SendIsTyping();
var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", var headers = new WebHeaderCollection();
new Tuple<string, string>[] { headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey);
new Tuple<string, string>("X-Mashape-Key", NadekoBot.creds.MashapeKey), var res = await SearchHelper.GetResponseAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers);
});
try { try {
var items = JArray.Parse(res); var items = JArray.Parse(res);
List<System.Drawing.Image> images = new List<System.Drawing.Image>(); List<System.Drawing.Image> images = new List<System.Drawing.Image>();
@ -155,7 +158,8 @@ namespace NadekoBot.Modules {
Console.WriteLine("Start"); Console.WriteLine("Start");
await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png)); await e.Channel.SendFile(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png));
Console.WriteLine("Finish"); Console.WriteLine("Finish");
} catch (Exception ex) { }
catch (Exception ex) {
await e.Send($"💢 Error {ex.Message}"); await e.Send($"💢 Error {ex.Message}");
} }
}); });
@ -176,59 +180,83 @@ namespace NadekoBot.Modules {
try { try {
await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)); await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result));
await e.Send($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`"); await e.Send($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`");
} catch { } }
catch { }
}; };
} catch { }
catch {
await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\"); await e.Channel.SendMessage("💢 Failed retrieving osu signature :\\");
} }
} }
}); });
cgb.CreateCommand("~ud") cgb.CreateCommand("~ud")
.Description("Searches Urban Dictionary for a word\n**Usage**:~ud Pineapple") .Description("Searches Urban Dictionary for a word\n**Usage**:~ud Pineapple")
.Parameter("query", ParameterType.Unparsed) .Parameter("query", ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
var arg = e.GetArg("query"); var arg = e.GetArg("query");
if (string.IsNullOrWhiteSpace(arg)) if (string.IsNullOrWhiteSpace(arg)) {
{
await e.Send("💢 Please enter a search term."); await e.Send("💢 Please enter a search term.");
return; return;
} }
await e.Channel.SendIsTyping(); await e.Channel.SendIsTyping();
var res = await SearchHelper.GetResponseAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", var headers = new WebHeaderCollection();
new Tuple<string, string>[] { headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey);
new Tuple<string, string>("X-Mashape-Key", NadekoBot.creds.MashapeKey) var res = await SearchHelper.GetResponseAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", headers);
}); try {
try
{
var items = JObject.Parse(res); var items = JObject.Parse(res);
await e.Send($"`Term:` {items["list"][0]["word"].ToString()}\n"); var sb = new System.Text.StringBuilder();
await e.Send($"`Definition:` {items["list"][0]["definition"].ToString()}\n"); sb.AppendLine($"`Term:` {items["list"][0]["word"].ToString()}");
await e.Send($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>"); sb.AppendLine($"`Definition:` {items["list"][0]["definition"].ToString()}");
sb.Append($"`Link:` <{await items["list"][0]["permalink"].ToString().ShortenUrl()}>");
await e.Send(sb.ToString());
} }
catch (Exception ex) catch {
{ await e.Channel.SendMessage("💢 Failed finding a definition for that term.");
await e.Channel.SendMessage("💢 Exception: " + ex.Message);
} }
});
//todo when moved from parse
/*
cgb.CreateCommand("~osubind")
.Description("Bind discord user to osu name\n**Usage**: ~osubind My osu name")
.Parameter("osu_name", ParameterType.Unparsed)
.Do(async e => {
var userName = e.GetArg("user_name");
var osuName = e.GetArg("osu_name");
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) {
await e.Send("Cannot find that discord user.");
return;
}
});
*/
}); });
// thanks to Blaubeerwald
cgb.CreateCommand("~#")
.Description("Searches Tagdef.com for a hashtag\n**Usage**:~# ff")
.Parameter("query", ParameterType.Unparsed)
.Do(async e => {
var arg = e.GetArg("query");
if (string.IsNullOrWhiteSpace(arg)) {
await e.Send("💢 Please enter a search term.");
return;
}
await e.Channel.SendIsTyping();
var headers = new WebHeaderCollection();
headers.Add("X-Mashape-Key", NadekoBot.creds.MashapeKey);
var res = await SearchHelper.GetResponseAsync($"https://tagdef.p.mashape.com/one.{Uri.EscapeUriString(arg)}.json", headers);
try {
var items = JObject.Parse(res);
var sb = new System.Text.StringBuilder();
sb.AppendLine($"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}");
sb.AppendLine($"`Definition:` {items["defs"]["def"]["text"].ToString()}");
sb.Append($"`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl()}>");
await e.Send(sb.ToString());
}
catch {
await e.Channel.SendMessage("💢 Failed finidng a definition for that tag");
}
});
//todo when moved from parse
/*
cgb.CreateCommand("~osubind")
.Description("Bind discord user to osu name\n**Usage**: ~osubind My osu name")
.Parameter("osu_name", ParameterType.Unparsed)
.Do(async e => {
var userName = e.GetArg("user_name");
var osuName = e.GetArg("osu_name");
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null) {
await e.Send("Cannot find that discord user.");
return;
}
});
*/
});
} }
} }
} }