Huge amount of work done on Searches module

This commit is contained in:
Kwoth 2016-08-16 14:11:45 +02:00
parent b54f5e161d
commit b8d7eedaf7
68 changed files with 2658 additions and 2214 deletions

View File

@ -1,7 +1,4 @@
#:C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net\Discord.Net.xproj
#:C:\Users\Kwoth\Source\Repos\NadekoBot1.0\src\NadekoBot\NadekoBot.xproj
C:\Users\Kwoth\Source\Repos\NadekoBot1.0\src\NadekoBot\NadekoBot.xproj|C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net\Discord.Net.xproj
C:\Users\Kwoth\Source\Repos\NadekoBot1.0\src\NadekoBot\NadekoBot.xproj|C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj
C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj|C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net\Discord.Net.xproj
#:C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj
C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net.Commands\Discord.Net.Commands.xproj|C:\Users\Kwoth\Source\Repos\NadekoBot1.0\discord.net\src\Discord.Net\Discord.Net.xproj

View File

@ -0,0 +1,99 @@
//using Discord;
//using Discord.Commands;
//using NadekoBot.Attributes;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading.Tasks;
//// todo RestSharp
//namespace NadekoBot.Modules.Searches.Commands
//{
// public partial class SearchesModule
// {
// [LocalizedCommand, LocalizedDescription, LocalizedSummary]
// [RequireContext(ContextType.Guild)]
// public async Task Anime(IMessage imsg, [Remainder] string query)
// {
// var channel = imsg.Channel as IGuildChannel;
// if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
// string result;
// try
// {
// result = (await GetAnimeData(query).ConfigureAwait(false)).ToString();
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false);
// return;
// }
// await imsg.Channel.SendMessageAsync(result.ToString()).ConfigureAwait(false);
// }
// [LocalizedCommand, LocalizedDescription, LocalizedSummary]
// [RequireContext(ContextType.Guild)]
// public async Task Manga(IMessage imsg, [Remainder] string query)
// {
// var channel = imsg.Channel as IGuildChannel;
// if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
// string result;
// try
// {
// result = (await GetMangaData(query).ConfigureAwait(false)).ToString();
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("Failed to find that manga.").ConfigureAwait(false);
// return;
// }
// await imsg.Channel.SendMessageAsync(result).ConfigureAwait(false);
// }
// public static async Task<AnimeResult> GetAnimeData(string query)
// {
// if (string.IsNullOrWhiteSpace(query))
// throw new ArgumentNullException(nameof(query));
// await RefreshAnilistToken().ConfigureAwait(false);
// var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
// var smallContent = "";
// var cl = new RestSharp.RestClient("http://anilist.co/api");
// var rq = new RestSharp.RestRequest("/anime/search/" + Uri.EscapeUriString(query));
// rq.AddParameter("access_token", token);
// smallContent = cl.Execute(rq).Content;
// var smallObj = JArray.Parse(smallContent)[0];
// rq = new RestSharp.RestRequest("/anime/" + smallObj["id"]);
// rq.AddParameter("access_token", token);
// var content = cl.Execute(rq).Content;
// return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content)).ConfigureAwait(false);
// }
// public static async Task<MangaResult> GetMangaData(string query)
// {
// if (string.IsNullOrWhiteSpace(query))
// throw new ArgumentNullException(nameof(query));
// await RefreshAnilistToken().ConfigureAwait(false);
// var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
// var smallContent = "";
// var cl = new RestSharp.RestClient("http://anilist.co/api");
// var rq = new RestSharp.RestRequest("/manga/search/" + Uri.EscapeUriString(query));
// rq.AddParameter("access_token", token);
// smallContent = cl.Execute(rq).Content;
// var smallObj = JArray.Parse(smallContent)[0];
// rq = new RestSharp.RestRequest("/manga/" + smallObj["id"]);
// rq.AddParameter("access_token", token);
// var content = cl.Execute(rq).Content;
// return await Task.Run(() => JsonConvert.DeserializeObject<MangaResult>(content)).ConfigureAwait(false);
// }
// }
//}

View File

@ -1,171 +0,0 @@
using Discord.Commands;
using NadekoBot.Classes;
using ScaredFingers.UnitsConversion;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands
{
class ConverterCommand : DiscordCommand
{
public ConverterCommand(DiscordModule module) : base(module)
{
if (unitTables == null)
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = ci;
unitTables = new List<UnitTable>();
unitTables.Add(UnitTable.LengthTable);
unitTables.Add(UnitTable.TemperatureTable);
unitTables.Add(UnitTable.VolumeTable);
unitTables.Add(UnitTable.WeightTable);
reInitCurrencyConverterTable();
}
}
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "convert")
.Description($"Convert quantities from>to. | `{Prefix}convert m>km 1000`")
.Parameter("from-to", ParameterType.Required)
.Parameter("quantity", ParameterType.Optional)
.Do(ConvertFunc());
cgb.CreateCommand(Module.Prefix + "convertlist")
.Description("List of the convertable dimensions and currencies.")
.Do(ConvertListFunc());
}
private Func<CommandEventArgs, Task> ConvertListFunc() =>
async e =>
{
reInitCurrencyConverterTable();
string msg = "";
foreach (var tmpTable in unitTables)
{
int i = 1;
while (tmpTable.IsKnownUnit(i))
{
msg += tmpTable.GetUnitName(i) + " (" + tmpTable.GetUnitSymbol(i) + "); ";
i++;
}
msg += "\n";
}
foreach (var curr in exchangeRateProvider.Currencies)
{
msg += curr + "; ";
}
await channel.SendMessageAsync(msg).ConfigureAwait(false);
};
private Func<CommandEventArgs, Task> ConvertFunc() =>
async e =>
{
try
{
await e.Channel.SendIsTyping().ConfigureAwait(false);
string from = e.GetArg("from-to").ToLowerInvariant().Split('>')[0];
string to = e.GetArg("from-to").ToLowerInvariant().Split('>')[1];
float quantity = 1.0f;
if (!float.TryParse(e.GetArg("quantity"), out quantity))
{
quantity = 1.0f;
}
int fromCode, toCode = 0;
UnitTable table = null;
ResolveUnitCodes(from, to, out table, out fromCode, out toCode);
if (table != null)
{
Unit inUnit = new Unit(fromCode, quantity, table);
Unit outUnit = inUnit.Convert(toCode);
await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
}
else
{
CultureInfo ci = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = ci;
reInitCurrencyConverterTable();
Unit inUnit = currTable.CreateUnit(quantity, from.ToUpperInvariant());
Unit outUnit = inUnit.Convert(currTable.CurrencyCode(to.ToUpperInvariant()));
await channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
}
}
catch //(Exception ex)
{
//Console.WriteLine(ex.ToString());
await channel.SendMessageAsync("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false);
}
};
private void reInitCurrencyConverterTable()
{
if (lastChanged == null || lastChanged.DayOfYear != DateTime.Now.DayOfYear)
{
try
{
exchangeRateProvider = new WebExchangeRatesProvider();
currTable = new CurrencyExchangeTable(exchangeRateProvider);
lastChanged = DateTime.Now;
}
catch
{
Console.WriteLine("Error with the currency download.");
}
}
}
private void ResolveUnitCodes(string from, string to, out UnitTable table, out int fromCode, out int toCode)
{
foreach (var tmpTable in unitTables)
{
int f = LookupUnit(tmpTable, from);
int t = LookupUnit(tmpTable, to);
if (f > 0 && t > 0)
{
table = tmpTable;
fromCode = f;
toCode = t;
return;
}
}
table = null;
fromCode = 0;
toCode = 0;
}
private int LookupUnit(UnitTable table, string lookup)
{
string wellformedLookup = lookup.ToLowerInvariant().Replace("°", "");
int i = 1;
while (table.IsKnownUnit(i))
{
if (wellformedLookup == table.GetUnitName(i).ToLowerInvariant().Replace("°", "") ||
wellformedLookup == table.GetUnitPlural(i).ToLowerInvariant().Replace("°", "") ||
wellformedLookup == table.GetUnitSymbol(i).ToLowerInvariant().Replace("°", ""))
{
return i;
}
i++;
}
return 0;
}
private static List<UnitTable> unitTables;
private static CurrencyExchangeRatesProvider exchangeRateProvider;
private static CurrencyExchangeTable currTable;
private static DateTime lastChanged;
}
}

View File

@ -0,0 +1,171 @@
//using Discord.Commands;
//using NadekoBot.Classes;
//using ScaredFingers.UnitsConversion;
//using System;
//using System.Collections.Generic;
//using System.Globalization;
//using System.Threading;
//using System.Threading.Tasks;
//namespace NadekoBot.Modules.Searches.Commands
//{
// class ConverterCommand : DiscordCommand
// {
// public ConverterCommand(DiscordModule module) : base(module)
// {
// if (unitTables == null)
// {
// CultureInfo ci = new CultureInfo("en-US");
// Thread.CurrentThread.CurrentCulture = ci;
// unitTables = new List<UnitTable>();
// unitTables.Add(UnitTable.LengthTable);
// unitTables.Add(UnitTable.TemperatureTable);
// unitTables.Add(UnitTable.VolumeTable);
// unitTables.Add(UnitTable.WeightTable);
// reInitCurrencyConverterTable();
// }
// }
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "convert")
// .Description($"Convert quantities from>to. | `{Prefix}convert m>km 1000`")
// .Parameter("from-to", ParameterType.Required)
// .Parameter("quantity", ParameterType.Optional)
// .Do(ConvertFunc());
// cgb.CreateCommand(Module.Prefix + "convertlist")
// .Description("List of the convertable dimensions and currencies.")
// .Do(ConvertListFunc());
// }
// private Func<CommandEventArgs, Task> ConvertListFunc() =>
// async e =>
// {
// reInitCurrencyConverterTable();
// string msg = "";
// foreach (var tmpTable in unitTables)
// {
// int i = 1;
// while (tmpTable.IsKnownUnit(i))
// {
// msg += tmpTable.GetUnitName(i) + " (" + tmpTable.GetUnitSymbol(i) + "); ";
// i++;
// }
// msg += "\n";
// }
// foreach (var curr in exchangeRateProvider.Currencies)
// {
// msg += curr + "; ";
// }
// await imsg.Channel.SendMessageAsync(msg).ConfigureAwait(false);
// };
// private Func<CommandEventArgs, Task> ConvertFunc() =>
// async e =>
// {
// try
// {
// await e.Channel.SendIsTyping().ConfigureAwait(false);
// string from = e.GetArg("from-to").ToLowerInvariant().Split('>')[0];
// string to = e.GetArg("from-to").ToLowerInvariant().Split('>')[1];
// float quantity = 1.0f;
// if (!float.TryParse(e.GetArg("quantity"), out quantity))
// {
// quantity = 1.0f;
// }
// int fromCode, toCode = 0;
// UnitTable table = null;
// ResolveUnitCodes(from, to, out table, out fromCode, out toCode);
// if (table != null)
// {
// Unit inUnit = new Unit(fromCode, quantity, table);
// Unit outUnit = inUnit.Convert(toCode);
// await imsg.Channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
// }
// else
// {
// CultureInfo ci = new CultureInfo("en-US");
// Thread.CurrentThread.CurrentCulture = ci;
// reInitCurrencyConverterTable();
// Unit inUnit = currTable.CreateUnit(quantity, from.ToUpperInvariant());
// Unit outUnit = inUnit.Convert(currTable.CurrencyCode(to.ToUpperInvariant()));
// await imsg.Channel.SendMessageAsync(inUnit.ToString() + " = " + outUnit.ToString()).ConfigureAwait(false);
// }
// }
// catch //(Exception ex)
// {
// //Console.WriteLine(ex.ToString());
// await imsg.Channel.SendMessageAsync("Bad input format, or sth went wrong... Try to list them with `" + Module.Prefix + "`convertlist").ConfigureAwait(false);
// }
// };
// private void reInitCurrencyConverterTable()
// {
// if (lastChanged == null || lastChanged.DayOfYear != DateTime.Now.DayOfYear)
// {
// try
// {
// exchangeRateProvider = new WebExchangeRatesProvider();
// currTable = new CurrencyExchangeTable(exchangeRateProvider);
// lastChanged = DateTime.Now;
// }
// catch
// {
// Console.WriteLine("Error with the currency download.");
// }
// }
// }
// private void ResolveUnitCodes(string from, string to, out UnitTable table, out int fromCode, out int toCode)
// {
// foreach (var tmpTable in unitTables)
// {
// int f = LookupUnit(tmpTable, from);
// int t = LookupUnit(tmpTable, to);
// if (f > 0 && t > 0)
// {
// table = tmpTable;
// fromCode = f;
// toCode = t;
// return;
// }
// }
// table = null;
// fromCode = 0;
// toCode = 0;
// }
// private int LookupUnit(UnitTable table, string lookup)
// {
// string wellformedLookup = lookup.ToLowerInvariant().Replace("°", "");
// int i = 1;
// while (table.IsKnownUnit(i))
// {
// if (wellformedLookup == table.GetUnitName(i).ToLowerInvariant().Replace("°", "") ||
// wellformedLookup == table.GetUnitPlural(i).ToLowerInvariant().Replace("°", "") ||
// wellformedLookup == table.GetUnitSymbol(i).ToLowerInvariant().Replace("°", ""))
// {
// return i;
// }
// i++;
// }
// return 0;
// }
// private static List<UnitTable> unitTables;
// private static CurrencyExchangeRatesProvider exchangeRateProvider;
// private static CurrencyExchangeTable currTable;
// private static DateTime lastChanged;
// }
//}

View File

@ -1,85 +1,85 @@
using Discord.Commands;
using Mathos.Parser;
using NadekoBot.Classes;
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
//using Discord.Commands;
//using Mathos.Parser;
//using NadekoBot.Classes;
//using System;
//using System.Text.RegularExpressions;
//using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands
{
class CalcCommand : DiscordCommand
{
public CalcCommand(DiscordModule module) : base(module)
{
}
//namespace NadekoBot.Modules.Searches.Commands
//{
// class CalcCommand : DiscordCommand
// {
// public CalcCommand(DiscordModule module) : base(module)
// {
// }
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "calculate")
.Alias(Module.Prefix + "calc")
.Description($"Evaluate a mathematical expression. | `{Prefix}calc 1+1`")
.Parameter("expression", ParameterType.Unparsed)
.Do(EvalFunc());
}
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "calculate")
// .Alias(Module.Prefix + "calc")
// .Description($"Evaluate a mathematical expression. | `{Prefix}calc 1+1`")
// .Parameter("expression", ParameterType.Unparsed)
// .Do(EvalFunc());
// }
private CustomParser parser = new CustomParser();
private Func<CommandEventArgs, Task> EvalFunc() => async e =>
{
string expression = e.GetArg("expression")?.Trim();
if (string.IsNullOrWhiteSpace(expression))
{
return;
}
string answer = Evaluate(expression);
if (answer == null)
{
await channel.SendMessageAsync($"Expression {expression} failed to evaluate");
return;
}
await channel.SendMessageAsync($"⚙ `{answer}`");
};
// private CustomParser parser = new CustomParser();
// private Func<CommandEventArgs, Task> EvalFunc() => async e =>
// {
// string expression = e.GetArg("expression")?.Trim();
// if (string.IsNullOrWhiteSpace(expression))
// {
// return;
// }
// string answer = Evaluate(expression);
// if (answer == null)
// {
// await imsg.Channel.SendMessageAsync($"Expression {expression} failed to evaluate");
// return;
// }
// await imsg.Channel.SendMessageAsync($"⚙ `{answer}`");
// };
private string Evaluate(string expression)
{
//check for factorial
expression = Regex.Replace(expression, @"\d+!", x => x.Value + "0");
try
{
string result = parser.Parse(expression).ToString();
return result;
}
catch (OverflowException)
{
return $"Overflow error on {expression}";
}
catch (FormatException)
{
return $"\"{expression}\" was not formatted correctly";
}
}
// private string Evaluate(string expression)
// {
// //check for factorial
// expression = Regex.Replace(expression, @"\d+!", x => x.Value + "0");
// try
// {
// string result = parser.Parse(expression).ToString();
// return result;
// }
// catch (OverflowException)
// {
// return $"Overflow error on {expression}";
// }
// catch (FormatException)
// {
// return $"\"{expression}\" was not formatted correctly";
// }
// }
class CustomParser : MathParser
{
public CustomParser() : base()
{
OperatorList.Add("!");
OperatorAction.Add("!", (x, y) => Factorial(x));
}
// class CustomParser : MathParser
// {
// public CustomParser() : base()
// {
// OperatorList.Add("!");
// OperatorAction.Add("!", (x, y) => Factorial(x));
// }
static decimal Factorial(decimal x)
{
decimal y = x - 1;
while (y > 0)
{
x = x * y--;
}
return x;
}
}
// static decimal Factorial(decimal x)
// {
// decimal y = x - 1;
// while (y > 0)
// {
// x = x * y--;
// }
// return x;
// }
// }
}
}
// }
//}

View File

@ -1,6 +1,6 @@
using NadekoBot.Extensions;
using System.Collections.Generic;
using System.Web;
using System.Net;
namespace NadekoBot.Modules.Searches.Commands.IMDB
{
@ -15,48 +15,18 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
public string Plot { get; set; }
public string Poster { get; set; }
public List<string> Genres { get; set; }
//public ArrayList Directors { get; set; }
//public ArrayList Writers { get; set; }
//public ArrayList Cast { get; set; }
//public ArrayList Producers { get; set; }
//public ArrayList Musicians { get; set; }
//public ArrayList Cinematographers { get; set; }
//public ArrayList Editors { get; set; }
//public string MpaaRating { get; set; }
//public string ReleaseDate { get; set; }
//public ArrayList PlotKeywords { get; set; }
//public string PosterLarge { get; set; }
//public string PosterFull { get; set; }
//public string Runtime { get; set; }
//public string Top250 { get; set; }
//public string Oscars { get; set; }
//public string Awards { get; set; }
//public string Nominations { get; set; }
//public string Storyline { get; set; }
//public string Tagline { get; set; }
//public string Votes { get; set; }
//public ArrayList Languages { get; set; }
//public ArrayList Countries { get; set; }
//public Dictionary<string, string> ReleaseDates { get; set; }
//public ArrayList MediaImages { get; set; }
//public ArrayList RecommendedTitles { get; set; }
public string ImdbURL { get; set; }
public Dictionary<string, string> Aka { get; set; }
public override string ToString() =>
$@"`Title:` {HttpUtility.HtmlDecode(Title)} {(string.IsNullOrEmpty(OriginalTitle) ? "" : $"({OriginalTitle})")}
$@"`Title:` {WebUtility.HtmlDecode(Title)} {(string.IsNullOrEmpty(OriginalTitle) ? "" : $"({OriginalTitle})")}
`Year:` {Year}
`Rating:` {Rating}
`Genre:` {GenresAsString}
`Link:` <{ImdbURL}>
`Plot:` {System.Net.WebUtility.HtmlDecode(Plot.TrimTo(500))}
`img:` " + Poster.ShortenUrl().Result;
//public string EnglishTitle => Aka.ContainsKey("USA") ? Aka["USA"] :
// (Aka.ContainsKey("UK") ? Aka["UK"] :
// (Aka.ContainsKey("(original title)") ? Aka["(original title)"] :
// (Aka.ContainsKey("(original)") ? Aka["(original)"] : OriginalTitle)));
public string GenresAsString =>
string.Join(", ", Genres);
}

View File

@ -4,8 +4,10 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
/*******************************************************************************
* Free ASP.net IMDb Scraper API for the new IMDb Template.
@ -24,57 +26,48 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
{
//Search Engine URLs
private static string GoogleSearch = "https://www.google.com/search?q=imdb+";
private static string BingSearch = "http://www.bing.com/search?q=imdb+";
private static string AskSearch = "http://www.ask.com/web?q=imdb+";
//Constructor
public static ImdbMovie ImdbScrape(string MovieName, bool GetExtraInfo = true)
public static async Task<ImdbMovie> ImdbScrape(string MovieName, bool GetExtraInfo = true)
{
ImdbMovie mov = new ImdbMovie();
string imdbUrl = GetIMDbUrl(System.Uri.EscapeUriString(MovieName));
string imdbUrl = await GetIMDbUrlAsync(System.Uri.EscapeUriString(MovieName));
mov.Status = false;
if (!string.IsNullOrWhiteSpace(imdbUrl))
{
ParseIMDbPage(imdbUrl, GetExtraInfo, mov);
await ParseIMDbPage(imdbUrl, GetExtraInfo, mov);
}
return mov;
}
public static ImdbMovie ImdbScrapeFromId(string imdbId, bool GetExtraInfo = true)
public static async Task<ImdbMovie> ImdbScrapeFromId(string imdbId, bool GetExtraInfo = true)
{
ImdbMovie mov = new ImdbMovie();
string imdbUrl = "http://www.imdb.com/title/" + imdbId + "/";
mov.Status = false;
ParseIMDbPage(imdbUrl, GetExtraInfo, mov);
await ParseIMDbPage(imdbUrl, GetExtraInfo, mov);
return mov;
}
public static string GetIMDBId(string MovieName)
public static async Task<string> GetIMDBId(string MovieName)
{
string imdbUrl = GetIMDbUrl(System.Uri.EscapeUriString(MovieName));
string imdbUrl = await GetIMDbUrlAsync(System.Uri.EscapeUriString(MovieName));
return match(@"http://www.imdb.com/title/(tt\d{7})", imdbUrl);
}
//Get IMDb URL from search results
private static string GetIMDbUrl(string MovieName, string searchEngine = "google")
private static async Task<string> GetIMDbUrlAsync(string MovieName)
{
string url = GoogleSearch + MovieName; //default to Google search
if (searchEngine.ToLower().Equals("bing")) url = BingSearch + MovieName;
if (searchEngine.ToLower().Equals("ask")) url = AskSearch + MovieName;
string html = GetUrlData(url);
ArrayList imdbUrls = MatchAll(@"<a href=""(http://www.imdb.com/title/tt\d{7}/)"".*?>.*?</a>", html);
string url = GoogleSearch + MovieName;
string html = await GetUrlDataAsync(url);
List<string> imdbUrls = MatchAll(@"<a href=""(http://www.imdb.com/title/tt\d{7}/)"".*?>.*?</a>", html);
if (imdbUrls.Count > 0)
return (string)imdbUrls[0]; //return first IMDb result
else if (searchEngine.ToLower().Equals("google")) //if Google search fails
return GetIMDbUrl(MovieName, "bing"); //search using Bing
else if (searchEngine.ToLower().Equals("bing")) //if Bing search fails
return GetIMDbUrl(MovieName, "ask"); //search using Ask
else //search fails
return string.Empty;
return (string)imdbUrls[0];
else return String.Empty;
}
//Parse IMDb page data
private static void ParseIMDbPage(string imdbUrl, bool GetExtraInfo, ImdbMovie mov)
private static async Task ParseIMDbPage(string imdbUrl, bool GetExtraInfo, ImdbMovie mov)
{
string html = GetUrlData(imdbUrl + "combined");
string html = await GetUrlDataAsync(imdbUrl + "combined");
mov.Id = match(@"<link rel=""canonical"" href=""http://www.imdb.com/title/(tt\d{7})/combined"" />", html);
if (!string.IsNullOrEmpty(mov.Id))
{
@ -85,55 +78,28 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
mov.Rating = match(@"<b>(\d.\d)/10</b>", html);
mov.Genres = MatchAll(@"<a.*?>(.*?)</a>", match(@"Genre.?:(.*?)(</div>|See more)", html)).Cast<string>().ToList();
mov.Plot = match(@"Plot:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", html);
//mov.Directors = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Directed by</a></h5>(.*?)</table>", html));
//mov.Writers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Writing credits</a></h5>(.*?)</table>", html));
//mov.Producers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Produced by</a></h5>(.*?)</table>", html));
//mov.Musicians = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Original Music by</a></h5>(.*?)</table>", html));
//mov.Cinematographers = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Cinematography by</a></h5>(.*?)</table>", html));
//mov.Editors = matchAll(@"<td valign=""top""><a.*?href=""/name/.*?/"">(.*?)</a>", match(@"Film Editing by</a></h5>(.*?)</table>", html));
//mov.Cast = matchAll(@"<td class=""nm""><a.*?href=""/name/.*?/"".*?>(.*?)</a>", match(@"<h3>Cast</h3>(.*?)</table>", html));
//mov.PlotKeywords = matchAll(@"<a.*?>(.*?)</a>", match(@"Plot Keywords:</h5>.*?<div class=""info-content"">(.*?)</div", html));
//mov.ReleaseDate = match(@"Release Date:</h5>.*?<div class=""info-content"">.*?(\d{1,2} (January|February|March|April|May|June|July|August|September|October|November|December) (19|20)\d{2})", html);
//mov.Runtime = match(@"Runtime:</h5><div class=""info-content"">(\d{1,4}) min[\s]*.*?</div>", html);
//mov.Top250 = match(@"Top 250: #(\d{1,3})<", html);
//mov.Oscars = match(@"Won (\d+) Oscars?\.", html);
//if (string.IsNullOrEmpty(mov.Oscars) && "Won Oscar.".Equals(match(@"(Won Oscar\.)", html))) mov.Oscars = "1";
//mov.Awards = match(@"(\d{1,4}) wins", html);
//mov.Nominations = match(@"(\d{1,4}) nominations", html);
//mov.Tagline = match(@"Tagline:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", html);
//mov.MpaaRating = match(@"MPAA</a>:</h5><div class=""info-content"">Rated (G|PG|PG-13|PG-14|R|NC-17|X) ", html);
//mov.Votes = match(@">(\d+,?\d*) votes<", html);
//mov.Languages = matchAll(@"<a.*?>(.*?)</a>", match(@"Language.?:(.*?)(</div>|>.?and )", html));
//mov.Countries = matchAll(@"<a.*?>(.*?)</a>", match(@"Country:(.*?)(</div>|>.?and )", html));
mov.Poster = match(@"<div class=""photo"">.*?<a name=""poster"".*?><img.*?src=""(.*?)"".*?</div>", html);
if (!string.IsNullOrEmpty(mov.Poster) && mov.Poster.IndexOf("media-imdb.com") > 0)
{
mov.Poster = Regex.Replace(mov.Poster, @"_V1.*?.jpg", "_V1._SY200.jpg");
//mov.PosterLarge = Regex.Replace(mov.Poster, @"_V1.*?.jpg", "_V1._SY500.jpg");
//mov.PosterFull = Regex.Replace(mov.Poster, @"_V1.*?.jpg", "_V1._SY0.jpg");
}
else
{
mov.Poster = string.Empty;
//mov.PosterLarge = string.Empty;
//mov.PosterFull = string.Empty;
}
mov.ImdbURL = "http://www.imdb.com/title/" + mov.Id + "/";
if (GetExtraInfo)
{
string plotHtml = GetUrlData(imdbUrl + "plotsummary");
//mov.Storyline = match(@"<p class=""plotpar"">(.*?)(<i>|</p>)", plotHtml);
GetReleaseDatesAndAka(mov);
//mov.MediaImages = getMediaImages(mov);
//mov.RecommendedTitles = getRecommendedTitles(mov);
string plotHtml = await GetUrlDataAsync(imdbUrl + "plotsummary");
await GetReleaseDatesAndAka(mov);
}
}
}
//Get all release dates and aka-s
private static void GetReleaseDatesAndAka(ImdbMovie mov)
private static async Task GetReleaseDatesAndAka(ImdbMovie mov)
{
Dictionary<string, string> release = new Dictionary<string, string>();
string releasehtml = GetUrlData("http://www.imdb.com/title/" + mov.Id + "/releaseinfo");
string releasehtml = await GetUrlDataAsync("http://www.imdb.com/title/" + mov.Id + "/releaseinfo");
foreach (string r in MatchAll(@"<tr class="".*?"">(.*?)</tr>", match(@"<table id=""release_dates"" class=""subpage_data spFirst"">\n*?(.*?)</table>", releasehtml)))
{
Match rd = new Regex(@"<td>(.*?)</td>\n*?.*?<td class=.*?>(.*?)</td>", RegexOptions.Multiline).Match(r);
@ -142,7 +108,7 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
//mov.ReleaseDates = release;
Dictionary<string, string> aka = new Dictionary<string, string>();
ArrayList list = MatchAll(@".*?<tr class="".*?"">(.*?)</tr>", match(@"<table id=""akas"" class=.*?>\n*?(.*?)</table>", releasehtml));
List<string> list = MatchAll(@".*?<tr class="".*?"">(.*?)</tr>", match(@"<table id=""akas"" class=.*?>\n*?(.*?)</table>", releasehtml));
foreach (string r in list)
{
Match rd = new Regex(@"\n*?.*?<td>(.*?)</td>\n*?.*?<td>(.*?)</td>", RegexOptions.Multiline).Match(r);
@ -154,15 +120,15 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
}
//Get all media images
private static ArrayList GetMediaImages(ImdbMovie mov)
private static async Task<List<string>> GetMediaImages(ImdbMovie mov)
{
ArrayList list = new ArrayList();
List<string> list = new List<string>();
string mediaurl = "http://www.imdb.com/title/" + mov.Id + "/mediaindex";
string mediahtml = GetUrlData(mediaurl);
string mediahtml = await GetUrlDataAsync(mediaurl);
int pagecount = MatchAll(@"<a href=""\?page=(.*?)"">", match(@"<span style=""padding: 0 1em;"">(.*?)</span>", mediahtml)).Count;
for (int p = 1; p <= pagecount + 1; p++)
{
mediahtml = GetUrlData(mediaurl + "?page=" + p);
mediahtml = await GetUrlDataAsync(mediaurl + "?page=" + p);
foreach (Match m in new Regex(@"src=""(.*?)""", RegexOptions.Multiline).Matches(match(@"<div class=""thumb_list"" style=""font-size: 0px;"">(.*?)</div>", mediahtml)))
{
String image = m.Groups[1].Value;
@ -172,15 +138,15 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
return list;
}
//Get Recommended Titles
private static ArrayList GetRecommendedTitles(ImdbMovie mov)
private static async Task<List<string>> GetRecommendedTitlesAsync(ImdbMovie mov)
{
ArrayList list = new ArrayList();
List<string> list = new List<string>();
string recUrl = "http://www.imdb.com/widget/recommendations/_ajax/get_more_recs?specs=p13nsims%3A" + mov.Id;
string json = GetUrlData(recUrl);
string json = await GetUrlDataAsync(recUrl);
list = MatchAll(@"title=\\""(.*?)\\""", json);
HashSet<String> set = new HashSet<string>();
foreach (String rec in list) set.Add(rec);
return new ArrayList(set.ToList());
return new List<string>(set.ToList());
}
/*******************************[ Helper Methods ]********************************/
//Match single instance
@ -188,10 +154,10 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
{
return new Regex(regex, RegexOptions.Multiline).Match(html).Groups[i].Value.Trim();
}
//Match all instances and return as ArrayList
private static ArrayList MatchAll(string regex, string html, int i = 1)
//Match all instances and return as List<string>
private static List<string> MatchAll(string regex, string html, int i = 1)
{
ArrayList list = new ArrayList();
List<string> list = new List<string>();
foreach (Match m in new Regex(regex, RegexOptions.Multiline).Matches(html))
list.Add(m.Groups[i].Value.Trim());
return list;
@ -202,22 +168,13 @@ namespace NadekoBot.Modules.Searches.Commands.IMDB
return Regex.Replace(inputString, @"<.*?>", string.Empty);
}
//Get URL Data
private static string GetUrlData(string url)
private static Task<string> GetUrlDataAsync(string url)
{
WebClient client = new WebClient();
Random r = new Random();
//Random IP Address
//client.Headers["X-Forwarded-For"] = r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255) + "." + r.Next(0, 255);
//Random User-Agent
client.Headers["User-Agent"] = "Mozilla/" + r.Next(3, 5) + ".0 (Windows NT " + r.Next(3, 5) + "." + r.Next(0, 2) + "; rv:37.0) Gecko/20100101 Firefox/" + r.Next(30, 37) + "." + r.Next(0, 5);
Stream datastream = client.OpenRead(url);
StreamReader reader = new StreamReader(datastream);
StringBuilder sb = new StringBuilder();
//TODO: Coud be reader error must catch and drop!!!
while (!reader.EndOfStream)
sb.Append(reader.ReadLine());
return sb.ToString();
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.202 Safari/535.1");
return http.GetStringAsync(url);
}
}
}
}

View File

@ -0,0 +1,91 @@
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Modules.Searches.Commands.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands
{
public partial class SearchesModule
{
[Group]
public class JokeCommands
{
//todo DB
private List<WoWJoke> wowJokes;
private List<MagicItem> magicItems;
public JokeCommands()
{
wowJokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json"));
magicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json"));
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Yomama(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://api.yomomma.info/").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Randjoke(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ChuckNorris(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task WowJoke(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
if (!wowJokes.Any())
{
}
await imsg.Channel.SendMessageAsync(wowJokes[new Random().Next(0, wowJokes.Count)].ToString());
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task MagicItem(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
var rng = new Random();
var item = magicItems[rng.Next(0, magicItems.Count)].ToString();
await imsg.Channel.SendMessageAsync(item).ConfigureAwait(false);
}
}
}
}

View File

@ -1,383 +1,384 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Extensions;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//using Discord.Commands;
//using NadekoBot.Classes;
//using NadekoBot.Extensions;
//using Newtonsoft.Json.Linq;
//using System;
//using System.Collections.Generic;
//using System.Drawing;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands
{
internal class LoLCommands : DiscordCommand
{
////todo drawing
//namespace NadekoBot.Modules.Searches.Commands
//{
// internal class LoLCommands : DiscordCommand
// {
private class CachedChampion
{
public System.IO.Stream ImageStream { get; set; }
public DateTime AddedAt { get; set; }
public string Name { get; set; }
}
// private class CachedChampion
// {
// public System.IO.Stream ImageStream { get; set; }
// public DateTime AddedAt { get; set; }
// public string Name { get; set; }
// }
private class ChampionNameComparer : IEqualityComparer<JToken>
{
public bool Equals(JToken a, JToken b) => a["name"].ToString() == b["name"].ToString();
// private class ChampionNameComparer : IEqualityComparer<JToken>
// {
// public bool Equals(JToken a, JToken b) => a["name"].ToString() == b["name"].ToString();
public int GetHashCode(JToken obj) =>
obj["name"].GetHashCode();
}
// public int GetHashCode(JToken obj) =>
// obj["name"].GetHashCode();
// }
private static Dictionary<string, CachedChampion> CachedChampionImages = new Dictionary<string, CachedChampion>();
// private static Dictionary<string, CachedChampion> CachedChampionImages = new Dictionary<string, CachedChampion>();
private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer();
public LoLCommands(DiscordModule module) : base(module)
{
clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds;
clearTimer.Start();
clearTimer.Elapsed += (s, e) =>
{
try
{
CachedChampionImages = CachedChampionImages
.Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0))
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
catch { }
};
}
// private System.Timers.Timer clearTimer { get; } = new System.Timers.Timer();
// public LoLCommands(DiscordModule module) : base(module)
// {
// clearTimer.Interval = new TimeSpan(0, 10, 0).TotalMilliseconds;
// clearTimer.Start();
// clearTimer.Elapsed += (s, e) =>
// {
// try
// {
// CachedChampionImages = CachedChampionImages
// .Where(kvp => DateTime.Now - kvp.Value.AddedAt > new TimeSpan(1, 0, 0))
// .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
// }
// catch { }
// };
// }
private readonly string[] trashTalk = { "Better ban your counters. You are going to carry the game anyway.",
"Go with the flow. Don't think. Just ban one of these.",
"DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
"Ask your teammates what would they like to play, and ban that.",
"If you consider playing teemo, do it. If you consider teemo, you deserve him.",
"Doesn't matter what you ban really. Enemy will ban your main and you will lose." };
// private readonly string[] trashTalk = { "Better ban your counters. You are going to carry the game anyway.",
// "Go with the flow. Don't think. Just ban one of these.",
// "DONT READ BELOW! Ban Urgot mid OP 100%. Im smurf Diamond 1.",
// "Ask your teammates what would they like to play, and ban that.",
// "If you consider playing teemo, do it. If you consider teemo, you deserve him.",
// "Doesn't matter what you ban really. Enemy will ban your main and you will lose." };
public Func<CommandEventArgs, Task> DoFunc()
{
throw new NotImplementedException();
}
// public Func<CommandEventArgs, Task> DoFunc()
// {
// throw new NotImplementedException();
// }
private class MatchupModel
{
public int Games { get; set; }
public float WinRate { get; set; }
[Newtonsoft.Json.JsonProperty("key")]
public string Name { get; set; }
public float StatScore { get; set; }
}
// private class MatchupModel
// {
// public int Games { get; set; }
// public float WinRate { get; set; }
// [Newtonsoft.Json.JsonProperty("key")]
// public string Name { get; set; }
// public float StatScore { get; set; }
// }
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "lolchamp")
.Description($"Shows League Of Legends champion statistics. If there are spaces/apostrophes or in the name - omit them. Optional second parameter is a role. |`{Prefix}lolchamp Riven` or `{Prefix}lolchamp Annie sup`")
.Parameter("champ", ParameterType.Required)
.Parameter("position", ParameterType.Unparsed)
.Do(async e =>
{
try
{
//get role
var role = ResolvePos(e.GetArg("position"));
var resolvedRole = role;
var name = e.GetArg("champ").Replace(" ", "").ToLower();
CachedChampion champ = null;
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "lolchamp")
// .Description($"Shows League Of Legends champion statistics. If there are spaces/apostrophes or in the name - omit them. Optional second parameter is a role. |`{Prefix}lolchamp Riven` or `{Prefix}lolchamp Annie sup`")
// .Parameter("champ", ParameterType.Required)
// .Parameter("position", ParameterType.Unparsed)
// .Do(async e =>
// {
// try
// {
// //get role
// var role = ResolvePos(e.GetArg("position"));
// var resolvedRole = role;
// var name = e.GetArg("champ").Replace(" ", "").ToLower();
// CachedChampion champ = null;
if(CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ))
if (champ != null)
{
champ.ImageStream.Position = 0;
await e.Channel.SendFile("champ.png", champ.ImageStream).ConfigureAwait(false);
return;
}
var allData = JArray.Parse(await Classes.http.GetStringAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}").ConfigureAwait(false));
JToken data = null;
if (role != null)
{
for (var i = 0; i < allData.Count; i++)
{
if (allData[i]["role"].ToString().Equals(role))
{
data = allData[i];
break;
}
}
if (data == null)
{
await channel.SendMessageAsync("💢 Data for that role does not exist.").ConfigureAwait(false);
return;
}
}
else
{
data = allData[0];
role = allData[0]["role"].ToString();
resolvedRole = ResolvePos(role);
}
if(CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ))
if (champ != null)
{
champ.ImageStream.Position = 0;
await e.Channel.SendFile("champ.png", champ.ImageStream).ConfigureAwait(false);
return;
}
//name = data["title"].ToString();
// get all possible roles, and "select" the shown one
var roles = new string[allData.Count];
for (var i = 0; i < allData.Count; i++)
{
roles[i] = allData[i]["role"].ToString();
if (roles[i] == role)
roles[i] = ">" + roles[i] + "<";
}
var general = JArray.Parse(await http.GetStringAsync($"http://api.champion.gg/stats/" +
$"champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")
.ConfigureAwait(false))
.FirstOrDefault(jt => jt["role"].ToString() == role)?["general"];
if (general == null)
{
Console.WriteLine("General is null.");
return;
}
//get build data for this role
var buildData = data["items"]["mostGames"]["items"];
var items = new string[6];
for (var i = 0; i < 6; i++)
{
items[i] = buildData[i]["id"].ToString();
}
// if(CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ))
// if (champ != null)
// {
// champ.ImageStream.Position = 0;
// await e.Channel.SendFile("champ.png", champ.ImageStream).ConfigureAwait(false);
// return;
// }
// var allData = JArray.Parse(await Classes.http.GetStringAsync($"http://api.champion.gg/champion/{name}?api_key={NadekoBot.Creds.LOLAPIKey}").ConfigureAwait(false));
// JToken data = null;
// if (role != null)
// {
// for (var i = 0; i < allData.Count; i++)
// {
// if (allData[i]["role"].ToString().Equals(role))
// {
// data = allData[i];
// break;
// }
// }
// if (data == null)
// {
// await imsg.Channel.SendMessageAsync("💢 Data for that role does not exist.").ConfigureAwait(false);
// return;
// }
// }
// else
// {
// data = allData[0];
// role = allData[0]["role"].ToString();
// resolvedRole = ResolvePos(role);
// }
// if(CachedChampionImages.TryGetValue(name + "_" + resolvedRole, out champ))
// if (champ != null)
// {
// champ.ImageStream.Position = 0;
// await e.Channel.SendFile("champ.png", champ.ImageStream).ConfigureAwait(false);
// return;
// }
// //name = data["title"].ToString();
// // get all possible roles, and "select" the shown one
// var roles = new string[allData.Count];
// for (var i = 0; i < allData.Count; i++)
// {
// roles[i] = allData[i]["role"].ToString();
// if (roles[i] == role)
// roles[i] = ">" + roles[i] + "<";
// }
// var general = JArray.Parse(await http.GetStringAsync($"http://api.champion.gg/stats/" +
// $"champs/{name}?api_key={NadekoBot.Creds.LOLAPIKey}")
// .ConfigureAwait(false))
// .FirstOrDefault(jt => jt["role"].ToString() == role)?["general"];
// if (general == null)
// {
// Console.WriteLine("General is null.");
// return;
// }
// //get build data for this role
// var buildData = data["items"]["mostGames"]["items"];
// var items = new string[6];
// for (var i = 0; i < 6; i++)
// {
// items[i] = buildData[i]["id"].ToString();
// }
//get matchup data to show counters and countered champions
var matchupDataIE = data["matchups"].ToObject<List<MatchupModel>>();
// //get matchup data to show counters and countered champions
// var matchupDataIE = data["matchups"].ToObject<List<MatchupModel>>();
var matchupData = matchupDataIE.OrderBy(m => m.StatScore).ToArray();
// var matchupData = matchupDataIE.OrderBy(m => m.StatScore).ToArray();
var countered = new[] { matchupData[0].Name, matchupData[1].Name, matchupData[2].Name };
var counters = new[] { matchupData[matchupData.Length - 1].Name, matchupData[matchupData.Length - 2].Name, matchupData[matchupData.Length - 3].Name };
// var countered = new[] { matchupData[0].Name, matchupData[1].Name, matchupData[2].Name };
// var counters = new[] { matchupData[matchupData.Length - 1].Name, matchupData[matchupData.Length - 2].Name, matchupData[matchupData.Length - 3].Name };
//get runes data
var runesJArray = data["runes"]["mostGames"]["runes"] as JArray;
var runes = string.Join("\n", runesJArray.OrderBy(jt => int.Parse(jt["number"].ToString())).Select(jt => jt["number"].ToString() + "x" + jt["name"]));
// //get runes data
// var runesJArray = data["runes"]["mostGames"]["runes"] as JArray;
// var runes = string.Join("\n", runesJArray.OrderBy(jt => int.Parse(jt["number"].ToString())).Select(jt => jt["number"].ToString() + "x" + jt["name"]));
// get masteries data
// // get masteries data
var masteries = (data["masteries"]["mostGames"]["masteries"] as JArray);
// var masteries = (data["masteries"]["mostGames"]["masteries"] as JArray);
//get skill order data<API_KEY>
// //get skill order data<API_KEY>
var orderArr = (data["skills"]["mostGames"]["order"] as JArray);
// var orderArr = (data["skills"]["mostGames"]["order"] as JArray);
var img = Image.FromFile("data/lol/bg.png");
using (var g = Graphics.FromImage(img))
{
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
const int margin = 5;
const int imageSize = 75;
var normalFont = new Font("Monaco", 8, FontStyle.Regular);
var smallFont = new Font("Monaco", 7, FontStyle.Regular);
//draw champ image
var champName = data["key"].ToString().Replace(" ", "");
// var img = Image.FromFile("data/lol/bg.png");
// using (var g = Graphics.FromImage(img))
// {
// g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
// //g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
// const int margin = 5;
// const int imageSize = 75;
// var normalFont = new Font("Monaco", 8, FontStyle.Regular);
// var smallFont = new Font("Monaco", 7, FontStyle.Regular);
// //draw champ image
// var champName = data["key"].ToString().Replace(" ", "");
g.DrawImage(GetImage(champName), new Rectangle(margin, margin, imageSize, imageSize));
//draw champ name
if (champName == "MonkeyKing")
champName = "Wukong";
g.DrawString($"{champName}", new Font("Times New Roman", 24, FontStyle.Regular), Brushes.WhiteSmoke, margin + imageSize + margin, margin);
//draw champ surname
// g.DrawImage(GetImage(champName), new Rectangle(margin, margin, imageSize, imageSize));
// //draw champ name
// if (champName == "MonkeyKing")
// champName = "Wukong";
// g.DrawString($"{champName}", new Font("Times New Roman", 24, FontStyle.Regular), Brushes.WhiteSmoke, margin + imageSize + margin, margin);
// //draw champ surname
//draw skill order
if (orderArr.Count != 0)
{
float orderFormula = 120 / orderArr.Count;
const float orderVerticalSpacing = 10;
for (var i = 0; i < orderArr.Count; i++)
{
var orderX = margin + margin + imageSize + orderFormula * i + i;
float orderY = margin + 35;
var spellName = orderArr[i].ToString().ToLowerInvariant();
// //draw skill order
// if (orderArr.Count != 0)
// {
// float orderFormula = 120 / orderArr.Count;
// const float orderVerticalSpacing = 10;
// for (var i = 0; i < orderArr.Count; i++)
// {
// var orderX = margin + margin + imageSize + orderFormula * i + i;
// float orderY = margin + 35;
// var spellName = orderArr[i].ToString().ToLowerInvariant();
switch (spellName)
{
case "w":
orderY += orderVerticalSpacing;
break;
case "e":
orderY += orderVerticalSpacing * 2;
break;
case "r":
orderY += orderVerticalSpacing * 3;
break;
default:
break;
}
// switch (spellName)
// {
// case "w":
// orderY += orderVerticalSpacing;
// break;
// case "e":
// orderY += orderVerticalSpacing * 2;
// break;
// case "r":
// orderY += orderVerticalSpacing * 3;
// break;
// default:
// break;
// }
g.DrawString(spellName.ToUpperInvariant(), new Font("Monaco", 7), Brushes.LimeGreen, orderX, orderY);
}
}
//draw roles
g.DrawString("Roles: " + string.Join(", ", roles), normalFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin);
// g.DrawString(spellName.ToUpperInvariant(), new Font("Monaco", 7), Brushes.LimeGreen, orderX, orderY);
// }
// }
// //draw roles
// g.DrawString("Roles: " + string.Join(", ", roles), normalFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin);
//draw average stats
g.DrawString(
$@" Average Stats
// //draw average stats
// g.DrawString(
//$@" Average Stats
Kills: {general["kills"]} CS: {general["minionsKilled"]}
Deaths: {general["deaths"]} Win: {general["winPercent"]}%
Assists: {general["assists"]} Ban: {general["banRate"]}%
", normalFont, Brushes.WhiteSmoke, img.Width - 150, margin);
//draw masteries
g.DrawString($"Masteries: {string.Join(" / ", masteries?.Select(jt => jt["total"]))}", normalFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 20);
//draw runes
g.DrawString($"{runes}", smallFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 40);
//draw counters
g.DrawString($"Best against", smallFont, Brushes.WhiteSmoke, margin, img.Height - imageSize + margin);
var smallImgSize = 50;
//Kills: {general["kills"]} CS: {general["minionsKilled"]}
//Deaths: {general["deaths"]} Win: {general["winPercent"]}%
//Assists: {general["assists"]} Ban: {general["banRate"]}%
//", normalFont, Brushes.WhiteSmoke, img.Width - 150, margin);
// //draw masteries
// g.DrawString($"Masteries: {string.Join(" / ", masteries?.Select(jt => jt["total"]))}", normalFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 20);
// //draw runes
// g.DrawString($"{runes}", smallFont, Brushes.WhiteSmoke, margin, margin + imageSize + margin + 40);
// //draw counters
// g.DrawString($"Best against", smallFont, Brushes.WhiteSmoke, margin, img.Height - imageSize + margin);
// var smallImgSize = 50;
for (var i = 0; i < counters.Length; i++)
{
g.DrawImage(GetImage(counters[i]),
new Rectangle(i * (smallImgSize + margin) + margin, img.Height - smallImgSize - margin,
smallImgSize,
smallImgSize));
}
//draw countered by
g.DrawString($"Worst against", smallFont, Brushes.WhiteSmoke, img.Width - 3 * (smallImgSize + margin), img.Height - imageSize + margin);
// for (var i = 0; i < counters.Length; i++)
// {
// g.DrawImage(GetImage(counters[i]),
// new Rectangle(i * (smallImgSize + margin) + margin, img.Height - smallImgSize - margin,
// smallImgSize,
// smallImgSize));
// }
// //draw countered by
// g.DrawString($"Worst against", smallFont, Brushes.WhiteSmoke, img.Width - 3 * (smallImgSize + margin), img.Height - imageSize + margin);
for (var i = 0; i < countered.Length; i++)
{
var j = countered.Length - i;
g.DrawImage(GetImage(countered[i]),
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), img.Height - smallImgSize - margin,
smallImgSize,
smallImgSize));
}
//draw item build
g.DrawString("Popular build", normalFont, Brushes.WhiteSmoke, img.Width - (3 * (smallImgSize + margin) + margin), 77);
// for (var i = 0; i < countered.Length; i++)
// {
// var j = countered.Length - i;
// g.DrawImage(GetImage(countered[i]),
// new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), img.Height - smallImgSize - margin,
// smallImgSize,
// smallImgSize));
// }
// //draw item build
// g.DrawString("Popular build", normalFont, Brushes.WhiteSmoke, img.Width - (3 * (smallImgSize + margin) + margin), 77);
for (var i = 0; i < 6; i++)
{
var inverseI = 5 - i;
var j = inverseI % 3 + 1;
var k = inverseI / 3;
g.DrawImage(GetImage(items[i], GetImageType.Item),
new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), 92 + k * (smallImgSize + margin),
smallImgSize,
smallImgSize));
}
}
var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole };
CachedChampionImages.Add(cachedChamp.Name, cachedChamp);
await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex);
await channel.SendMessageAsync("💢 Failed retreiving data for that champion.").ConfigureAwait(false);
}
});
// for (var i = 0; i < 6; i++)
// {
// var inverseI = 5 - i;
// var j = inverseI % 3 + 1;
// var k = inverseI / 3;
// g.DrawImage(GetImage(items[i], GetImageType.Item),
// new Rectangle(img.Width - (j * (smallImgSize + margin) + margin), 92 + k * (smallImgSize + margin),
// smallImgSize,
// smallImgSize));
// }
// }
// var cachedChamp = new CachedChampion { AddedAt = DateTime.Now, ImageStream = img.ToStream(System.Drawing.Imaging.ImageFormat.Png), Name = name.ToLower() + "_" + resolvedRole };
// CachedChampionImages.Add(cachedChamp.Name, cachedChamp);
// await e.Channel.SendFile(data["title"] + "_stats.png", cachedChamp.ImageStream).ConfigureAwait(false);
// }
// catch (Exception ex)
// {
// Console.WriteLine(ex);
// await imsg.Channel.SendMessageAsync("💢 Failed retreiving data for that champion.").ConfigureAwait(false);
// }
// });
cgb.CreateCommand(Module.Prefix + "lolban")
.Description($"Shows top 6 banned champions ordered by ban rate. Ban these champions and you will be Plat 5 in no time. | `{Prefix}lolban`")
.Do(async e =>
{
// cgb.CreateCommand(Module.Prefix + "lolban")
// .Description($"Shows top 6 banned champions ordered by ban rate. Ban these champions and you will be Plat 5 in no time. | `{Prefix}lolban`")
// .Do(async e =>
// {
var showCount = 8;
//http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2
try
{
var data = JObject.Parse(
await Classes
.SearchHelper
.GetResponseStringAsync($"http://api.champion.gg/stats/champs/mostBanned?" +
$"api_key={NadekoBot.Creds.LOLAPIKey}&page=1&" +
$"limit={showCount}")
.ConfigureAwait(false))["data"] as JArray;
var dataList = data.Distinct(new ChampionNameComparer()).Take(showCount).ToList();
var sb = new StringBuilder();
sb.AppendLine($"**Showing {showCount} top banned champions.**");
sb.AppendLine($"`{trashTalk[new Random().Next(0, trashTalk.Length)]}`");
for (var i = 0; i < dataList.Count; i++)
{
if (i % 2 == 0 && i != 0)
sb.AppendLine();
sb.Append($"`{i + 1}.` **{dataList[i]["name"]}** ");
//sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)");
}
// var showCount = 8;
// //http://api.champion.gg/stats/champs/mostBanned?api_key=YOUR_API_TOKEN&page=1&limit=2
// try
// {
// var data = JObject.Parse(
// await Classes
// .SearchHelper
// .GetResponseStringAsync($"http://api.champion.gg/stats/champs/mostBanned?" +
// $"api_key={NadekoBot.Creds.LOLAPIKey}&page=1&" +
// $"limit={showCount}")
// .ConfigureAwait(false))["data"] as JArray;
// var dataList = data.Distinct(new ChampionNameComparer()).Take(showCount).ToList();
// var sb = new StringBuilder();
// sb.AppendLine($"**Showing {showCount} top banned champions.**");
// sb.AppendLine($"`{trashTalk[new Random().Next(0, trashTalk.Length)]}`");
// for (var i = 0; i < dataList.Count; i++)
// {
// if (i % 2 == 0 && i != 0)
// sb.AppendLine();
// sb.Append($"`{i + 1}.` **{dataList[i]["name"]}** ");
// //sb.AppendLine($" ({dataList[i]["general"]["banRate"]}%)");
// }
await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
}
catch (Exception)
{
await channel.SendMessageAsync($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false);
}
});
}
// await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
// }
// catch (Exception)
// {
// await imsg.Channel.SendMessageAsync($":anger: Fail: Champion.gg didsabled ban data until next patch. Sorry for the inconvenience.").ConfigureAwait(false);
// }
// });
// }
private enum GetImageType
{
Champion,
Item
}
private static Image GetImage(string id, GetImageType imageType = GetImageType.Champion)
{
try
{
switch (imageType)
{
case GetImageType.Champion:
return Image.FromFile($"data/lol/champions/{id}.png");
case GetImageType.Item:
default:
return Image.FromFile($"data/lol/items/{id}.png");
}
}
catch (Exception)
{
return Image.FromFile("data/lol/_ERROR.png");
}
}
// private enum GetImageType
// {
// Champion,
// Item
// }
// private static Image GetImage(string id, GetImageType imageType = GetImageType.Champion)
// {
// try
// {
// switch (imageType)
// {
// case GetImageType.Champion:
// return Image.FromFile($"data/lol/champions/{id}.png");
// case GetImageType.Item:
// default:
// return Image.FromFile($"data/lol/items/{id}.png");
// }
// }
// catch (Exception)
// {
// return Image.FromFile("data/lol/_ERROR.png");
// }
// }
private static string ResolvePos(string pos)
{
if (string.IsNullOrWhiteSpace(pos))
return null;
switch (pos.ToLowerInvariant())
{
case "m":
case "mid":
case "midorfeed":
case "midd":
case "middle":
return "Middle";
case "top":
case "topp":
case "t":
case "toporfeed":
return "Top";
case "j":
case "jun":
case "jungl":
case "jungle":
return "Jungle";
case "a":
case "ad":
case "adc":
case "carry":
case "ad carry":
case "adcarry":
case "c":
return "ADC";
case "s":
case "sup":
case "supp":
case "support":
return "Support";
default:
return pos;
}
}
}
}
// private static string ResolvePos(string pos)
// {
// if (string.IsNullOrWhiteSpace(pos))
// return null;
// switch (pos.ToLowerInvariant())
// {
// case "m":
// case "mid":
// case "midorfeed":
// case "midd":
// case "middle":
// return "Middle";
// case "top":
// case "topp":
// case "t":
// case "toporfeed":
// return "Top";
// case "j":
// case "jun":
// case "jungl":
// case "jungle":
// return "Jungle";
// case "a":
// case "ad":
// case "adc":
// case "carry":
// case "ad carry":
// case "adcarry":
// case "c":
// return "ADC";
// case "s":
// case "sup":
// case "supp":
// case "support":
// return "Support";
// default:
// return pos;
// }
// }
// }
//}

View File

@ -5,42 +5,44 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Discord;
using NadekoBot.Services;
using System.Threading.Tasks;
using NadekoBot.Attributes;
using System.Net.Http;
using NadekoBot.Extensions;
namespace NadekoBot.Modules.Searches.Commands
{
class MemegenCommands : DiscordCommand
public partial class SearchesModule : DiscordModule
{
public MemegenCommands(DiscordModule module) : base(module)
public SearchesModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
{
}
internal override void Init(CommandGroupBuilder cgb)
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Memelist(IMessage imsg)
{
cgb.CreateCommand(Prefix + "memelist")
.Description($"Pulls a list of memes you can use with `~memegen` from http://memegen.link/templates/ | `{Prefix}memelist`")
.Do(async e =>
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
int i = 0;
await channel.SendMessageAsync("`List Of Commands:`\n```xl\n" +
string.Join("\n", JsonConvert.DeserializeObject<Dictionary<string, string>>(await http.GetStringAsync("http://memegen.link/templates/"))
.Select(kvp => Path.GetFileName(kvp.Value))
.GroupBy(item => (i++) / 4)
.Select(ig => string.Concat(ig.Select(el => $"{el,-17}"))))
+ $"\n```").ConfigureAwait(false);
});
var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(await http.GetStringAsync("http://memegen.link/templates/"))
.Select(kvp => Path.GetFileName(kvp.Value));
cgb.CreateCommand(Prefix + "memegen")
.Description($"Generates a meme from memelist with top and bottom text. | `{Prefix}memegen biw \"gets iced coffee\" \"in the winter\"`")
.Parameter("meme", ParameterType.Required)
.Parameter("toptext", ParameterType.Required)
.Parameter("bottext", ParameterType.Required)
.Do(async e =>
await imsg.Channel.SendTableAsync(data, x => $"{x,-17}", 3);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Memegen(IMessage imsg, string meme, string topText, string botText)
{
var meme = e.GetArg("meme");
var top = Uri.EscapeDataString(e.GetArg("toptext").Replace(' ', '-'));
var bot = Uri.EscapeDataString(e.GetArg("bottext").Replace(' ', '-'));
await channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg");
});
var channel = imsg.Channel as IGuildChannel;
var top = Uri.EscapeDataString(topText.Replace(' ', '-'));
var bot = Uri.EscapeDataString(botText.Replace(' ', '-'));
await imsg.Channel.SendMessageAsync($"http://memegen.link/{meme}/{top}/{bot}.jpg");
}
}
}

View File

@ -0,0 +1,10 @@
namespace NadekoBot.Modules.Searches.Commands.Models
{
class MagicItem
{
public string Name { get; set; }
public string Description { get; set; }
public override string ToString() =>
$"✨`{Name}`\n\t*{Description}*";
}
}

View File

@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands.Models
{
public class SearchPokemon
{
public class GenderRatioClass
{
public float M { get; set; }
public float F { get; set; }
}
public class BaseStatsClass
{
public int HP { get; set; }
public int ATK { get; set; }
public int DEF { get; set; }
public int SPA { get; set; }
public int SPD { get; set; }
public int SPE { get; set; }
public override string ToString() => $@"
**HP:** {HP,-4} **ATK:** {ATK,-4} **DEF:** {DEF,-4}
**SPA:** {SPA,-4} **SPD:** {SPD,-4} **SPE:** {SPE,-4}";
}
public int Id { get; set; }
public string Species { get; set; }
public string[] Types { get; set; }
public GenderRatioClass GenderRatio { get; set; }
public BaseStatsClass BaseStats { get; set; }
public Dictionary<string, string> Abilities { get; set; }
public float HeightM { get; set; }
public float WeightKg { get; set; }
public string Color { get; set; }
public string[] Evos { get; set; }
public string[] EggGroups { get; set; }
public override string ToString() => $@"`Name:` {Species}
`Types:` {string.Join(", ", Types)}
`Stats:` {BaseStats}
`Height:` {HeightM,4}m `Weight:` {WeightKg}kg
`Abilities:` {string.Join(", ", Abilities.Values)}";
}
public class SearchPokemonAbility
{
public string Desc { get; set; }
public string Name { get; set; }
public float Rating { get; set; }
public override string ToString() => $@"`Name:` : {Name}
`Rating:` {Rating}
`Description:` {Desc}";
}
}

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands.Models
{
public class WikipediaApiModel
{
public WikipediaQuery Query { get; set; }
public class WikipediaQuery
{
public WikipediaPage[] Pages { get; set; }
public class WikipediaPage
{
public bool Missing { get; set; } = false;
public string FullUrl { get; set; }
}
}
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands.Models
{
public class WoWJoke
{
public string Question { get; set; }
public string Answer { get; set; }
public override string ToString() => $"`{Question}`\n\n**{Answer}**";
}
}

View File

@ -1,268 +1,268 @@
using Discord.Commands;
using NadekoBot.Classes;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
//using Discord.Commands;
//using NadekoBot.Classes;
//using Newtonsoft.Json.Linq;
//using System;
//using System.IO;
//using System.Net;
//using System.Text.RegularExpressions;
namespace NadekoBot.Modules.Searches.Commands
{
internal class OsuCommands : DiscordCommand
{
public OsuCommands(DiscordModule module) : base(module)
{
}
//namespace NadekoBot.Modules.Searches.Commands
//{
// internal class OsuCommands : DiscordCommand
// {
// public OsuCommands(DiscordModule module) : base(module)
// {
// }
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "osu")
.Description($"Shows osu stats for a player. | `{Prefix}osu Name` or `{Prefix}osu Name taiko`")
.Parameter("usr", ParameterType.Required)
.Parameter("mode", ParameterType.Unparsed)
.Do(async e =>
{
if (string.IsNullOrWhiteSpace(e.GetArg("usr")))
return;
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "osu")
// .Description($"Shows osu stats for a player. | `{Prefix}osu Name` or `{Prefix}osu Name taiko`")
// .Parameter("usr", ParameterType.Required)
// .Parameter("mode", ParameterType.Unparsed)
// .Do(async e =>
// {
// if (string.IsNullOrWhiteSpace(e.GetArg("usr")))
// return;
using (WebClient cl = new WebClient())
{
try
{
var m = 0;
if (!string.IsNullOrWhiteSpace(e.GetArg("mode")))
{
m = ResolveGameMode(e.GetArg("mode"));
}
// using (WebClient cl = new WebClient())
// {
// try
// {
// var m = 0;
// if (!string.IsNullOrWhiteSpace(e.GetArg("mode")))
// {
// m = ResolveGameMode(e.GetArg("mode"));
// }
cl.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
cl.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; Win64; x64)");
cl.DownloadDataAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ e.GetArg("usr") }&flagshadow&xpbar&xpbarhex&pp=2&mode={m}"));
cl.DownloadDataCompleted += async (s, cle) =>
{
try
{
await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).ConfigureAwait(false);
await channel.SendMessageAsync($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false);
}
catch { }
};
}
catch
{
await channel.SendMessageAsync("💢 Failed retrieving osu signature :\\").ConfigureAwait(false);
}
}
});
// cl.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
// cl.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (Windows NT 6.2; Win64; x64)");
// cl.DownloadDataAsync(new Uri($"http://lemmmy.pw/osusig/sig.php?uname={ e.GetArg("usr") }&flagshadow&xpbar&xpbarhex&pp=2&mode={m}"));
// cl.DownloadDataCompleted += async (s, cle) =>
// {
// try
// {
// await e.Channel.SendFile($"{e.GetArg("usr")}.png", new MemoryStream(cle.Result)).ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync($"`Profile Link:`https://osu.ppy.sh/u/{Uri.EscapeDataString(e.GetArg("usr"))}\n`Image provided by https://lemmmy.pw/osusig`").ConfigureAwait(false);
// }
// catch { }
// };
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("💢 Failed retrieving osu signature :\\").ConfigureAwait(false);
// }
// }
// });
cgb.CreateCommand(Module.Prefix + "osu b")
.Description($"Shows information about an osu beatmap. |`{Prefix}osu b` https://osu.ppy.sh/s/127712`")
.Parameter("map", ParameterType.Unparsed)
.Do(async e =>
{
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
{
await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
return;
}
// cgb.CreateCommand(Module.Prefix + "osu b")
// .Description($"Shows information about an osu beatmap. |`{Prefix}osu b` https://osu.ppy.sh/s/127712`")
// .Parameter("map", ParameterType.Unparsed)
// .Do(async e =>
// {
// if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
// {
// await imsg.Channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
// return;
// }
if (string.IsNullOrWhiteSpace(e.GetArg("map")))
return;
// if (string.IsNullOrWhiteSpace(e.GetArg("map")))
// return;
try
{
var mapId = ResolveMap(e.GetArg("map"));
var reqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&{mapId}";
var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false))[0];
var sb = new System.Text.StringBuilder();
var starRating = Math.Round(Double.Parse($"{obj["difficultyrating"]}"), 2);
var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss");
sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}");
sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}");
await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Something went wrong.");
}
});
// try
// {
// var mapId = ResolveMap(e.GetArg("map"));
// var reqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&{mapId}";
// var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false))[0];
// var sb = new System.Text.StringBuilder();
// var starRating = Math.Round(Double.Parse($"{obj["difficultyrating"]}"), 2);
// var time = TimeSpan.FromSeconds(Double.Parse($"{obj["total_length"]}")).ToString(@"mm\:ss");
// sb.AppendLine($"{obj["artist"]} - {obj["title"]}, mapped by {obj["creator"]}. https://osu.ppy.sh/s/{obj["beatmapset_id"]}");
// sb.AppendLine($"{starRating} stars, {obj["bpm"]} BPM | AR{obj["diff_approach"]}, CS{obj["diff_size"]}, OD{obj["diff_overall"]} | Length: {time}");
// await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("Something went wrong.");
// }
// });
cgb.CreateCommand(Module.Prefix + "osu top5")
.Description($"Displays a user's top 5 plays. |`{Prefix}osu top5 Name`")
.Parameter("usr", ParameterType.Required)
.Parameter("mode", ParameterType.Unparsed)
.Do(async e =>
{
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
{
await channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
return;
}
// cgb.CreateCommand(Module.Prefix + "osu top5")
// .Description($"Displays a user's top 5 plays. |`{Prefix}osu top5 Name`")
// .Parameter("usr", ParameterType.Required)
// .Parameter("mode", ParameterType.Unparsed)
// .Do(async e =>
// {
// if (string.IsNullOrWhiteSpace(NadekoBot.Creds.OsuAPIKey))
// {
// await imsg.Channel.SendMessageAsync("💢 An osu! API key is required.").ConfigureAwait(false);
// return;
// }
if (string.IsNullOrWhiteSpace(e.GetArg("usr")))
{
await channel.SendMessageAsync("💢 Please provide a username.").ConfigureAwait(false);
return;
}
// if (string.IsNullOrWhiteSpace(e.GetArg("usr")))
// {
// await imsg.Channel.SendMessageAsync("💢 Please provide a username.").ConfigureAwait(false);
// return;
// }
try
{
var m = 0;
if (!string.IsNullOrWhiteSpace(e.GetArg("mode")))
{
m = ResolveGameMode(e.GetArg("mode"));
}
// try
// {
// var m = 0;
// if (!string.IsNullOrWhiteSpace(e.GetArg("mode")))
// {
// m = ResolveGameMode(e.GetArg("mode"));
// }
var reqString = $"https://osu.ppy.sh/api/get_user_best?k={NadekoBot.Creds.OsuAPIKey}&u={Uri.EscapeDataString(e.GetArg("usr"))}&type=string&limit=5&m={m}";
var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false));
var sb = new System.Text.StringBuilder($"`Top 5 plays for {e.GetArg("usr")}:`\n```xl" + Environment.NewLine);
foreach (var item in obj)
{
var mapReqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&b={item["beatmap_id"]}";
var map = JArray.Parse(await http.GetStringAsync(mapReqString).ConfigureAwait(false))[0];
var pp = Math.Round(Double.Parse($"{item["pp"]}"), 2);
var acc = CalculateAcc(item, m);
var mods = ResolveMods(Int32.Parse($"{item["enabled_mods"]}"));
if (mods != "+")
sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | **{mods,-10}** | /b/{item["beatmap_id"]}");
else
sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}");
}
sb.Append("```");
await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Something went wrong.");
}
});
}
// var reqString = $"https://osu.ppy.sh/api/get_user_best?k={NadekoBot.Creds.OsuAPIKey}&u={Uri.EscapeDataString(e.GetArg("usr"))}&type=string&limit=5&m={m}";
// var obj = JArray.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false));
// var sb = new System.Text.StringBuilder($"`Top 5 plays for {e.GetArg("usr")}:`\n```xl" + Environment.NewLine);
// foreach (var item in obj)
// {
// var mapReqString = $"https://osu.ppy.sh/api/get_beatmaps?k={NadekoBot.Creds.OsuAPIKey}&b={item["beatmap_id"]}";
// var map = JArray.Parse(await http.GetStringAsync(mapReqString).ConfigureAwait(false))[0];
// var pp = Math.Round(Double.Parse($"{item["pp"]}"), 2);
// var acc = CalculateAcc(item, m);
// var mods = ResolveMods(Int32.Parse($"{item["enabled_mods"]}"));
// if (mods != "+")
// sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | **{mods,-10}** | /b/{item["beatmap_id"]}");
// else
// sb.AppendLine($"{pp + "pp",-7} | {acc + "%",-7} | {map["artist"] + "-" + map["title"] + " (" + map["version"],-40}) | /b/{item["beatmap_id"]}");
// }
// sb.Append("```");
// await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("Something went wrong.");
// }
// });
// }
//https://osu.ppy.sh/wiki/Accuracy
private static Double CalculateAcc(JToken play, int mode)
{
if (mode == 0)
{
var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["count300"]}") * 300;
var totalHits = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countmiss"]}");
totalHits *= 300;
return Math.Round(hitPoints / totalHits * 100, 2);
}
else if (mode == 1)
{
var hitPoints = Double.Parse($"{play["countmiss"]}") * 0 + Double.Parse($"{play["count100"]}") * 0.5 + Double.Parse($"{play["count300"]}") * 1;
var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}");
hitPoints *= 300;
totalHits *= 300;
return Math.Round(hitPoints / totalHits * 100, 2);
}
else if (mode == 2)
{
var fruitsCaught = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}");
var totalFruits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countkatu"]}");
return Math.Round(fruitsCaught / totalFruits * 100, 2);
}
else
{
var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["countkatu"]}") * 200 + (Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}")) * 300;
var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["countkatu"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}");
totalHits *= 300;
return Math.Round(hitPoints / totalHits * 100, 2);
}
}
// //https://osu.ppy.sh/wiki/Accuracy
// private static Double CalculateAcc(JToken play, int mode)
// {
// if (mode == 0)
// {
// var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["count300"]}") * 300;
// var totalHits = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countmiss"]}");
// totalHits *= 300;
// return Math.Round(hitPoints / totalHits * 100, 2);
// }
// else if (mode == 1)
// {
// var hitPoints = Double.Parse($"{play["countmiss"]}") * 0 + Double.Parse($"{play["count100"]}") * 0.5 + Double.Parse($"{play["count300"]}") * 1;
// var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}");
// hitPoints *= 300;
// totalHits *= 300;
// return Math.Round(hitPoints / totalHits * 100, 2);
// }
// else if (mode == 2)
// {
// var fruitsCaught = Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}");
// var totalFruits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countkatu"]}");
// return Math.Round(fruitsCaught / totalFruits * 100, 2);
// }
// else
// {
// var hitPoints = Double.Parse($"{play["count50"]}") * 50 + Double.Parse($"{play["count100"]}") * 100 + Double.Parse($"{play["countkatu"]}") * 200 + (Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}")) * 300;
// var totalHits = Double.Parse($"{play["countmiss"]}") + Double.Parse($"{play["count50"]}") + Double.Parse($"{play["count100"]}") + Double.Parse($"{play["countkatu"]}") + Double.Parse($"{play["count300"]}") + Double.Parse($"{play["countgeki"]}");
// totalHits *= 300;
// return Math.Round(hitPoints / totalHits * 100, 2);
// }
// }
private static string ResolveMap(string mapLink)
{
Match s = new Regex(@"osu.ppy.sh\/s\/", RegexOptions.IgnoreCase).Match(mapLink);
Match b = new Regex(@"osu.ppy.sh\/b\/", RegexOptions.IgnoreCase).Match(mapLink);
Match p = new Regex(@"osu.ppy.sh\/p\/", RegexOptions.IgnoreCase).Match(mapLink);
Match m = new Regex(@"&m=", RegexOptions.IgnoreCase).Match(mapLink);
if (s.Success)
{
var mapId = mapLink.Substring(mapLink.IndexOf("/s/") + 3);
return $"s={mapId}";
}
else if (b.Success)
{
if (m.Success)
return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("/b/") + 3))}";
else
return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3)}";
}
else if (p.Success)
{
if (m.Success)
return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("?b=") + 3))}";
else
return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3)}";
}
else
{
return $"s={mapLink}"; //just a default incase an ID number was provided by itself (non-url)?
}
}
// private static string ResolveMap(string mapLink)
// {
// Match s = new Regex(@"osu.ppy.sh\/s\/", RegexOptions.IgnoreCase).Match(mapLink);
// Match b = new Regex(@"osu.ppy.sh\/b\/", RegexOptions.IgnoreCase).Match(mapLink);
// Match p = new Regex(@"osu.ppy.sh\/p\/", RegexOptions.IgnoreCase).Match(mapLink);
// Match m = new Regex(@"&m=", RegexOptions.IgnoreCase).Match(mapLink);
// if (s.Success)
// {
// var mapId = mapLink.Substring(mapLink.IndexOf("/s/") + 3);
// return $"s={mapId}";
// }
// else if (b.Success)
// {
// if (m.Success)
// return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("/b/") + 3))}";
// else
// return $"b={mapLink.Substring(mapLink.IndexOf("/b/") + 3)}";
// }
// else if (p.Success)
// {
// if (m.Success)
// return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3, mapLink.IndexOf("&m") - (mapLink.IndexOf("?b=") + 3))}";
// else
// return $"b={mapLink.Substring(mapLink.IndexOf("?b=") + 3)}";
// }
// else
// {
// return $"s={mapLink}"; //just a default incase an ID number was provided by itself (non-url)?
// }
// }
private static int ResolveGameMode(string mode)
{
switch (mode.ToLower())
{
case "std":
case "standard":
return 0;
case "taiko":
return 1;
case "ctb":
case "catchthebeat":
return 2;
case "mania":
case "osu!mania":
return 3;
default:
return 0;
}
}
// private static int ResolveGameMode(string mode)
// {
// switch (mode.ToLower())
// {
// case "std":
// case "standard":
// return 0;
// case "taiko":
// return 1;
// case "ctb":
// case "catchthebeat":
// return 2;
// case "mania":
// case "osu!mania":
// return 3;
// default:
// return 0;
// }
// }
//https://github.com/ppy/osu-api/wiki#mods
private static string ResolveMods(int mods)
{
var modString = $"+";
// //https://github.com/ppy/osu-api/wiki#mods
// private static string ResolveMods(int mods)
// {
// var modString = $"+";
if (IsBitSet(mods, 0))
modString += "NF";
if (IsBitSet(mods, 1))
modString += "EZ";
if (IsBitSet(mods, 8))
modString += "HT";
// if (IsBitSet(mods, 0))
// modString += "NF";
// if (IsBitSet(mods, 1))
// modString += "EZ";
// if (IsBitSet(mods, 8))
// modString += "HT";
if (IsBitSet(mods, 3))
modString += "HD";
if (IsBitSet(mods, 4))
modString += "HR";
if (IsBitSet(mods, 6) && !IsBitSet(mods, 9))
modString += "DT";
if (IsBitSet(mods, 9))
modString += "NC";
if (IsBitSet(mods, 10))
modString += "FL";
// if (IsBitSet(mods, 3))
// modString += "HD";
// if (IsBitSet(mods, 4))
// modString += "HR";
// if (IsBitSet(mods, 6) && !IsBitSet(mods, 9))
// modString += "DT";
// if (IsBitSet(mods, 9))
// modString += "NC";
// if (IsBitSet(mods, 10))
// modString += "FL";
if (IsBitSet(mods, 5))
modString += "SD";
if (IsBitSet(mods, 14))
modString += "PF";
// if (IsBitSet(mods, 5))
// modString += "SD";
// if (IsBitSet(mods, 14))
// modString += "PF";
if (IsBitSet(mods, 7))
modString += "RX";
if (IsBitSet(mods, 11))
modString += "AT";
if (IsBitSet(mods, 12))
modString += "SO";
return modString;
}
// if (IsBitSet(mods, 7))
// modString += "RX";
// if (IsBitSet(mods, 11))
// modString += "AT";
// if (IsBitSet(mods, 12))
// modString += "SO";
// return modString;
// }
private static bool IsBitSet(int mods, int pos)
{
return (mods & (1 << pos)) != 0;
}
// private static bool IsBitSet(int mods, int pos)
// {
// return (mods & (1 << pos)) != 0;
// }
}
}
// }
//}

View File

@ -1,116 +1,69 @@
using Discord.Commands;
using NadekoBot.Classes;
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Modules.Searches.Commands.Models;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Searches.Commands
{
class PokemonSearchCommands : DiscordCommand
public partial class SearchesModule : DiscordModule
{
[Group]
public class PokemonSearchCommands
{
//todo DB
private static Dictionary<string, SearchPokemon> pokemons;
private static Dictionary<string, SearchPokemonAbility> pokemonAbilities;
public PokemonSearchCommands(DiscordModule module) : base(module)
public PokemonSearchCommands()
{
pokemons = JsonConvert.DeserializeObject<Dictionary<string, SearchPokemon>>(File.ReadAllText("data/pokemon/pokemon_list.json"));
pokemonAbilities = JsonConvert.DeserializeObject<Dictionary<string, SearchPokemonAbility>>(File.ReadAllText("data/pokemon/pokemon_abilities.json"));
}
internal override void Init(CommandGroupBuilder cgb)
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Pokemon(IMessage imsg, [Remainder] string pokemon)
{
cgb.CreateCommand(Prefix + "pokemon")
.Alias(Prefix + "poke")
.Description($"Searches for a pokemon. | `{Prefix}poke Sylveon`")
.Parameter("pokemon", ParameterType.Unparsed)
.Do(async e =>
{
var pok = e.GetArg("pokemon")?.Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(pok))
var channel = imsg.Channel as IGuildChannel;
pokemon = pokemon?.Trim().ToUpperInvariant();
if (string.IsNullOrWhiteSpace(pokemon))
return;
foreach (var kvp in pokemons)
{
if (kvp.Key.ToUpperInvariant() == pok.ToUpperInvariant())
if (kvp.Key.ToUpperInvariant() == pokemon.ToUpperInvariant())
{
await channel.SendMessageAsync($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}");
await imsg.Channel.SendMessageAsync($"`Stats for \"{kvp.Key}\" pokemon:`\n{kvp.Value}");
return;
}
}
await channel.SendMessageAsync("`No pokemon found.`");
});
await imsg.Channel.SendMessageAsync("`No pokemon found.`");
}
cgb.CreateCommand(Prefix + "pokemonability")
.Alias(Prefix + "pokeab")
.Description($"Searches for a pokemon ability. | `{Prefix}pokeab \"water gun\"`")
.Parameter("abil", ParameterType.Unparsed)
.Do(async e =>
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task PokemonAbility(IMessage imsg, [Remainder] string ability)
{
var ab = e.GetArg("abil")?.Trim().ToUpperInvariant().Replace(" ", "");
if (string.IsNullOrWhiteSpace(ab))
var channel = imsg.Channel as IGuildChannel;
ability = ability?.Trim().ToUpperInvariant().Replace(" ", "");
if (string.IsNullOrWhiteSpace(ability))
return;
foreach (var kvp in pokemonAbilities)
{
if (kvp.Key.ToUpperInvariant() == ab)
if (kvp.Key.ToUpperInvariant() == ability)
{
await channel.SendMessageAsync($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}");
await imsg.Channel.SendMessageAsync($"`Info for \"{kvp.Key}\" ability:`\n{kvp.Value}");
return;
}
}
await channel.SendMessageAsync("`No ability found.`");
});
await imsg.Channel.SendMessageAsync("`No ability found.`");
}
}
public class SearchPokemon
{
public class GenderRatioClass
{
public float M { get; set; }
public float F { get; set; }
}
public class BaseStatsClass
{
public int HP { get; set; }
public int ATK { get; set; }
public int DEF { get; set; }
public int SPA { get; set; }
public int SPD { get; set; }
public int SPE { get; set; }
public override string ToString() => $@"
**HP:** {HP,-4} **ATK:** {ATK,-4} **DEF:** {DEF,-4}
**SPA:** {SPA,-4} **SPD:** {SPD,-4} **SPE:** {SPE,-4}";
}
public int Id { get; set; }
public string Species { get; set; }
public string[] Types { get; set; }
public GenderRatioClass GenderRatio { get; set; }
public BaseStatsClass BaseStats { get; set; }
public Dictionary<string, string> Abilities { get; set; }
public float HeightM { get; set; }
public float WeightKg { get; set; }
public string Color { get; set; }
public string[] Evos { get; set; }
public string[] EggGroups { get; set; }
public override string ToString() => $@"`Name:` {Species}
`Types:` {string.Join(", ", Types)}
`Stats:` {BaseStats}
`Height:` {HeightM,4}m `Weight:` {WeightKg}kg
`Abilities:` {string.Join(", ", Abilities.Values)}";
}
public class SearchPokemonAbility
{
public string Desc { get; set; }
public string Name { get; set; }
public float Rating { get; set; }
public override string ToString() => $@"`Name:` : {Name}
`Rating:` {Rating}
`Description:` {Desc}";
}
}

View File

@ -1,17 +0,0 @@
using Discord.Commands;
using NadekoBot.Classes;
namespace NadekoBot.Modules.Searches.Commands
{
class RedditCommand : DiscordCommand
{
public RedditCommand(DiscordModule module) : base(module)
{
}
internal override void Init(CommandGroupBuilder cgb)
{
//throw new NotImplementedException();
}
}
}

View File

@ -0,0 +1,347 @@
//using Discord.Commands;
//using NadekoBot.Classes;
//using Newtonsoft.Json.Linq;
//using System;
//using System.Collections.Concurrent;
//using System.Linq;
//using System.Threading.Tasks;
//using Discord;
//using NadekoBot.Services;
//using System.Threading;
//namespace NadekoBot.Modules.Searches.Commands
//{
// public partial class SearchesModule : DiscordModule
// {
// [Group]
// public class StreamNotificationCommands
// {
// private readonly Timer checkTimer;
// private ConcurrentDictionary<string, Tuple<bool, string>> cachedStatuses = new ConcurrentDictionary<string, Tuple<bool, string>>();
// private bool FirstPass { get; set; } = true;
// public StreamNotifications(DiscordModule module)
// {
// checkTimer = new Timer(async (state) =>
// {
// cachedStatuses.Clear();
// try
// {
// var streams = SpecificConfigurations.Default.AllConfigs.SelectMany(c => c.ObservingStreams);
// if (!streams.Any()) return;
// foreach (var stream in streams)
// {
// Tuple<bool, string> data;
// try
// {
// data = await GetStreamStatus(stream).ConfigureAwait(false);
// }
// catch
// {
// continue;
// }
// if (data.Item1 != stream.LastStatus)
// {
// stream.LastStatus = data.Item1;
// if (FirstPass)
// continue;
// var server = NadekoBot.Client.GetServer(stream.ServerId);
// var channel = server?.GetChannel(stream.ChannelId);
// if (channel == null)
// continue;
// var msg = $"`{stream.Username}`'s stream is now " +
// $"**{(data.Item1 ? "ONLINE" : "OFFLINE")}** with " +
// $"**{data.Item2}** viewers.";
// if (stream.LastStatus)
// if (stream.Type == StreamNotificationConfig.StreamType.Hitbox)
// msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
// else if (stream.Type == StreamNotificationConfig.StreamType.Twitch)
// msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
// else if (stream.Type == StreamNotificationConfig.StreamType.Beam)
// msg += $"\n`Here is the Link:`【 http://www.beam.pro/{stream.Username}/ 】";
// else if (stream.Type == StreamNotificationConfig.StreamType.YoutubeGaming)
// msg += $"\n`Here is the Link:`【 not implemented yet - {stream.Username} 】";
// await channel.SendMessage(msg).ConfigureAwait(false);
// }
// }
// FirstPass = false;
// }
// catch { }
// }, null, TimeSpan.Zero, TimeSpan.FromSeconds(15));
// }
// public StreamNotifications(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
// {
// }
// private async Task<Tuple<bool, string>> GetStreamStatus(StreamNotificationConfig stream, bool checkCache = true)
// {
// bool isLive;
// string response;
// JObject data;
// Tuple<bool, string> result;
// switch (stream.Type)
// {
// case StreamNotificationConfig.StreamType.Hitbox:
// var hitboxUrl = $"https://api.hitbox.tv/media/status/{stream.Username}";
// if (checkCache && cachedStatuses.TryGetValue(hitboxUrl, out result))
// return result;
// response = await http.GetStringAsync(hitboxUrl).ConfigureAwait(false);
// data = JObject.Parse(response);
// isLive = data["media_is_live"].ToString() == "1";
// result = new Tuple<bool, string>(isLive, data["media_views"].ToString());
// cachedStatuses.TryAdd(hitboxUrl, result);
// return result;
// case StreamNotificationConfig.StreamType.Twitch:
// var twitchUrl = $"https://api.twitch.tv/kraken/streams/{Uri.EscapeUriString(stream.Username)}";
// if (checkCache && cachedStatuses.TryGetValue(twitchUrl, out result))
// return result;
// response = await http.GetStringAsync(twitchUrl).ConfigureAwait(false);
// data = JObject.Parse(response);
// isLive = !string.IsNullOrWhiteSpace(data["stream"].ToString());
// result = new Tuple<bool, string>(isLive, isLive ? data["stream"]["viewers"].ToString() : "0");
// cachedStatuses.TryAdd(twitchUrl, result);
// return result;
// case StreamNotificationConfig.StreamType.Beam:
// var beamUrl = $"https://beam.pro/api/v1/channels/{stream.Username}";
// if (checkCache && cachedStatuses.TryGetValue(beamUrl, out result))
// return result;
// response = await http.GetStringAsync(beamUrl).ConfigureAwait(false);
// data = JObject.Parse(response);
// isLive = data["online"].ToObject<bool>() == true;
// result = new Tuple<bool, string>(isLive, data["viewersCurrent"].ToString());
// cachedStatuses.TryAdd(beamUrl, result);
// return result;
// default:
// break;
// }
// return new Tuple<bool, string>(false, "0");
// }
// internal override void Init(CommandGroupBuilder cgb)
// {
// cgb.CreateCommand(Module.Prefix + "hitbox")
// .Alias(Module.Prefix + "hb")
// .Description("Notifies this channel when a certain user starts streaming." +
// $" | `{Prefix}hitbox SomeStreamer`")
// .Parameter("username", ParameterType.Unparsed)
// .AddCheck(SimpleCheckers.ManageServer())
// .Do(TrackStream(StreamNotificationConfig.StreamType.Hitbox));
// cgb.CreateCommand(Module.Prefix + "twitch")
// .Alias(Module.Prefix + "tw")
// .Description("Notifies this channel when a certain user starts streaming." +
// $" | `{Prefix}twitch SomeStreamer`")
// .AddCheck(SimpleCheckers.ManageServer())
// .Parameter("username", ParameterType.Unparsed)
// .Do(TrackStream(StreamNotificationConfig.StreamType.Twitch));
// cgb.CreateCommand(Module.Prefix + "beam")
// .Alias(Module.Prefix + "bm")
// .Description("Notifies this channel when a certain user starts streaming." +
// $" | `{Prefix}beam SomeStreamer`")
// .AddCheck(SimpleCheckers.ManageServer())
// .Parameter("username", ParameterType.Unparsed)
// .Do(TrackStream(StreamNotificationConfig.StreamType.Beam));
// cgb.CreateCommand(Module.Prefix + "checkhitbox")
// .Alias(Module.Prefix + "chhb")
// .Description("Checks if a certain user is streaming on the hitbox platform." +
// $" | `{Prefix}chhb SomeStreamer`")
// .Parameter("username", ParameterType.Unparsed)
// .AddCheck(SimpleCheckers.ManageServer())
// .Do(async e =>
// {
// var stream = e.GetArg("username")?.Trim();
// if (string.IsNullOrWhiteSpace(stream))
// return;
// try
// {
// var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
// {
// Username = stream,
// Type = StreamNotificationConfig.StreamType.Hitbox
// }));
// if (streamStatus.Item1)
// {
// await imsg.Channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
// }
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("No channel found.");
// }
// });
// cgb.CreateCommand(Module.Prefix + "checktwitch")
// .Alias(Module.Prefix + "chtw")
// .Description("Checks if a certain user is streaming on the twitch platform." +
// $" | `{Prefix}chtw SomeStreamer`")
// .AddCheck(SimpleCheckers.ManageServer())
// .Parameter("username", ParameterType.Unparsed)
// .Do(async e =>
// {
// var stream = e.GetArg("username")?.Trim();
// if (string.IsNullOrWhiteSpace(stream))
// return;
// try
// {
// var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
// {
// Username = stream,
// Type = StreamNotificationConfig.StreamType.Twitch
// }));
// if (streamStatus.Item1)
// {
// await imsg.Channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
// }
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("No channel found.");
// }
// });
// cgb.CreateCommand(Module.Prefix + "checkbeam")
// .Alias(Module.Prefix + "chbm")
// .Description("Checks if a certain user is streaming on the beam platform." +
// $" | `{Prefix}chbm SomeStreamer`")
// .AddCheck(SimpleCheckers.ManageServer())
// .Parameter("username", ParameterType.Unparsed)
// .Do(async e =>
// {
// var stream = e.GetArg("username")?.Trim();
// if (string.IsNullOrWhiteSpace(stream))
// return;
// try
// {
// var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
// {
// Username = stream,
// Type = StreamNotificationConfig.StreamType.Beam
// }));
// if (streamStatus.Item1)
// {
// await imsg.Channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
// }
// }
// catch
// {
// await imsg.Channel.SendMessageAsync("No channel found.");
// }
// });
// cgb.CreateCommand(Module.Prefix + "removestream")
// .Alias(Module.Prefix + "rms")
// .Description("Removes notifications of a certain streamer on this channel." +
// $" | `{Prefix}rms SomeGuy`")
// .AddCheck(SimpleCheckers.ManageServer())
// .Parameter("username", ParameterType.Unparsed)
// .Do(async e =>
// {
// var username = e.GetArg("username")?.ToLower().Trim();
// if (string.IsNullOrWhiteSpace(username))
// return;
// var config = SpecificConfigurations.Default.Of(e.Server.Id);
// var toRemove = config.ObservingStreams
// .FirstOrDefault(snc => snc.ChannelId == e.Channel.Id &&
// snc.Username.ToLower().Trim() == username);
// if (toRemove == null)
// {
// await imsg.Channel.SendMessageAsync(":anger: No such stream.").ConfigureAwait(false);
// return;
// }
// config.ObservingStreams.Remove(toRemove);
// await ConfigHandler.SaveConfig().ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false);
// });
// cgb.CreateCommand(Module.Prefix + "liststreams")
// .Alias(Module.Prefix + "ls")
// .Description("Lists all streams you are following on this server." +
// $" | `{Prefix}ls`")
// .Do(async e =>
// {
// var config = SpecificConfigurations.Default.Of(e.Server.Id);
// var streams = config.ObservingStreams.Where(snc =>
// snc.ServerId == e.Server.Id);
// var streamsArray = streams as StreamNotificationConfig[] ?? streams.ToArray();
// if (streamsArray.Length == 0)
// {
// await imsg.Channel.SendMessageAsync("You are not following any streams on this server.").ConfigureAwait(false);
// return;
// }
// var text = string.Join("\n", streamsArray.Select(snc =>
// {
// try
// {
// return $"`{snc.Username}`'s stream on **{e.Server.GetChannel(e.Channel.Id).Name}** channel. 【`{snc.Type.ToString()}`】";
// }
// catch { }
// return "";
// }));
// await imsg.Channel.SendMessageAsync($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false);
// });
// }
// private Func<CommandEventArgs, Task> TrackStream(StreamNotificationConfig.StreamType type) =>
// async e =>
// {
// var username = e.GetArg("username")?.ToLowerInvariant();
// if (string.IsNullOrWhiteSpace(username))
// return;
// var config = SpecificConfigurations.Default.Of(e.Server.Id);
// var stream = new StreamNotificationConfig
// {
// ServerId = e.Server.Id,
// ChannelId = e.Channel.Id,
// Username = username,
// Type = type,
// };
// var exists = config.ObservingStreams.Contains(stream);
// if (exists)
// {
// await imsg.Channel.SendMessageAsync(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false);
// return;
// }
// Tuple<bool, string> data;
// try
// {
// data = await GetStreamStatus(stream).ConfigureAwait(false);
// }
// catch
// {
// await imsg.Channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false);
// return;
// }
// var msg = $"Stream is currently **{(data.Item1 ? "ONLINE" : "OFFLINE")}** with **{data.Item2}** viewers";
// if (data.Item1)
// if (type == StreamNotificationConfig.StreamType.Hitbox)
// msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
// else if (type == StreamNotificationConfig.StreamType.Twitch)
// msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
// else if (type == StreamNotificationConfig.StreamType.Beam)
// msg += $"\n`Here is the Link:`【 https://beam.pro/{stream.Username}/ 】";
// else if (type == StreamNotificationConfig.StreamType.YoutubeGaming)
// msg += $"\n`Here is the Link:` not implemented yet - {stream.Username}";
// stream.LastStatus = data.Item1;
// if (!exists)
// msg = $":ok: I will notify this channel when status changes.\n{msg}";
// await imsg.Channel.SendMessageAsync(msg).ConfigureAwait(false);
// config.ObservingStreams.Add(stream);
// };
// }
// }
//}

View File

@ -1,344 +0,0 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.JSONModels;
using NadekoBot.Modules.Permissions.Classes;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
namespace NadekoBot.Modules.Searches.Commands
{
internal class StreamNotifications : DiscordCommand
{
private readonly Timer checkTimer = new Timer
{
Interval = new TimeSpan(0, 0, 15).TotalMilliseconds,
};
private ConcurrentDictionary<string, Tuple<bool, string>> cachedStatuses = new ConcurrentDictionary<string, Tuple<bool, string>>();
public StreamNotifications(DiscordModule module) : base(module)
{
checkTimer.Elapsed += async (s, e) =>
{
cachedStatuses.Clear();
try
{
var streams = SpecificConfigurations.Default.AllConfigs.SelectMany(c => c.ObservingStreams);
if (!streams.Any()) return;
foreach (var stream in streams)
{
Tuple<bool, string> data;
try
{
data = await GetStreamStatus(stream).ConfigureAwait(false);
}
catch
{
continue;
}
if (data.Item1 != stream.LastStatus)
{
stream.LastStatus = data.Item1;
var server = NadekoBot.Client.GetServer(stream.ServerId);
var channel = server?.GetChannel(stream.ChannelId);
if (channel == null)
continue;
var msg = $"`{stream.Username}`'s stream is now " +
$"**{(data.Item1 ? "ONLINE" : "OFFLINE")}** with " +
$"**{data.Item2}** viewers.";
if (stream.LastStatus)
if (stream.Type == StreamNotificationConfig.StreamType.Hitbox)
msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
else if (stream.Type == StreamNotificationConfig.StreamType.Twitch)
msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
else if (stream.Type == StreamNotificationConfig.StreamType.Beam)
msg += $"\n`Here is the Link:`【 http://www.beam.pro/{stream.Username}/ 】";
else if (stream.Type == StreamNotificationConfig.StreamType.YoutubeGaming)
msg += $"\n`Here is the Link:`【 not implemented yet - {stream.Username} 】";
await channel.SendMessage(msg).ConfigureAwait(false);
}
}
}
catch { }
await ConfigHandler.SaveConfig().ConfigureAwait(false);
};
checkTimer.Start();
}
private async Task<Tuple<bool, string>> GetStreamStatus(StreamNotificationConfig stream, bool checkCache = true)
{
bool isLive;
string response;
JObject data;
Tuple<bool, string> result;
switch (stream.Type)
{
case StreamNotificationConfig.StreamType.Hitbox:
var hitboxUrl = $"https://api.hitbox.tv/media/status/{stream.Username}";
if (checkCache && cachedStatuses.TryGetValue(hitboxUrl, out result))
return result;
response = await http.GetStringAsync(hitboxUrl).ConfigureAwait(false);
data = JObject.Parse(response);
isLive = data["media_is_live"].ToString() == "1";
result = new Tuple<bool, string>(isLive, data["media_views"].ToString());
cachedStatuses.TryAdd(hitboxUrl, result);
return result;
case StreamNotificationConfig.StreamType.Twitch:
var twitchUrl = $"https://api.twitch.tv/kraken/streams/{Uri.EscapeUriString(stream.Username)}";
if (checkCache && cachedStatuses.TryGetValue(twitchUrl, out result))
return result;
response = await http.GetStringAsync(twitchUrl).ConfigureAwait(false);
data = JObject.Parse(response);
isLive = !string.IsNullOrWhiteSpace(data["stream"].ToString());
result = new Tuple<bool, string>(isLive, isLive ? data["stream"]["viewers"].ToString() : "0");
cachedStatuses.TryAdd(twitchUrl, result);
return result;
case StreamNotificationConfig.StreamType.Beam:
var beamUrl = $"https://beam.pro/api/v1/channels/{stream.Username}";
if (checkCache && cachedStatuses.TryGetValue(beamUrl, out result))
return result;
response = await http.GetStringAsync(beamUrl).ConfigureAwait(false);
data = JObject.Parse(response);
isLive = data["online"].ToObject<bool>() == true;
result = new Tuple<bool, string>(isLive, data["viewersCurrent"].ToString());
cachedStatuses.TryAdd(beamUrl, result);
return result;
default:
break;
}
return new Tuple<bool, string>(false, "0");
}
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "hitbox")
.Alias(Module.Prefix + "hb")
.Description("Notifies this channel when a certain user starts streaming." +
$" | `{Prefix}hitbox SomeStreamer`")
.Parameter("username", ParameterType.Unparsed)
.AddCheck(SimpleCheckers.ManageServer())
.Do(TrackStream(StreamNotificationConfig.StreamType.Hitbox));
cgb.CreateCommand(Module.Prefix + "twitch")
.Alias(Module.Prefix + "tw")
.Description("Notifies this channel when a certain user starts streaming." +
$" | `{Prefix}twitch SomeStreamer`")
.AddCheck(SimpleCheckers.ManageServer())
.Parameter("username", ParameterType.Unparsed)
.Do(TrackStream(StreamNotificationConfig.StreamType.Twitch));
cgb.CreateCommand(Module.Prefix + "beam")
.Alias(Module.Prefix + "bm")
.Description("Notifies this channel when a certain user starts streaming." +
$" | `{Prefix}beam SomeStreamer`")
.AddCheck(SimpleCheckers.ManageServer())
.Parameter("username", ParameterType.Unparsed)
.Do(TrackStream(StreamNotificationConfig.StreamType.Beam));
cgb.CreateCommand(Module.Prefix + "checkhitbox")
.Alias(Module.Prefix + "chhb")
.Description("Checks if a certain user is streaming on the hitbox platform." +
$" | `{Prefix}chhb SomeStreamer`")
.Parameter("username", ParameterType.Unparsed)
.AddCheck(SimpleCheckers.ManageServer())
.Do(async e =>
{
var stream = e.GetArg("username")?.Trim();
if (string.IsNullOrWhiteSpace(stream))
return;
try
{
var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
{
Username = stream,
Type = StreamNotificationConfig.StreamType.Hitbox
}));
if (streamStatus.Item1)
{
await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
}
}
catch
{
await channel.SendMessageAsync("No channel found.");
}
});
cgb.CreateCommand(Module.Prefix + "checktwitch")
.Alias(Module.Prefix + "chtw")
.Description("Checks if a certain user is streaming on the twitch platform." +
$" | `{Prefix}chtw SomeStreamer`")
.AddCheck(SimpleCheckers.ManageServer())
.Parameter("username", ParameterType.Unparsed)
.Do(async e =>
{
var stream = e.GetArg("username")?.Trim();
if (string.IsNullOrWhiteSpace(stream))
return;
try
{
var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
{
Username = stream,
Type = StreamNotificationConfig.StreamType.Twitch
}));
if (streamStatus.Item1)
{
await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
}
}
catch
{
await channel.SendMessageAsync("No channel found.");
}
});
cgb.CreateCommand(Module.Prefix + "checkbeam")
.Alias(Module.Prefix + "chbm")
.Description("Checks if a certain user is streaming on the beam platform." +
$" | `{Prefix}chbm SomeStreamer`")
.AddCheck(SimpleCheckers.ManageServer())
.Parameter("username", ParameterType.Unparsed)
.Do(async e =>
{
var stream = e.GetArg("username")?.Trim();
if (string.IsNullOrWhiteSpace(stream))
return;
try
{
var streamStatus = (await GetStreamStatus(new StreamNotificationConfig
{
Username = stream,
Type = StreamNotificationConfig.StreamType.Beam
}));
if (streamStatus.Item1)
{
await channel.SendMessageAsync($"`Streamer {streamStatus.Item2} is online.`");
}
}
catch
{
await channel.SendMessageAsync("No channel found.");
}
});
cgb.CreateCommand(Module.Prefix + "removestream")
.Alias(Module.Prefix + "rms")
.Description("Removes notifications of a certain streamer on this channel." +
$" | `{Prefix}rms SomeGuy`")
.AddCheck(SimpleCheckers.ManageServer())
.Parameter("username", ParameterType.Unparsed)
.Do(async e =>
{
var username = e.GetArg("username")?.ToLower().Trim();
if (string.IsNullOrWhiteSpace(username))
return;
var config = SpecificConfigurations.Default.Of(e.Server.Id);
var toRemove = config.ObservingStreams
.FirstOrDefault(snc => snc.ChannelId == e.Channel.Id &&
snc.Username.ToLower().Trim() == username);
if (toRemove == null)
{
await channel.SendMessageAsync(":anger: No such stream.").ConfigureAwait(false);
return;
}
config.ObservingStreams.Remove(toRemove);
await ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($":ok: Removed `{toRemove.Username}`'s stream from notifications.").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "liststreams")
.Alias(Module.Prefix + "ls")
.Description("Lists all streams you are following on this server." +
$" | `{Prefix}ls`")
.Do(async e =>
{
var config = SpecificConfigurations.Default.Of(e.Server.Id);
var streams = config.ObservingStreams.Where(snc =>
snc.ServerId == e.Server.Id);
var streamsArray = streams as StreamNotificationConfig[] ?? streams.ToArray();
if (streamsArray.Length == 0)
{
await channel.SendMessageAsync("You are not following any streams on this server.").ConfigureAwait(false);
return;
}
var text = string.Join("\n", streamsArray.Select(snc =>
{
try
{
return $"`{snc.Username}`'s stream on **{e.Server.GetChannel(e.Channel.Id).Name}** channel. 【`{snc.Type.ToString()}`】";
}
catch { }
return "";
}));
await channel.SendMessageAsync($"You are following **{streamsArray.Length}** streams on this server.\n\n" + text).ConfigureAwait(false);
});
}
private Func<CommandEventArgs, Task> TrackStream(StreamNotificationConfig.StreamType type) =>
async e =>
{
var username = e.GetArg("username")?.ToLowerInvariant();
if (string.IsNullOrWhiteSpace(username))
return;
var config = SpecificConfigurations.Default.Of(e.Server.Id);
var stream = new StreamNotificationConfig
{
ServerId = e.Server.Id,
ChannelId = e.Channel.Id,
Username = username,
Type = type,
};
var exists = config.ObservingStreams.Contains(stream);
if (exists)
{
await channel.SendMessageAsync(":anger: I am already notifying that stream on this channel.").ConfigureAwait(false);
return;
}
Tuple<bool, string> data;
try
{
data = await GetStreamStatus(stream).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync(":anger: Stream probably doesn't exist.").ConfigureAwait(false);
return;
}
var msg = $"Stream is currently **{(data.Item1 ? "ONLINE" : "OFFLINE")}** with **{data.Item2}** viewers";
if (data.Item1)
if (type == StreamNotificationConfig.StreamType.Hitbox)
msg += $"\n`Here is the Link:`【 http://www.hitbox.tv/{stream.Username}/ 】";
else if (type == StreamNotificationConfig.StreamType.Twitch)
msg += $"\n`Here is the Link:`【 http://www.twitch.tv/{stream.Username}/ 】";
else if (type == StreamNotificationConfig.StreamType.Beam)
msg += $"\n`Here is the Link:`【 https://beam.pro/{stream.Username}/ 】";
else if (type == StreamNotificationConfig.StreamType.YoutubeGaming)
msg += $"\n`Here is the Link:` not implemented yet - {stream.Username}";
stream.LastStatus = data.Item1;
if (!exists)
msg = $":ok: I will notify this channel when status changes.\n{msg}";
await channel.SendMessageAsync(msg).ConfigureAwait(false);
config.ObservingStreams.Add(stream);
};
}
}

View File

@ -1,36 +0,0 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Classes.JSONModels;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NadekoBot.Modules.Searches.Commands
{
class WowJokeCommand : DiscordCommand
{
List<WoWJoke> jokes = new List<WoWJoke>();
public WowJokeCommand(DiscordModule module) : base(module)
{
}
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "wowjoke")
.Description($"Get one of Kwoth's penultimate WoW jokes. | `{Prefix}wowjoke`")
.Do(async e =>
{
if (!jokes.Any())
{
jokes = JsonConvert.DeserializeObject<List<WoWJoke>>(File.ReadAllText("data/wowjokes.json"));
}
await channel.SendMessageAsync(jokes[new Random().Next(0, jokes.Count)].ToString());
});
}
}
}

View File

@ -14,6 +14,9 @@ using NadekoBot.Attributes;
using NadekoBot.Extensions;
using Discord.API;
using System.Text.RegularExpressions;
using System.Net;
using NadekoBot.Modules.Searches.Commands.Models;
using Google.Apis.YouTube.v3;
namespace NadekoBot.Modules.Searches
{
@ -22,9 +25,12 @@ namespace NadekoBot.Modules.Searches
{
private readonly Random rng;
public SearchesModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
private IYoutubeService _yt { get; }
public SearchesModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client, IYoutubeService youtube) : base(loc, cmds, config, client)
{
rng = new Random();
_yt = youtube;
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
@ -54,59 +60,16 @@ $@"🌍 **Weather for** 【{obj["target"]}】
{
var channel = imsg.Channel as IGuildChannel;
if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
var link = await FindYoutubeUrlByKeywords(query).ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(link))
var result = (await _yt.FindVideosByKeywordsAsync(query, 1)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(result))
{
await imsg.Channel.SendMessageAsync("No results found for that query.");
return;
}
var shortUrl = await link.ShortenUrl().ConfigureAwait(false);
var shortUrl = await result.ShortenUrl().ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(shortUrl).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Anime(IMessage imsg, [Remainder] string query)
{
var channel = imsg.Channel as IGuildChannel;
if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
string result;
try
{
result = (await GetAnimeData(query).ConfigureAwait(false)).ToString();
}
catch
{
await imsg.Channel.SendMessageAsync("Failed to find that anime.").ConfigureAwait(false);
return;
}
await imsg.Channel.SendMessageAsync(result.ToString()).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Manga(IMessage imsg, [Remainder] string query)
{
var channel = imsg.Channel as IGuildChannel;
if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
string result;
try
{
result = (await GetMangaData(query).ConfigureAwait(false)).ToString();
}
catch
{
await imsg.Channel.SendMessageAsync("Failed to find that manga.").ConfigureAwait(false);
return;
}
await imsg.Channel.SendMessageAsync(result).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Imdb(IMessage imsg, [Remainder] string query)
@ -114,11 +77,11 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var channel = imsg.Channel as IGuildChannel;
if (!(await ValidateQuery(imsg.Channel as ITextChannel, query).ConfigureAwait(false))) return;
await e.Channel.SendIsTyping().ConfigureAwait(false);
await imsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
string result;
try
{
var movie = ImdbScraper.ImdbScrape(query, true);
var movie = await ImdbScraper.ImdbScrape(query, true);
if (movie.Status) result = movie.ToString();
else result = "Failed to find that movie.";
}
@ -240,55 +203,54 @@ $@"🌍 **Weather for** 【{obj["target"]}】
terms = terms?.Trim();
if (string.IsNullOrWhiteSpace(terms))
return;
await imsg.Channel.SendMessageAsync($"https://google.com/search?q={ HttpUtility.UrlEncode(terms).Replace(' ', '+') }")
await imsg.Channel.SendMessageAsync($"https://google.com/search?q={ WebUtility.UrlEncode(terms).Replace(' ', '+') }")
.ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Hearthstone(IMessage imsg, [Remainder] string name)
{
var channel = imsg.Channel as IGuildChannel;
var arg = e.GetArg("name");
if (string.IsNullOrWhiteSpace(arg))
{
await imsg.Channel.SendMessageAsync("💢 Please enter a card name to search for.").ConfigureAwait(false);
return;
}
await imsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
string response = "";
using (var http = new HttpClient())
{
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey);
response = await http.GetStringAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers)
.ConfigureAwait(false);
try
{
var items = JArray.Parse(response);
var images = new List<Image>();
if (items == null)
throw new KeyNotFoundException("Cannot find a card by that name");
var cnt = 0;
items.Shuffle();
foreach (var item in items.TakeWhile(item => cnt++ < 4).Where(item => item.HasValues && item["img"] != null))
{
images.Add(
Image.FromStream(await http.GetStreamAsync(item["img"].ToString()).ConfigureAwait(false)));
}
if (items.Count > 4)
{
await imsg.Channel.SendMessageAsync("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false);
}
await imsg.Channel.SendMessageAsync(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png))
.ConfigureAwait(false);
}
catch (Exception ex)
{
await imsg.Channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false);
}
}
}
////todo drawing
//[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public async Task Hearthstone(IMessage imsg, [Remainder] string name)
//{
// var channel = imsg.Channel as IGuildChannel;
// var arg = e.GetArg("name");
// if (string.IsNullOrWhiteSpace(arg))
// {
// await imsg.Channel.SendMessageAsync("💢 Please enter a card name to search for.").ConfigureAwait(false);
// return;
// }
// await imsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
// string response = "";
// using (var http = new HttpClient())
// {
// http.DefaultRequestHeaders.Clear();
// http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey);
// response = await http.GetStringAsync($"https://omgvamp-hearthstone-v1.p.mashape.com/cards/search/{Uri.EscapeUriString(arg)}", headers)
// .ConfigureAwait(false);
// try
// {
// var items = JArray.Parse(response).Shuffle().ToList();
// var images = new List<Image>();
// if (items == null)
// throw new KeyNotFoundException("Cannot find a card by that name");
// var cnt = 0;
// foreach (var item in items.TakeWhile(item => cnt++ < 4).Where(item => item.HasValues && item["img"] != null))
// {
// images.Add(
// Image.FromStream(await http.GetStreamAsync(item["img"].ToString()).ConfigureAwait(false)));
// }
// if (items.Count > 4)
// {
// await imsg.Channel.SendMessageAsync("⚠ Found over 4 images. Showing random 4.").ConfigureAwait(false);
// }
// await imsg.Channel.SendMessageAsync(arg + ".png", (await images.MergeAsync()).ToStream(System.Drawing.Imaging.ImageFormat.Png))
// .ConfigureAwait(false);
// }
// catch (Exception ex)
// {
// await imsg.Channel.SendMessageAsync($"💢 Error {ex.Message}").ConfigureAwait(false);
// }
// }
//}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
@ -307,7 +269,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
{
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("X-Mashape-Key", NadekoBot.Credentials.MashapeKey);
var res = await http.GetStringAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}", headers).ConfigureAwait(false);
var res = await http.GetStringAsync($"https://mashape-community-urban-dictionary.p.mashape.com/define?term={Uri.EscapeUriString(arg)}").ConfigureAwait(false);
try
{
var items = JObject.Parse(res);
@ -350,7 +312,7 @@ $@"🌍 **Weather for** 【{obj["target"]}】
var items = JObject.Parse(res);
var str = $@"`Hashtag:` {items["defs"]["def"]["hashtag"].ToString()}
`Definition:` {items["defs"]["def"]["text"].ToString()}
`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl().ConfigureAwait(false)}>");
`Link:` <{await items["defs"]["def"]["uri"].ToString().ShortenUrl().ConfigureAwait(false)}>";
await imsg.Channel.SendMessageAsync(str);
}
catch
@ -358,16 +320,16 @@ $@"🌍 **Weather for** 【{obj["target"]}】
await imsg.Channel.SendMessageAsync("💢 Failed finding a definition for that tag.").ConfigureAwait(false);
}
}
//todo DB
//[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public async Task Quote(IMessage imsg)
//{
// var channel = imsg.Channel as IGuildChannel;
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Quote(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
var quote = NadekoBot.Config.Quotes[rng.Next(0, NadekoBot.Config.Quotes.Count)].ToString();
await imsg.Channel.SendMessageAsync(quote).ConfigureAwait(false);
}
// var quote = NadekoBot.Config.Quotes[rng.Next(0, NadekoBot.Config.Quotes.Count)].ToString();
// await imsg.Channel.SendMessageAsync(quote).ConfigureAwait(false);
//}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
@ -383,54 +345,6 @@ $@"🌍 **Weather for** 【{obj["target"]}】
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Yomama(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://api.yomomma.info/").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Randjoke(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task ChuckNorris(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
using (var http = new HttpClient())
{
var response = await http.GetStringAsync("http://tambal.azurewebsites.net/joke/random").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`" + JObject.Parse(response)["joke"].ToString() + "` 😆").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task MagicItem(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
var magicItems = JsonConvert.DeserializeObject<List<MagicItem>>(File.ReadAllText("data/magicitems.json"));
var item = magicItems[rng.Next(0, magicItems.Count)].ToString();
await imsg.Channel.SendMessageAsync(item).ConfigureAwait(false);
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Revav(IMessage imsg, [Remainder] string arg)
@ -494,30 +408,31 @@ $@"🌍 **Weather for** 【{obj["target"]}】
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Clr(IMessage imsg, [Remainder] string color)
{
var channel = imsg.Channel as IGuildChannel;
////todo Drawing
//[LocalizedCommand, LocalizedDescription, LocalizedSummary]
//[RequireContext(ContextType.Guild)]
//public async Task Clr(IMessage imsg, [Remainder] string color)
//{
// var channel = imsg.Channel as IGuildChannel;
var arg1 = e.GetArg("color")?.Trim()?.Replace("#", "");
if (string.IsNullOrWhiteSpace(arg1))
return;
var img = new Bitmap(50, 50);
// color = color?.Trim().Replace("#", "");
// if (string.IsNullOrWhiteSpace((string)color))
// return;
// var img = new Bitmap(50, 50);
var red = Convert.ToInt32(arg1.Substring(0, 2), 16);
var green = Convert.ToInt32(arg1.Substring(2, 2), 16);
var blue = Convert.ToInt32(arg1.Substring(4, 2), 16);
var brush = new SolidBrush(System.Drawing.Color.FromArgb(red, green, blue));
// var red = Convert.ToInt32(color.Substring(0, 2), 16);
// var green = Convert.ToInt32(color.Substring(2, 2), 16);
// var blue = Convert.ToInt32(color.Substring(4, 2), 16);
// var brush = new SolidBrush(System.Drawing.Color.FromArgb(red, green, blue));
using (Graphics g = Graphics.FromImage(img))
{
g.FillRectangle(brush, 0, 0, 50, 50);
g.Flush();
}
// using (Graphics g = Graphics.FromImage(img))
// {
// g.FillRectangle(brush, 0, 0, 50, 50);
// g.Flush();
// }
await imsg.Channel.SendFileAsync("arg1.png", img.ToStream());
}
// await imsg.Channel.SendFileAsync("arg1.png", img.ToStream());
//}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]

View File

@ -1,94 +1,23 @@
// Copyright (c) 2015 Ravi Bhavnani
// License: Code Project Open License
// http://www.codeproject.com/info/cpol10.aspx
using Newtonsoft.Json.Linq;
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
namespace NadekoBot.Modules.Translator.Helpers
namespace NadekoBot.Modules.Translator
{
/// <summary>
/// Translates text using Google's online language tools.
/// </summary>
public class GoogleTranslator
{
#region Properties
private static GoogleTranslator _instance;
public static GoogleTranslator Instance = _instance ?? (_instance = new GoogleTranslator());
/// <summary>
/// Gets the supported languages.
/// </summary>
public static IEnumerable<string> Languages {
get {
GoogleTranslator.EnsureInitialized();
return GoogleTranslator._languageModeMap.Keys.OrderBy(p => p);
}
}
#endregion
public IEnumerable<string> Languages => _languageDictionary.Keys.OrderBy(x => x);
private Dictionary<string, string> _languageDictionary;
#region Public methods
/// <summary>
/// Translates the specified source text.
/// </summary>
/// <param name="sourceText">The source text.</param>
/// <param name="sourceLanguage">The source language.</param>
/// <param name="targetLanguage">The target language.</param>
/// <returns>The translation.</returns>
public async Task<string> Translate
(string sourceText,
string sourceLanguage,
string targetLanguage)
{
// Initialize
DateTime tmStart = DateTime.Now;
string text = string.Empty;
// Download translation
string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
GoogleTranslator.LanguageEnumToIdentifier(sourceLanguage),
GoogleTranslator.LanguageEnumToIdentifier(targetLanguage),
HttpUtility.UrlEncode(sourceText));
using (HttpClient http = new HttpClient())
{
http.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
text = await http.GetStringAsync(url).ConfigureAwait(false);
}
return (string.Concat(JArray.Parse(text)[0].Select(x => x[0])));
}
#endregion
#region Private methods
/// <summary>
/// Converts a language to its identifier.
/// </summary>
/// <param name="language">The language."</param>
/// <returns>The identifier or <see cref="string.Empty"/> if none.</returns>
private static string LanguageEnumToIdentifier
(string language)
{
string mode = string.Empty;
GoogleTranslator.EnsureInitialized();
GoogleTranslator._languageModeMap.TryGetValue(language, out mode);
return mode;
}
/// <summary>
/// Ensures the translator has been initialized.
/// </summary>
public static void EnsureInitialized()
{
if (GoogleTranslator._languageModeMap == null)
{
GoogleTranslator._languageModeMap = new Dictionary<string, string>() {
static GoogleTranslator() { }
private GoogleTranslator() {
_languageDictionary = new Dictionary<string, string>() {
{ "afrikaans", "af"},
{ "albanian", "sq"},
{ "arabic", "ar"},
@ -99,6 +28,8 @@ namespace NadekoBot.Modules.Translator.Helpers
{ "bengali", "bn"},
{ "bulgarian", "bg"},
{ "catalan", "ca"},
{ "chinese-traditional", "zh-TW"},
{ "chinese-simplified", "zh-CN"},
{ "chinese", "zh-CN"},
{ "croatian", "hr"},
{ "czech", "cs"},
@ -218,17 +149,29 @@ namespace NadekoBot.Modules.Translator.Helpers
{ "yi", "yi"},
};
}
public async Task<string> Translate(string sourceText, string sourceLanguage, string targetLanguage)
{
string text = string.Empty;
string url = string.Format("https://translate.googleapis.com/translate_a/single?client=gtx&sl={0}&tl={1}&dt=t&q={2}",
ConvertToLanguageCode(sourceLanguage),
ConvertToLanguageCode(targetLanguage),
WebUtility.UrlEncode(sourceText));
using (HttpClient http = new HttpClient())
{
http.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
text = await http.GetStringAsync(url).ConfigureAwait(false);
}
#endregion
return (string.Concat(JArray.Parse(text)[0].Select(x => x[0])));
}
#region Fields
/// <summary>
/// The language to translation mode map.
/// </summary>
public static Dictionary<string, string> _languageModeMap;
#endregion
private string ConvertToLanguageCode(string language)
{
string mode = string.Empty;
_languageDictionary.TryGetValue(language, out mode);
return mode;
}
}
}

View File

@ -1,45 +0,0 @@
using Discord.Commands;
using NadekoBot.Classes;
using NadekoBot.Modules.Translator.Helpers;
using System;
using System.Threading.Tasks;
namespace NadekoBot.Modules.Translator
{
class TranslateCommand : DiscordCommand
{
public TranslateCommand(DiscordModule module) : base(module) { }
internal override void Init(CommandGroupBuilder cgb)
{
cgb.CreateCommand(Module.Prefix + "translate")
.Alias(Module.Prefix + "trans")
.Description($"Translates from>to text. From the given language to the destiation language. | `{Module.Prefix}trans en>fr Hello`")
.Parameter("langs", ParameterType.Required)
.Parameter("text", ParameterType.Unparsed)
.Do(TranslateFunc());
}
private GoogleTranslator t = new GoogleTranslator();
private Func<CommandEventArgs, Task> TranslateFunc() => async e =>
{
try
{
await e.Channel.SendIsTyping().ConfigureAwait(false);
string from = e.GetArg("langs").ToLowerInvariant().Split('>')[0];
string to = e.GetArg("langs").ToLowerInvariant().Split('>')[1];
var text = e.GetArg("text")?.Trim();
if (string.IsNullOrWhiteSpace(text))
return;
string translation = await t.Translate(text, from, to).ConfigureAwait(false);
await channel.SendMessageAsync(translation).ConfigureAwait(false);
}
catch (Exception ex)
{
Console.WriteLine(ex);
await channel.SendMessageAsync("Bad input format, or something went wrong...").ConfigureAwait(false);
}
};
}
}

View File

@ -1,26 +1,54 @@
using Discord.Modules;
using Discord;
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using NadekoBot.Modules.Permissions.Classes;
using System;
using System.Threading.Tasks;
using NadekoBot.Services;
namespace NadekoBot.Modules.Translator
{
internal class TranslatorModule : DiscordModule
public class TranslatorModule : DiscordModule
{
public TranslatorModule()
public TranslatorModule(ILocalization loc, CommandService cmds, IBotConfiguration config, IDiscordClient client) : base(loc, cmds, config, client)
{
commands.Add(new TranslateCommand(this));
commands.Add(new ValidLanguagesCommand(this));
}
public override string Prefix { get; } = NadekoBot.Config.CommandPrefixes.Searches;
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Translate(IMessage imsg, string langs, [Remainder] string text)
{
var channel = imsg.Channel as IGuildChannel;
public override void Install(ModuleManager manager)
try
{
manager.CreateCommands("", cgb =>
var langarr = langs.ToLowerInvariant().Split('>');
if (langarr.Length != 2)
return;
string from = langarr[0];
string to = langarr[1];
text = text?.Trim();
if (string.IsNullOrWhiteSpace(text))
return;
await imsg.Channel.TriggerTypingAsync().ConfigureAwait(false);
string translation = await GoogleTranslator.Instance.Translate(text, from, to).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(translation).ConfigureAwait(false);
}
catch (Exception ex)
{
cgb.AddCheck(PermissionChecker.Instance);
commands.ForEach(cmd => cmd.Init(cgb));
});
Console.WriteLine(ex);
await imsg.Channel.SendMessageAsync("Bad input format, or something went wrong...").ConfigureAwait(false);
}
}
[LocalizedCommand, LocalizedDescription, LocalizedSummary]
[RequireContext(ContextType.Guild)]
public async Task Translangs(IMessage imsg)
{
var channel = imsg.Channel as IGuildChannel;
await imsg.Channel.SendTableAsync(GoogleTranslator.Instance.Languages, str => str, columns: 4);
}
}

View File

@ -19,31 +19,6 @@ namespace NadekoBot.Modules.Translator
}
private Func<CommandEventArgs, Task> ListLanguagesFunc() => async e =>
{
try
{
GoogleTranslator.EnsureInitialized();
string s = e.GetArg("search");
string ret = "";
foreach (string key in GoogleTranslator._languageModeMap.Keys)
{
if (!s.Equals(""))
{
if (key.ToLower().Contains(s))
{
ret += " " + key + ";";
}
}
else
{
ret += " " + key + ";";
}
}
await channel.SendMessageAsync(ret).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Bad input format, or sth went wrong...").ConfigureAwait(false);
}
};
}

View File

@ -113,7 +113,7 @@
// if (ch == null)
// {
// await channel.SendMessageAsync($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync($"{e.User.Mention} Something went wrong (channel cannot be found) ;(").ConfigureAwait(false);
// return;
// }
@ -123,7 +123,7 @@
// if (m.Length == 0)
// {
// await channel.SendMessageAsync("Not a valid time format blablabla").ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync("Not a valid time format blablabla").ConfigureAwait(false);
// return;
// }
@ -148,7 +148,7 @@
// (groupName == "hours" && value > 23) ||
// (groupName == "minutes" && value > 59))
// {
// await channel.SendMessageAsync($"Invalid {groupName} value.").ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync($"Invalid {groupName} value.").ConfigureAwait(false);
// return;
// }
// else
@ -175,7 +175,7 @@
// reminders.Add(StartNewReminder(rem));
// await channel.SendMessageAsync($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false);
// await imsg.Channel.SendMessageAsync($"⏰ I will remind \"{ch.Name}\" to \"{e.GetArg("message").ToString()}\" in {output}. ({time:d.M.yyyy.} at {time:HH:mm})").ConfigureAwait(false);
// });
// cgb.CreateCommand(Module.Prefix + "remindmsg")
// .Description("Sets message for when the remind is triggered. " +
@ -190,7 +190,7 @@
// return;
// NadekoBot.Config.RemindMessageFormat = arg;
// await channel.SendMessageAsync("`New remind message set.`");
// await imsg.Channel.SendMessageAsync("`New remind message set.`");
// });
// }
// }

View File

@ -138,7 +138,7 @@ namespace NadekoBot.Modules.Utility
if (string.IsNullOrWhiteSpace(target))
{
var enumerable = (await msg.Channel.GetMessagesAsync(limit: 100)).Where(x => x.Author.Id == user.Id);
var enumerable = (await msg.Channel.GetMessagesAsync()).Where(x => x.Author.Id == user.Id);
await msg.Channel.DeleteMessagesAsync(enumerable);
return;
}
@ -156,6 +156,7 @@ namespace NadekoBot.Modules.Utility
int limit = (count < 100) ? count : 100;
var enumerable = (await msg.Channel.GetMessagesAsync(limit: limit));
await msg.Channel.DeleteMessagesAsync(enumerable);
await Task.Delay(1000); // there is a 1 per second per guild ratelimit for deletemessages
if (enumerable.Count < limit) break;
count -= limit;
}
@ -181,8 +182,14 @@ namespace NadekoBot.Modules.Utility
{
toDel.AddRange(messages.Where(m => m.Author.Id == mention.Id));
}
//TODO check if limit == 100 or there is no limit
await msg.Channel.DeleteMessagesAsync(toDel);
var messagesEnum = messages.AsEnumerable();
while (messagesEnum.Count() > 0)
{
await msg.Channel.DeleteMessagesAsync(messagesEnum.Take(100));
await Task.Delay(1000); // 1 second ratelimit
messagesEnum = messagesEnum.Skip(100);
}
}
}
}

View File

@ -20,6 +20,8 @@ namespace NadekoBot
public static Localization Localizer { get; private set; }
public static BotCredentials Credentials { get; private set; }
private static YoutubeService Youtube { get; set; }
public async Task RunAsync(string[] args)
{
//create client
@ -32,10 +34,11 @@ namespace NadekoBot
});
//initialize Services
Credentials = new BotCredentials();
Commands = new CommandService();
Config = new BotConfiguration();
Localizer = new Localization();
Credentials = new BotCredentials();
Youtube = new YoutubeService();
//setup DI
var depMap = new DependencyMap();
@ -43,6 +46,7 @@ namespace NadekoBot
depMap.Add<IBotConfiguration>(Config);
depMap.Add<IDiscordClient>(Client);
depMap.Add<CommandService>(Commands);
depMap.Add<IYoutubeService>(Youtube);
//connect
await Client.LoginAsync(TokenType.Bot, "MTE5Nzc3MDIxMzE5NTc3NjEw.CpGoCA.yQBJbLWurrjSk7IlGpGzBm-tPTg");

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NadekoBot.Services
{
public interface IYoutubeService
{
Task<IEnumerable<string>> FindVideosByKeywordsAsync(string keywords, int count = 1);
Task<IEnumerable<string>> FindPlaylistIdsByKeywordsAsync(string keywords, int count = 1);
Task<IEnumerable<string>> FindRelatedVideosAsync(string url, int count = 1);
}
}

View File

@ -14,6 +14,8 @@ namespace NadekoBot.Services.Impl
}
}
public IEnumerable<string> MashapeKey { get; internal set; }
public string Token {
get {
throw new NotImplementedException();

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.YouTube.v3;
using Google.Apis.Services;
using System.Text.RegularExpressions;
using System.Diagnostics.Contracts;
namespace NadekoBot.Services.Impl
{
public class YoutubeService : IYoutubeService
{
private YouTubeService yt;
public YoutubeService()
{
yt = new YouTubeService(new BaseClientService.Initializer {
ApplicationName = "Nadeko Bot",
ApiKey = NadekoBot.Credentials.GoogleApiKey
});
}
public async Task<IEnumerable<string>> FindPlaylistIdsByKeywordsAsync(string keywords, int count = 1)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(keywords));
Contract.Requires<ArgumentOutOfRangeException>(count > 0);
var match = new Regex("(?:youtu\\.be\\/|list=)(?<id>[\\da-zA-Z\\-_]*)").Match(keywords);
if (match.Length > 1)
{
return new[] { match.Groups["id"].Value.ToString() };
}
var query = yt.Search.List("snippet");
query.MaxResults = count;
query.Type = "playlist";
return (await query.ExecuteAsync()).Items.Select(i => i.Id.PlaylistId);
}
public async Task<IEnumerable<string>> FindRelatedVideosAsync(string id, int count = 1)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(id));
Contract.Requires<ArgumentOutOfRangeException>(count > 0);
var match = new Regex("(?:youtu\\.be\\/|v=)(?<id>[\\da-zA-Z\\-_]*)").Match(id);
if (match.Length > 1)
{
id = match.Groups["id"].Value;
}
var query = yt.Search.List("snippet");
query.MaxResults = count;
query.RelatedToVideoId = id;
query.Type = "video";
return (await query.ExecuteAsync()).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
}
public async Task<IEnumerable<string>> FindVideosByKeywordsAsync(string keywords, int count = 1)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(keywords));
Contract.Requires<ArgumentOutOfRangeException>(count > 0);
var query = yt.Search.List("snippet");
query.MaxResults = count;
query.Q = keywords;
query.Type = "video";
return (await query.ExecuteAsync()).Items.Select(i => "http://www.youtube.com/watch?v=" + i.Id.VideoId);
}
}
}

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
@ -24,11 +25,11 @@ namespace NadekoBot.Extensions
string toolong;
//while ((toolong = temp.FirstOrDefault(x => x.Length > 2000)) != null)
//{
// //TODO more desperate measures == split on whitespace?
// more desperate measures == split on whitespace?
//}
StringBuilder builder = new StringBuilder();
//TODO make this less crappy to look at, maybe it's bugged
//make this less crappy to look at, maybe it's bugged
for (int i = 0; i < temp.Count; i++)
{
var addition = temp[i];
@ -49,6 +50,15 @@ namespace NadekoBot.Extensions
return list.ToArray();
}
public static Task<IMessage> SendTableAsync<T>(this IMessageChannel ch, IEnumerable<T> items, Func<T, string> howToPrint, int columns = 3)
{
var i = 0;
return ch.SendMessageAsync($@"```xl
{string.Join("\n", items.GroupBy(item => (i++) / columns)
.Select(ig => string.Concat(ig.Select(el => howToPrint(el)))))}
```");
}
public static async Task<string> ShortenUrl(this string url)
{
if (string.IsNullOrWhiteSpace(NadekoBot.Credentials.GoogleApiKey)) return url;
@ -82,5 +92,48 @@ namespace NadekoBot.Extensions
}
}
/// <summary>
/// returns an IEnumerable with randomized element order
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)
{
// Thanks to @Joe4Evr for finding a bug in the old version of the shuffle
var provider = RandomNumberGenerator.Create();
var list = items.ToList();
var n = list.Count;
while (n > 1)
{
var box = new byte[(n / Byte.MaxValue) + 1];
int boxSum;
do
{
provider.GetBytes(box);
boxSum = box.Sum(b => b);
}
while (!(boxSum < n * ((Byte.MaxValue * box.Length) / n)));
var k = (boxSum % n);
n--;
var value = list[k];
list[k] = list[n];
list[n] = value;
}
return list;
}
public static string TrimTo(this string str, int maxLength, bool hideDots = false)
{
if (maxLength < 0)
throw new ArgumentOutOfRangeException(nameof(maxLength), $"Argument {nameof(maxLength)} can't be negative.");
if (maxLength == 0)
return string.Empty;
if (maxLength <= 3)
return string.Concat(str.Select(c => '.'));
if (str.Length < maxLength)
return str;
return string.Concat(str.Take(maxLength - 3)) + (hideDots ? "" : "...");
}
}
}

View File

@ -72,9 +72,9 @@ namespace NadekoBot.Modules.Administration
conf.AutoDeleteMessagesOnCommand = !conf.AutoDeleteMessagesOnCommand;
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
if (conf.AutoDeleteMessagesOnCommand)
await channel.SendMessageAsync("❗`Now automatically deleting successfull command invokations.`");
await imsg.Channel.SendMessageAsync("❗`Now automatically deleting successfull command invokations.`");
else
await channel.SendMessageAsync("❗`Stopped automatic deletion of successfull command invokations.`");
await imsg.Channel.SendMessageAsync("❗`Stopped automatic deletion of successfull command invokations.`");
});
@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Administration
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
await channel.SendMessageAsync("`Restarting in 2 seconds...`");
await imsg.Channel.SendMessageAsync("`Restarting in 2 seconds...`");
await Task.Delay(2000);
System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
Environment.Exit(0);
@ -103,31 +103,31 @@ namespace NadekoBot.Modules.Administration
if (!e.User.ServerPermissions.ManageRoles)
{
await channel.SendMessageAsync("You have insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You have insufficient permissions.").ConfigureAwait(false);
}
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return;
}
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
return;
}
try
{
await usr.AddRoles(role).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully added role **{role.Name}** to user **{usr.Name}**").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Failed to add roles. Bot has insufficient permissions.\n").ConfigureAwait(false);
Console.WriteLine(ex.ToString());
}
});
@ -147,25 +147,25 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return;
}
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You failed to supply a valid role").ConfigureAwait(false);
return;
}
try
{
await usr.RemoveRoles(role).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully removed role **{role.Name}** from user **{usr.Name}**").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
}
});
@ -183,7 +183,7 @@ namespace NadekoBot.Modules.Administration
var roleToEdit = e.Server.FindRoles(r1).FirstOrDefault();
if (roleToEdit == null)
{
await channel.SendMessageAsync("Can't find that role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Can't find that role.").ConfigureAwait(false);
return;
}
@ -191,15 +191,15 @@ namespace NadekoBot.Modules.Administration
{
if (roleToEdit.Position > e.Server.CurrentUser.Roles.Max(r => r.Position))
{
await channel.SendMessageAsync("I can't edit roles higher than my highest role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I can't edit roles higher than my highest role.").ConfigureAwait(false);
return;
}
await roleToEdit.Edit(r2);
await channel.SendMessageAsync("Role renamed.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Role renamed.").ConfigureAwait(false);
}
catch (Exception)
{
await channel.SendMessageAsync("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Failed to rename role. Probably insufficient permissions.").ConfigureAwait(false);
}
});
@ -214,18 +214,18 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(userName).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You failed to supply a valid username").ConfigureAwait(false);
return;
}
try
{
await usr.RemoveRoles(usr.Roles.ToArray()).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully removed **all** roles from user **{usr.Name}**").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Failed to remove roles. Most likely reason: Insufficient permissions.").ConfigureAwait(false);
}
});
@ -240,11 +240,11 @@ namespace NadekoBot.Modules.Administration
try
{
var r = await e.Server.CreateRole(e.GetArg("role_name")).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully created role **{r.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully created role **{r.Name}**.").ConfigureAwait(false);
}
catch (Exception)
{
await channel.SendMessageAsync(":warning: Unspecified error.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":warning: Unspecified error.").ConfigureAwait(false);
}
});
@ -258,7 +258,7 @@ namespace NadekoBot.Modules.Administration
{
if (!e.User.ServerPermissions.ManageRoles)
{
await channel.SendMessageAsync("You don't have permission to use this!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You don't have permission to use this!").ConfigureAwait(false);
return;
}
@ -266,7 +266,7 @@ namespace NadekoBot.Modules.Administration
if (args.Count() != 2 && args.Count() != 4)
{
await channel.SendMessageAsync("The parameters are invalid.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("The parameters are invalid.").ConfigureAwait(false);
return;
}
@ -274,7 +274,7 @@ namespace NadekoBot.Modules.Administration
if (role == null)
{
await channel.SendMessageAsync("That role does not exist.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("That role does not exist.").ConfigureAwait(false);
return;
}
try
@ -287,11 +287,11 @@ namespace NadekoBot.Modules.Administration
var blue = Convert.ToByte(rgb ? int.Parse(e.Args[3]) : Convert.ToInt32(arg1.Substring(4, 2), 16));
await role.Edit(color: new Color(red, green, blue)).ConfigureAwait(false);
await channel.SendMessageAsync($"Role {role.Name}'s color has been changed.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Role {role.Name}'s color has been changed.").ConfigureAwait(false);
}
catch (Exception)
{
await channel.SendMessageAsync("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Error occured, most likely invalid parameters or insufficient permissions.").ConfigureAwait(false);
}
});
@ -308,7 +308,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return;
}
if (!string.IsNullOrWhiteSpace(msg))
@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration
{
await e.Server.Ban(usr, 7).ConfigureAwait(false);
await channel.SendMessageAsync("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
}
}
});
@ -343,7 +343,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return;
}
if (!string.IsNullOrWhiteSpace(msg))
@ -357,11 +357,11 @@ namespace NadekoBot.Modules.Administration
await e.Server.Ban(usr, 7).ConfigureAwait(false);
await e.Server.Unban(usr).ConfigureAwait(false);
await channel.SendMessageAsync("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Soft-Banned user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
}
}
});
@ -379,7 +379,7 @@ namespace NadekoBot.Modules.Administration
var usr = e.Server.FindUsers(user).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("User not found.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("User not found.").ConfigureAwait(false);
return;
}
if (!string.IsNullOrWhiteSpace(msg))
@ -391,11 +391,11 @@ namespace NadekoBot.Modules.Administration
try
{
await usr.Kick().ConfigureAwait(false);
await channel.SendMessageAsync("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Kicked user " + usr.Name + " Id: " + usr.Id).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Error. Most likely I don't have sufficient permissions.").ConfigureAwait(false);
}
}
});
@ -406,7 +406,7 @@ namespace NadekoBot.Modules.Administration
{
if (!e.User.ServerPermissions.MuteMembers)
{
await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
return;
}
if (!e.Message.MentionedUsers.Any())
@ -417,11 +417,11 @@ namespace NadekoBot.Modules.Administration
{
await u.Edit(isMuted: true).ConfigureAwait(false);
}
await channel.SendMessageAsync("Mute successful").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Mute successful").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
}
});
@ -432,7 +432,7 @@ namespace NadekoBot.Modules.Administration
{
if (!e.User.ServerPermissions.MuteMembers)
{
await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return;
}
if (!e.Message.MentionedUsers.Any())
@ -443,11 +443,11 @@ namespace NadekoBot.Modules.Administration
{
await u.Edit(isMuted: false).ConfigureAwait(false);
}
await channel.SendMessageAsync("Unmute successful").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Unmute successful").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
}
});
@ -459,7 +459,7 @@ namespace NadekoBot.Modules.Administration
{
if (!e.User.ServerPermissions.DeafenMembers)
{
await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return;
}
if (!e.Message.MentionedUsers.Any())
@ -470,11 +470,11 @@ namespace NadekoBot.Modules.Administration
{
await u.Edit(isDeafened: true).ConfigureAwait(false);
}
await channel.SendMessageAsync("Deafen successful").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Deafen successful").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
}
});
@ -486,7 +486,7 @@ namespace NadekoBot.Modules.Administration
{
if (!e.User.ServerPermissions.DeafenMembers)
{
await channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You do not have permission to do that.").ConfigureAwait(false);
return;
}
if (!e.Message.MentionedUsers.Any())
@ -497,11 +497,11 @@ namespace NadekoBot.Modules.Administration
{
await u.Edit(isDeafened: false).ConfigureAwait(false);
}
await channel.SendMessageAsync("Undeafen successful").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Undeafen successful").ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I most likely don't have the permission necessary for that.").ConfigureAwait(false);
}
});
@ -519,12 +519,12 @@ namespace NadekoBot.Modules.Administration
if (ch == null)
return;
await ch.Delete().ConfigureAwait(false);
await channel.SendMessageAsync($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Removed channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
}
}
catch
{
await channel.SendMessageAsync("Insufficient permissions.");
await imsg.Channel.SendMessageAsync("Insufficient permissions.");
}
});
@ -539,12 +539,12 @@ namespace NadekoBot.Modules.Administration
if (e.User.ServerPermissions.ManageChannels)
{
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Voice).ConfigureAwait(false);
await channel.SendMessageAsync($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Created voice channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
}
}
catch
{
await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
}
});
@ -561,12 +561,12 @@ namespace NadekoBot.Modules.Administration
var channel = e.Server.FindChannels(e.GetArg("channel_name"), ChannelType.Text).FirstOrDefault();
if (channel == null) return;
await channel.Delete().ConfigureAwait(false);
await channel.SendMessageAsync($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Removed text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
}
}
catch
{
await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
}
});
@ -581,12 +581,12 @@ namespace NadekoBot.Modules.Administration
if (e.User.ServerPermissions.ManageChannels)
{
await e.Server.CreateChannel(e.GetArg("channel_name"), ChannelType.Text).ConfigureAwait(false);
await channel.SendMessageAsync($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Added text channel **{e.GetArg("channel_name")}**.").ConfigureAwait(false);
}
}
catch
{
await channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Insufficient permissions.").ConfigureAwait(false);
}
});
@ -599,7 +599,7 @@ namespace NadekoBot.Modules.Administration
{
var topic = e.GetArg("topic")?.Trim() ?? "";
await e.Channel.Edit(topic: topic).ConfigureAwait(false);
await channel.SendMessageAsync(":ok: **New channel topic set.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":ok: **New channel topic set.**").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "setchanlname")
@ -613,7 +613,7 @@ namespace NadekoBot.Modules.Administration
if (string.IsNullOrWhiteSpace(name))
return;
await e.Channel.Edit(name: name).ConfigureAwait(false);
await channel.SendMessageAsync(":ok: **New channel name set.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":ok: **New channel name set.**").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "heap")
@ -622,7 +622,7 @@ namespace NadekoBot.Modules.Administration
.Do(async e =>
{
var heap = await Task.Run(() => NadekoStats.Instance.Heap()).ConfigureAwait(false);
await channel.SendMessageAsync($"`Heap Size:` {heap}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Heap Size:` {heap}").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "prune")
@ -647,7 +647,7 @@ namespace NadekoBot.Modules.Administration
return;
else if (!e.Server.CurrentUser.GetPermissions(e.Channel).ManageMessages)
{
await channel.SendMessageAsync("💢I don't have the permission to manage messages.");
await imsg.Channel.SendMessageAsync("💢I don't have the permission to manage messages.");
return;
}
int val;
@ -678,7 +678,7 @@ namespace NadekoBot.Modules.Administration
.AddCheck(SimpleCheckers.OwnerOnly())
.Do(async e =>
{
await channel.SendMessageAsync("`Shutting down.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Shutting down.`").ConfigureAwait(false);
await Task.Delay(2000).ConfigureAwait(false);
Environment.Exit(0);
});
@ -711,7 +711,7 @@ namespace NadekoBot.Modules.Administration
await client.CurrentUser.Edit("", avatar: image.ToStream()).ConfigureAwait(false);
// Send confirm.
await channel.SendMessageAsync("New avatar set.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("New avatar set.").ConfigureAwait(false);
// Save the image to disk.
image.Save("data/avatar.png", System.Drawing.Imaging.ImageFormat.Png);
@ -770,7 +770,7 @@ namespace NadekoBot.Modules.Administration
}
else
{
await channel.SendMessageAsync("`Invalid format.`");
await imsg.Channel.SendMessageAsync("`Invalid format.`");
}
});
@ -824,7 +824,7 @@ namespace NadekoBot.Modules.Administration
var donatorsOrdered = rows.OrderByDescending(d => d.Amount);
string str = $"**Thanks to the people listed below for making this project happen!**\n";
await channel.SendMessageAsync(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str + string.Join("⭐", donatorsOrdered.Select(d => d.UserName))).ConfigureAwait(false);
}).ConfigureAwait(false);
});
@ -848,7 +848,7 @@ namespace NadekoBot.Modules.Administration
UserName = donator.Name,
UserId = (long)donator.Id
});
channel.SendMessageAsync("Successfuly added a new donator. 👑").ConfigureAwait(false);
imsg.Channel.SendMessageAsync("Successfuly added a new donator. 👑").ConfigureAwait(false);
}
catch { }
}).ConfigureAwait(false);
@ -865,7 +865,7 @@ namespace NadekoBot.Modules.Administration
await ch.SendMessage(e.GetArg("msg")).ConfigureAwait(false);
}
await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":ok:").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "savechat")

View File

@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
if (!e.Server.CurrentUser.ServerPermissions.ManageRoles)
{
await channel.SendMessageAsync("I do not have the permission to manage roles.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("I do not have the permission to manage roles.").ConfigureAwait(false);
return;
}
var r = e.GetArg("role")?.Trim();
@ -52,19 +52,19 @@ namespace NadekoBot.Modules.Administration.Commands
{
config.AutoAssignedRole = 0;
await channel.SendMessageAsync("`Auto assign role on user join is now disabled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Auto assign role on user join is now disabled.`").ConfigureAwait(false);
return;
}
var role = e.Server.FindRoles(r).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync("💢 `Role not found.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 `Role not found.`").ConfigureAwait(false);
return;
}
config.AutoAssignedRole = role.Id;
await channel.SendMessageAsync("`Auto assigned role is set.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Auto assigned role is set.`").ConfigureAwait(false);
});
}

View File

@ -91,7 +91,7 @@ namespace NadekoBot.Modules.Administration.Commands
if (!Subscribers.TryGetValue(token, out set))
return;
set.Add(e.Channel);
await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":ok:").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "lcsc")
@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
subscriber.Value.Remove(e.Channel);
}
await channel.SendMessageAsync(":ok:").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":ok:").ConfigureAwait(false);
});
}
}

View File

@ -33,7 +33,7 @@ namespace NadekoBot.Modules.Administration.Commands
var message = e.GetArg("message")?.Trim();
if (string.IsNullOrWhiteSpace(message))
{
await channel.SendMessageAsync($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Incorrect command usage. See -h {Prefix}acr for correct formatting").ConfigureAwait(false);
return;
}
if (NadekoBot.Config.CustomReactions.ContainsKey(name))
@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Administration.Commands
else
NadekoBot.Config.CustomReactions.Add(name, new System.Collections.Generic.List<string>() { message });
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"Added {name} : {message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Added {name} : {message}").ConfigureAwait(false);
});
@ -69,12 +69,12 @@ namespace NadekoBot.Modules.Administration.Commands
var cmds = GetCustomsOnPage(num - 1);
if (!cmds.Any())
{
await channel.SendMessageAsync("`There are no custom reactions.`");
await imsg.Channel.SendMessageAsync("`There are no custom reactions.`");
}
else
{
string result = SearchHelper.ShowInPrettyCode<string>(cmds, s => $"{s,-25}"); //People prefer starting with 1
await channel.SendMessageAsync($"`Showing page {num}:`\n" + result).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Showing page {num}:`\n" + result).ConfigureAwait(false);
}
});
@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands
return;
if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{
await channel.SendMessageAsync("`Can't find that custom reaction.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Can't find that custom reaction.`").ConfigureAwait(false);
return;
}
var items = NadekoBot.Config.CustomReactions[name];
@ -101,7 +101,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
message.AppendLine($"[{i++}] " + Format.Code(Format.Escape(reaction)));
}
await channel.SendMessageAsync(message.ToString());
await imsg.Channel.SendMessageAsync(message.ToString());
});
cgb.CreateCommand(Prefix + "editcustreact")
@ -127,21 +127,21 @@ namespace NadekoBot.Modules.Administration.Commands
if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{
await channel.SendMessageAsync("`Could not find given commandname`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Could not find given commandname`").ConfigureAwait(false);
return;
}
int index;
if (!int.TryParse(indexstr, out index) || index < 1 || index > NadekoBot.Config.CustomReactions[name].Count)
{
await channel.SendMessageAsync("`Invalid index.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Invalid index.`").ConfigureAwait(false);
return;
}
index = index - 1;
NadekoBot.Config.CustomReactions[name][index] = msg;
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Edited response #{index + 1} from `{name}`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "delcustreact")
@ -157,7 +157,7 @@ namespace NadekoBot.Modules.Administration.Commands
return;
if (!NadekoBot.Config.CustomReactions.ContainsKey(name))
{
await channel.SendMessageAsync("Could not find given commandname").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Could not find given commandname").ConfigureAwait(false);
return;
}
string message = "";
@ -167,7 +167,7 @@ namespace NadekoBot.Modules.Administration.Commands
index = index - 1;
if (index < 0 || index > NadekoBot.Config.CustomReactions[name].Count)
{
await channel.SendMessageAsync("Given index was out of range").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Given index was out of range").ConfigureAwait(false);
return;
}
@ -184,7 +184,7 @@ namespace NadekoBot.Modules.Administration.Commands
message = $"Deleted custom reaction: `{name}`";
}
await Classes.JSONModels.ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync(message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(message).ConfigureAwait(false);
});
}

View File

@ -42,7 +42,7 @@ namespace NadekoBot.Modules.Administration.Commands
var usr = e.Message.MentionedUsers.FirstOrDefault(u => u != e.User);
if (usr?.Status != UserStatus.Offline)
return;
await channel.SendMessageAsync($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"User `{usr.Name}` is offline. PM sent.").ConfigureAwait(false);
await usr.SendMessage(
$"User `{e.User.Name}` mentioned you on " +
$"`{e.Server.Name}` server while you were offline.\n" +
@ -383,10 +383,10 @@ namespace NadekoBot.Modules.Administration.Commands
specificConfig.SendPrivateMessageOnMention =
!specificConfig.SendPrivateMessageOnMention;
if (specificConfig.SendPrivateMessageOnMention)
await channel.SendMessageAsync(":ok: I will send private messages " +
await imsg.Channel.SendMessageAsync(":ok: I will send private messages " +
"to mentioned offline users.").ConfigureAwait(false);
else
await channel.SendMessageAsync(":ok: I won't send private messages " +
await imsg.Channel.SendMessageAsync(":ok: I won't send private messages " +
"to mentioned offline users anymore.").ConfigureAwait(false);
});
@ -400,7 +400,7 @@ namespace NadekoBot.Modules.Administration.Commands
if (chId == null)
{
SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = e.Channel.Id;
await channel.SendMessageAsync($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"❗**I WILL BEGIN LOGGING SERVER ACTIVITY IN THIS CHANNEL**❗").ConfigureAwait(false);
return;
}
Channel ch;
@ -408,7 +408,7 @@ namespace NadekoBot.Modules.Administration.Commands
return;
SpecificConfigurations.Default.Of(e.Server.Id).LogServerChannel = null;
await channel.SendMessageAsync($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"❗**NO LONGER LOGGING IN {ch.Mention} CHANNEL**❗").ConfigureAwait(false);
});
@ -421,12 +421,12 @@ namespace NadekoBot.Modules.Administration.Commands
var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (config.LogserverIgnoreChannels.Remove(e.Channel.Id))
{
await channel.SendMessageAsync($"`{Prefix}logserver will stop ignoring this channel.`");
await imsg.Channel.SendMessageAsync($"`{Prefix}logserver will stop ignoring this channel.`");
}
else
{
config.LogserverIgnoreChannels.Add(e.Channel.Id);
await channel.SendMessageAsync($"`{Prefix}logserver will ignore this channel.`");
await imsg.Channel.SendMessageAsync($"`{Prefix}logserver will ignore this channel.`");
}
});
@ -439,11 +439,11 @@ namespace NadekoBot.Modules.Administration.Commands
if (chId == null)
{
SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = e.Channel.Id;
await channel.SendMessageAsync($"**User presence notifications enabled.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"**User presence notifications enabled.**").ConfigureAwait(false);
return;
}
SpecificConfigurations.Default.Of(e.Server.Id).LogPresenceChannel = null;
await channel.SendMessageAsync($"**User presence notifications disabled.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"**User presence notifications disabled.**").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "voicepresence")
@ -460,23 +460,23 @@ namespace NadekoBot.Modules.Administration.Commands
{
config.VoiceChannelLog.TryAdd(voiceChannel.Id, e.Channel.Id);
}
await channel.SendMessageAsync("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Started logging user presence for **ALL** voice channels!").ConfigureAwait(false);
return;
}
if (e.User.VoiceChannel == null)
{
await channel.SendMessageAsync("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 You are not in a voice channel right now. If you are, please rejoin it.").ConfigureAwait(false);
return;
}
ulong throwaway;
if (!config.VoiceChannelLog.TryRemove(e.User.VoiceChannel.Id, out throwaway))
{
config.VoiceChannelLog.TryAdd(e.User.VoiceChannel.Id, e.Channel.Id);
await channel.SendMessageAsync($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
}
else
await channel.SendMessageAsync($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Stopped logging user updates for` {e.User.VoiceChannel.Mention} `voice channel.`").ConfigureAwait(false);
});
}
}

View File

@ -64,7 +64,7 @@ namespace NadekoBot.Modules.Administration.Commands
Repeater rep;
if (!repeaters.TryGetValue(e.Server, out rep))
{
await channel.SendMessageAsync("`No repeating message found on this server.`");
await imsg.Channel.SendMessageAsync("`No repeating message found on this server.`");
return;
}
@ -90,13 +90,13 @@ namespace NadekoBot.Modules.Administration.Commands
if (!repeaters.TryRemove(e.Server, out rep))
return;
rep.MessageTimer.Stop();
await channel.SendMessageAsync("Repeating disabled").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Repeating disabled").ConfigureAwait(false);
return;
}
int minutes;
if (!int.TryParse(minutesStr, out minutes) || minutes < 1 || minutes > 1440)
{
await channel.SendMessageAsync("Invalid value").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Invalid value").ConfigureAwait(false);
return;
}
@ -117,7 +117,7 @@ namespace NadekoBot.Modules.Administration.Commands
repeater.MessageTimer.Stop();
repeater.MessageTimer.Start();
await channel.SendMessageAsync(String.Format("👌 Repeating `{0}` every " +
await imsg.Channel.SendMessageAsync(String.Format("👌 Repeating `{0}` every " +
"**{1}** minutes on {2} channel.",
repeater.RepeatingMessage, minutes, repeater.RepeatingChannel))
.ConfigureAwait(false);

View File

@ -89,7 +89,7 @@ namespace NadekoBot.Modules.Administration.Commands
finally {
playingPlaceholderLock.Release();
}
await channel.SendMessageAsync($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"❗`Rotating playing status has been {(timer.Enabled ? "enabled" : "disabled")}.`").ConfigureAwait(false);
};
internal override void Init(CommandGroupBuilder cgb)
@ -121,7 +121,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
playingPlaceholderLock.Release();
}
await channel.SendMessageAsync("🆗 `Added a new playing string.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🆗 `Added a new playing string.`").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "listplaying")
@ -131,14 +131,14 @@ namespace NadekoBot.Modules.Administration.Commands
.Do(async e =>
{
if (NadekoBot.Config.RotatingStatuses.Count == 0)
await channel.SendMessageAsync("`There are no playing strings. " +
await imsg.Channel.SendMessageAsync("`There are no playing strings. " +
"Add some with .addplaying [text] command.`").ConfigureAwait(false);
var sb = new StringBuilder();
for (var i = 0; i < NadekoBot.Config.RotatingStatuses.Count; i++)
{
sb.AppendLine($"`{i + 1}.` {NadekoBot.Config.RotatingStatuses[i]}");
}
await channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(sb.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "removeplaying")
@ -160,7 +160,7 @@ namespace NadekoBot.Modules.Administration.Commands
await ConfigHandler.SaveConfig().ConfigureAwait(false);
}
finally { playingPlaceholderLock.Release(); }
await channel.SendMessageAsync($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🆗 `Removed playing string #{num}`({str})").ConfigureAwait(false);
});
}
}

View File

@ -48,12 +48,12 @@ namespace NadekoBot.Modules.Administration.Commands
ConcurrentDictionary<ulong, DateTime> throwaway;
if (RatelimitingChannels.TryRemove(e.Channel.Id, out throwaway))
{
await channel.SendMessageAsync("Slow mode disabled.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Slow mode disabled.").ConfigureAwait(false);
return;
}
if (RatelimitingChannels.TryAdd(e.Channel.Id, new ConcurrentDictionary<ulong, DateTime>()))
{
await channel.SendMessageAsync("Slow mode initiated. " +
await imsg.Channel.SendMessageAsync("Slow mode initiated. " +
"Users can't send more than 1 message every 5 seconds.")
.ConfigureAwait(false);
}

View File

@ -40,7 +40,7 @@ namespace NadekoBot.Modules.Administration.Commands
msg.AppendLine($":ok:Role **{role.Name}** added to the list.");
}
}
await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "rsar")
@ -55,17 +55,17 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return;
}
var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{
await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return;
}
config.ListOfSelfAssignableRoles.Remove(role.Id);
await channel.SendMessageAsync($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":ok:**{role.Name}** has been removed from the list of self-assignable roles").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "lsar")
@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
config.ListOfSelfAssignableRoles.Remove(id);
}
await channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(msg.ToString()).ConfigureAwait(false);
});
@ -106,7 +106,7 @@ namespace NadekoBot.Modules.Administration.Commands
var config = SpecificConfigurations.Default.Of(e.Server.Id);
config.ExclusiveSelfAssignedRoles = !config.ExclusiveSelfAssignedRoles;
string exl = config.ExclusiveSelfAssignedRoles ? "exclusive" : "not exclusive";
await channel.SendMessageAsync("Self assigned roles are now " + exl);
await imsg.Channel.SendMessageAsync("Self assigned roles are now " + exl);
});
cgb.CreateCommand(Module.Prefix + "iam")
@ -122,24 +122,24 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return;
}
var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{
await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return;
}
if (e.User.HasRole(role))
{
await channel.SendMessageAsync($":anger:You already have {role.Name} role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":anger:You already have {role.Name} role.").ConfigureAwait(false);
return;
}
var sameRoles = e.User.Roles.Where(r => config.ListOfSelfAssignableRoles.Contains(r.Id));
if (config.ExclusiveSelfAssignedRoles && sameRoles.Any())
{
await channel.SendMessageAsync($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":anger:You already have {sameRoles.FirstOrDefault().Name} role.").ConfigureAwait(false);
return;
}
try
@ -151,10 +151,10 @@ namespace NadekoBot.Modules.Administration.Commands
}
catch (Exception ex)
{
await channel.SendMessageAsync($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":anger:`I am unable to add that role to you. I can't add roles to owners or other roles higher than my role in the role hierarchy.`").ConfigureAwait(false);
return;
}
var msg = await channel.SendMessageAsync($":ok:You now have {role.Name} role.").ConfigureAwait(false);
var msg = await imsg.Channel.SendMessageAsync($":ok:You now have {role.Name} role.").ConfigureAwait(false);
await Task.Delay(3000).ConfigureAwait(false);
await msg.Delete().ConfigureAwait(false);
try
@ -178,22 +178,22 @@ namespace NadekoBot.Modules.Administration.Commands
var role = e.Server.FindRoles(roleName).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role does not exist.").ConfigureAwait(false);
return;
}
var config = SpecificConfigurations.Default.Of(e.Server.Id);
if (!config.ListOfSelfAssignableRoles.Contains(role.Id))
{
await channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(":anger:That role is not self-assignable.").ConfigureAwait(false);
return;
}
if (!e.User.HasRole(role))
{
await channel.SendMessageAsync($":anger:You don't have {role.Name} role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":anger:You don't have {role.Name} role.").ConfigureAwait(false);
return;
}
await e.User.RemoveRoles(role).ConfigureAwait(false);
var msg = await channel.SendMessageAsync($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false);
var msg = await imsg.Channel.SendMessageAsync($":ok:Successfuly removed {role.Name} role from you.").ConfigureAwait(false);
await Task.Delay(3000).ConfigureAwait(false);
await msg.Delete().ConfigureAwait(false);
try

View File

@ -24,7 +24,7 @@ namespace NadekoBot.Modules.Administration.Commands
NadekoBot.Client.FindServers(arg).FirstOrDefault();
if (server == null)
{
await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
return;
}
if (!server.IsOwner)

View File

@ -226,9 +226,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleDelete())
await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been enabled.`").ConfigureAwait(false);
else
await channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Automatic deletion of greet and bye messages has been disabled.`").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "greet")
@ -239,9 +239,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleGreet(e.Channel.Id))
await channel.SendMessageAsync("Greet announcements enabled on this channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Greet announcements enabled on this channel.").ConfigureAwait(false);
else
await channel.SendMessageAsync("Greet announcements disabled.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Greet announcements disabled.").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "greetmsg")
@ -253,15 +253,15 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (string.IsNullOrWhiteSpace(e.GetArg("msg")))
{
await channel.SendMessageAsync("`Current greet message:` " + ann.GreetText);
await imsg.Channel.SendMessageAsync("`Current greet message:` " + ann.GreetText);
return;
}
ann.GreetText = e.GetArg("msg");
await channel.SendMessageAsync("New greet message set.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("New greet message set.").ConfigureAwait(false);
if (!ann.Greet)
await channel.SendMessageAsync("Enable greet messsages by typing `.greet`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Enable greet messsages by typing `.greet`").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "bye")
@ -272,9 +272,9 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleBye(e.Channel.Id))
await channel.SendMessageAsync("Bye announcements enabled on this channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Bye announcements enabled on this channel.").ConfigureAwait(false);
else
await channel.SendMessageAsync("Bye announcements disabled.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Bye announcements disabled.").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "byemsg")
@ -286,14 +286,14 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (string.IsNullOrWhiteSpace(e.GetArg("msg")))
{
await channel.SendMessageAsync("`Current bye message:` " + ann.ByeText);
await imsg.Channel.SendMessageAsync("`Current bye message:` " + ann.ByeText);
return;
}
ann.ByeText = e.GetArg("msg");
await channel.SendMessageAsync("New bye message set.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("New bye message set.").ConfigureAwait(false);
if (!ann.Bye)
await channel.SendMessageAsync("Enable bye messsages by typing `.bye`.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Enable bye messsages by typing `.bye`.").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "byepm")
@ -305,11 +305,11 @@ namespace NadekoBot.Modules.Administration.Commands
if (ann.ToggleByePM())
await channel.SendMessageAsync("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Bye messages will be sent in a PM from now on.\n ⚠ Keep in mind this might fail if the user and the bot have no common servers after the user leaves.").ConfigureAwait(false);
else
await channel.SendMessageAsync("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Bye messages will be sent in a bound channel from now on.").ConfigureAwait(false);
if (!ann.Bye)
await channel.SendMessageAsync("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Enable bye messsages by typing `.bye`, and set the bye message using `.byemsg`").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "greetpm")
@ -321,11 +321,11 @@ namespace NadekoBot.Modules.Administration.Commands
var ann = AnnouncementsDictionary.GetOrAdd(e.Server.Id, new AnnounceControls(e.Server.Id));
if (ann.ToggleGreetPM())
await channel.SendMessageAsync("Greet messages will be sent in a PM from now on.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Greet messages will be sent in a PM from now on.").ConfigureAwait(false);
else
await channel.SendMessageAsync("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Greet messages will be sent in a bound channel from now on.").ConfigureAwait(false);
if (!ann.Greet)
await channel.SendMessageAsync("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Enable greet messsages by typing `.greet`, and set the greet message using `.greetmsg`").ConfigureAwait(false);
});
}
}

View File

@ -95,7 +95,7 @@ namespace NadekoBot.Modules.Administration.Commands
{
if (!e.Server.CurrentUser.ServerPermissions.ManageChannels)
{
await channel.SendMessageAsync("`I have insufficient permission to do that.`");
await imsg.Channel.SendMessageAsync("`I have insufficient permission to do that.`");
return;
}
@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Administration.Commands
await Task.Delay(500);
}
await channel.SendMessageAsync("`Done.`");
await imsg.Channel.SendMessageAsync("`Done.`");
});
cgb.CreateCommand(Module.Prefix + "voice+text")
@ -139,24 +139,24 @@ namespace NadekoBot.Modules.Administration.Commands
}
catch
{
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
":anger: Error: Most likely i don't have permissions to do this.")
.ConfigureAwait(false);
return;
}
}
await channel.SendMessageAsync("Successfuly removed voice + text feature.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Successfuly removed voice + text feature.").ConfigureAwait(false);
return;
}
config.VoicePlusTextEnabled = true;
await channel.SendMessageAsync("Successfuly enabled voice + text feature. " +
await imsg.Channel.SendMessageAsync("Successfuly enabled voice + text feature. " +
"**Make sure the bot has manage roles and manage channels permissions**")
.ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync(ex.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(ex.ToString()).ConfigureAwait(false);
}
});
}

View File

@ -58,7 +58,7 @@ namespace NadekoBot.Modules.CustomReactions
commandFuncs.Keys.ForEach(key => str = key.Replace(str, m => commandFuncs[key](e, m)));
await channel.SendMessageAsync(str).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str).ConfigureAwait(false);
});
}
});

View File

@ -48,7 +48,7 @@ namespace NadekoBot.Modules.Gambling.Commands
if (userFlowers < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return;
}
@ -58,7 +58,7 @@ namespace NadekoBot.Modules.Gambling.Commands
AnimalRace ar;
if (!AnimalRaces.TryGetValue(e.Server.Id, out ar))
{
await channel.SendMessageAsync("No race exists on this server");
await imsg.Channel.SendMessageAsync("No race exists on this server");
return;
}
await ar.JoinRace(e.User, amount);

View File

@ -80,7 +80,7 @@ namespace NadekoBot.Modules.Gambling
arr[i] = r.Next(1, n2 + 1);
}
var elemCnt = 0;
await channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Rolled {n1} {(n1 == 1 ? "die" : "dice")} 1-{n2}.`\n`Result:` " + string.Join(", ", (ordered ? arr.OrderBy(x => x).AsEnumerable() : arr).Select(x => elemCnt++ % 2 == 0 ? $"**{x}**" : x.ToString()))).ConfigureAwait(false);
}
return;
}
@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Gambling
if (num < 1) num = 1;
if (num > 30)
{
await channel.SendMessageAsync("You can roll up to 30 dice at a time.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You can roll up to 30 dice at a time.").ConfigureAwait(false);
num = 30;
}
var dices = new List<Image>(num);
@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Gambling
}
var bitmap = dices.Merge();
await channel.SendMessageAsync(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(values.Count + " Dice rolled. Total: **" + values.Sum() + "** Average: **" + (values.Sum() / (1.0f * values.Count)).ToString("N2") + "**").ConfigureAwait(false);
await e.Channel.SendFile("dice.png", bitmap.ToStream(ImageFormat.Png)).ConfigureAwait(false);
}
catch
{
await channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Please enter a number of dice to roll.").ConfigureAwait(false);
}
};
}
@ -153,11 +153,11 @@ namespace NadekoBot.Modules.Gambling
rolled = new Random().Next(0, int.Parse(e.GetArg("range")) + 1);
}
await channel.SendMessageAsync($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} rolled **{rolled}**.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($":anger: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":anger: {ex.Message}").ConfigureAwait(false);
}
};
}

View File

@ -41,7 +41,7 @@ namespace NadekoBot.Modules.Gambling
return c;
});
await channel.SendMessageAsync("Deck reshuffled.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Deck reshuffled.").ConfigureAwait(false);
};
}
@ -68,7 +68,7 @@ namespace NadekoBot.Modules.Gambling
{
if (cards.CardPool.Count == 0 && i != 0)
{
await channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No more cards in a deck.").ConfigureAwait(false);
break;
}
var currentCard = cards.DrawACard();
@ -79,7 +79,7 @@ namespace NadekoBot.Modules.Gambling
await e.Channel.SendFile(images.Count + " cards.jpg", bitmap.ToStream()).ConfigureAwait(false);
if (cardObjects.Count == 5)
{
await channel.SendMessageAsync($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} `{Cards.GetHandValue(cardObjects)}`").ConfigureAwait(false);
}
}
catch (Exception ex)

View File

@ -47,7 +47,7 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return;
}
@ -75,7 +75,7 @@ namespace NadekoBot.Modules.Gambling
else
str = $"{e.User.Mention}`More luck next time.`";
await channel.SendMessageAsync(str).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str).ConfigureAwait(false);
};
public Func<CommandEventArgs, Task> FlipCoinFunc() => async e =>
@ -105,7 +105,7 @@ namespace NadekoBot.Modules.Gambling
await e.Channel.SendFile($"{result} coins.png", imgs.Merge().ToStream(System.Drawing.Imaging.ImageFormat.Png)).ConfigureAwait(false);
return;
}
await channel.SendMessageAsync("Invalid number").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Invalid number").ConfigureAwait(false);
}
};
}

View File

@ -41,13 +41,13 @@ namespace NadekoBot.Modules.Gambling
var role = e.Server.FindRoles(arg).FirstOrDefault();
if (role == null)
{
await channel.SendMessageAsync("💢 Role not found.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 Role not found.").ConfigureAwait(false);
return;
}
var members = role.Members.Where(u => u.Status == UserStatus.Online); // only online
var membersArray = members as User[] ?? members.ToArray();
var usr = membersArray[new Random().Next(0, membersArray.Length)];
await channel.SendMessageAsync($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"**Raffled user:** {usr.Name} (id: {usr.Id})").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "$$")
@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Gambling
var usr = e.Message.MentionedUsers.FirstOrDefault() ?? e.User;
var pts = GetUserFlowers(usr.Id);
var str = $"{usr.Name} has {pts} {NadekoBot.Config.CurrencySign}";
await channel.SendMessageAsync(str).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "give")
@ -83,14 +83,14 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return;
}
await FlowersHandler.RemoveFlowers(e.User, "Gift", (int)amount, true).ConfigureAwait(false);
await FlowersHandler.AddFlowersAsync(mentionedUser, "Gift", (int)amount).ConfigureAwait(false);
await channel.SendMessageAsync($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} successfully sent {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
});
@ -113,7 +113,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.AddFlowersAsync(mentionedUser, $"Awarded by bot owner. ({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false);
await channel.SendMessageAsync($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} successfully awarded {amount} {NadekoBot.Config.CurrencyName}s to {mentionedUser.Mention}!").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "take")
@ -135,7 +135,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.RemoveFlowers(mentionedUser, $"Taken by bot owner.({e.User.Name}/{e.User.Id})", (int)amount).ConfigureAwait(false);
await channel.SendMessageAsync($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} successfully took {amount} {NadekoBot.Config.CurrencyName}s from {mentionedUser.Mention}!").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "betroll")
@ -154,7 +154,7 @@ namespace NadekoBot.Modules.Gambling
if (userFlowers < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} You don't have enough {NadekoBot.Config.CurrencyName}s. You only have {userFlowers}{NadekoBot.Config.CurrencySign}.").ConfigureAwait(false);
return;
}
@ -181,7 +181,7 @@ namespace NadekoBot.Modules.Gambling
await FlowersHandler.AddFlowersAsync(e.User, "Betroll Gamble", amount * 10, true).ConfigureAwait(false);
}
await channel.SendMessageAsync(str).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str).ConfigureAwait(false);
});
@ -194,7 +194,7 @@ namespace NadekoBot.Modules.Gambling
var richest = richestTemp as CurrencyState[] ?? richestTemp.ToArray();
if (richest.Length == 0)
return;
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
richest.Aggregate(new StringBuilder(
$@"```xl

View File

@ -90,7 +90,7 @@ namespace NadekoBot.Modules.Games.Commands
UserPoints -= 3;
}
await channel.SendMessageAsync($"**ROUND {++round}**\n" +
await imsg.Channel.SendMessageAsync($"**ROUND {++round}**\n" +
$"{response}\n" +
$"{nadekoResponse}\n" +
$"--------------------------------\n" +
@ -100,11 +100,11 @@ namespace NadekoBot.Modules.Games.Commands
.ConfigureAwait(false);
if (round < 10) return;
if (nadekoPoints == userPoints)
await channel.SendMessageAsync("Its a draw").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Its a draw").ConfigureAwait(false);
else if (nadekoPoints > userPoints)
await channel.SendMessageAsync("Nadeko won.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Nadeko won.").ConfigureAwait(false);
else
await channel.SendMessageAsync("You won.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You won.").ConfigureAwait(false);
nadekoPoints = 0;
userPoints = 0;
round = 0;

View File

@ -93,7 +93,7 @@ namespace NadekoBot.Modules.Games.Commands
// {
// if (gameChannel != null)
// return;
// godMsg = await channel.SendMessageAsync("GAME START IN 1 SECOND....").ConfigureAwait(false);
// godMsg = await imsg.Channel.SendMessageAsync("GAME START IN 1 SECOND....").ConfigureAwait(false);
// gameChannel = e.Channel;
// players[0] = new BombermanPlayer
// {

View File

@ -310,7 +310,7 @@ namespace NadekoBot.Modules.Games.Commands
return;
if (string.IsNullOrWhiteSpace(text))
return;
await channel.SendMessageAsync(ToLeet(text, level)).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(ToLeet(text, level)).ConfigureAwait(false);
});
}
}

View File

@ -49,7 +49,7 @@ namespace NadekoBot.Modules.Games.Commands
var rnd = Math.Abs(rng.Next(0,101));
if (rnd == 0)
{
var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await channel.SendMessageAsync($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") };
var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await imsg.Channel.SendMessageAsync($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") };
plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; });
plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now);
}
@ -78,7 +78,7 @@ namespace NadekoBot.Modules.Games.Commands
await msgToDelete.Delete().ConfigureAwait(false);
await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false);
var msg = await channel.SendMessageAsync($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false);
var msg = await imsg.Channel.SendMessageAsync($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false);
ThreadPool.QueueUserWorkItem(async (state) =>
{
try
@ -99,24 +99,24 @@ namespace NadekoBot.Modules.Games.Commands
{
if (plantedFlowerChannels.ContainsKey(e.Channel.Id))
{
await channel.SendMessageAsync($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false);
return;
}
var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false);
if (!removed)
{
await channel.SendMessageAsync($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false);
return;
}
var file = GetRandomCurrencyImagePath();
Message msg;
if (file == null)
msg = await channel.SendMessageAsync(NadekoBot.Config.CurrencySign).ConfigureAwait(false);
msg = await imsg.Channel.SendMessageAsync(NadekoBot.Config.CurrencySign).ConfigureAwait(false);
else
msg = await e.Channel.SendFile(file).ConfigureAwait(false);
var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
var msg2 = await channel.SendMessageAsync($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false);
var msg2 = await imsg.Channel.SendMessageAsync($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false);
plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 });
}
finally { locker.Release(); }
@ -139,12 +139,12 @@ namespace NadekoBot.Modules.Games.Commands
int throwaway;
if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway))
{
await channel.SendMessageAsync("`Currency generation disabled on this channel.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Currency generation disabled on this channel.`").ConfigureAwait(false);
}
else
{
if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd))
await channel.SendMessageAsync($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false);
}
});
}

View File

@ -83,7 +83,7 @@ namespace NadekoBot.Modules.Games.Commands
var num = 1;
msgToSend = answers.Aggregate(msgToSend, (current, answ) => current + $"`{num++}.` **{answ}**\n");
msgToSend += "\n**Private Message me with the corresponding number of the answer.**";
await channel.SendMessageAsync(msgToSend).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(msgToSend).ConfigureAwait(false);
}
public async Task StopPoll(Channel ch)

View File

@ -114,7 +114,7 @@ namespace NadekoBot.Modules.Games.Commands
await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ CurrentSentence.Length / WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!").ConfigureAwait(false);
if (finishedUserIds.Count % 2 == 0)
{
await channel.SendMessageAsync($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{CurrentSentence}**:book:").ConfigureAwait(false);
}
}
}
@ -142,7 +142,7 @@ namespace NadekoBot.Modules.Games.Commands
if (game.IsActive)
{
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
$"Contest already running in " +
$"{game.Channell.Mention} channel.")
.ConfigureAwait(false);
@ -162,7 +162,7 @@ namespace NadekoBot.Modules.Games.Commands
await game.Stop().ConfigureAwait(false);
return;
}
await channel.SendMessageAsync("No contest to stop on this channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No contest to stop on this channel.").ConfigureAwait(false);
};
internal override void Init(CommandGroupBuilder cgb)
@ -188,7 +188,7 @@ namespace NadekoBot.Modules.Games.Commands
DateAdded = DateTime.Now
});
await channel.SendMessageAsync("Added new article for typing game.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Added new article for typing game.").ConfigureAwait(false);
});
}
}

View File

@ -37,12 +37,12 @@ namespace NadekoBot.Modules.Games.Commands
return;
var triviaGame = new TriviaGame(e, showHints, number == 0 ? 10 : number);
if (RunningTrivias.TryAdd(e.Server.Id, triviaGame))
await channel.SendMessageAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"**Trivia game started! {triviaGame.WinRequirement} points needed to win.**").ConfigureAwait(false);
else
await triviaGame.StopGame().ConfigureAwait(false);
}
else
await channel.SendMessageAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Trivia game is already running on this server.\n" + trivia.CurrentQuestion).ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "tl")
@ -51,9 +51,9 @@ namespace NadekoBot.Modules.Games.Commands
{
TriviaGame trivia;
if (RunningTrivias.TryGetValue(e.Server.Id, out trivia))
await channel.SendMessageAsync(trivia.GetLeaderboard()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(trivia.GetLeaderboard()).ConfigureAwait(false);
else
await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
});
cgb.CreateCommand(Module.Prefix + "tq")
@ -66,7 +66,7 @@ namespace NadekoBot.Modules.Games.Commands
await trivia.StopGame().ConfigureAwait(false);
}
else
await channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No trivia is running on this server.").ConfigureAwait(false);
});
}
}

View File

@ -46,7 +46,7 @@ namespace NadekoBot.Modules.Games
var list = arg.Split(';');
if (list.Count() < 2)
return;
await channel.SendMessageAsync(list[rng.Next(0, list.Length)]).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(list[rng.Next(0, list.Length)]).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "8ball")
@ -59,7 +59,7 @@ namespace NadekoBot.Modules.Games
return;
try
{
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
$":question: `Question` __**{question}**__ \n🎱 `8Ball Answers` __**{NadekoBot.Config._8BallResponses[rng.Next(0, NadekoBot.Config._8BallResponses.Length)]}**__")
.ConfigureAwait(false);
}
@ -103,7 +103,7 @@ namespace NadekoBot.Modules.Games
else
msg = $"{e.User.Mention} won! :{GetRPSPick(pick)}: beats :{GetRPSPick(nadekoPick)}:";
await channel.SendMessageAsync(msg).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(msg).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "linux")
@ -115,7 +115,7 @@ namespace NadekoBot.Modules.Games
var guhnoo = e.Args[0];
var loonix = e.Args[1];
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
$@"
I'd just like to interject for moment. What you're refering to as {loonix}, is in fact, {guhnoo}/{loonix}, or as I've recently taken to calling it, {guhnoo} plus {loonix}. {loonix} is not an operating system unto itself, but rather another free component of a fully functioning {guhnoo} system made useful by the {guhnoo} corelibs, shell utilities and vital system components comprising a full OS as defined by POSIX.

View File

@ -31,7 +31,7 @@ namespace NadekoBot.Classes.Help.Commands
if (alias != null)
str = $" / `{ com.Aliases.FirstOrDefault()}`";
if (com != null)
await channel.SendMessageAsync($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($@"**__Help for:__ `{com.Text}`**" + str + $"\n**Desc:** {new Regex(@"\|").Replace(com.Description, "\n**Usage:**", 1)}").ConfigureAwait(false);
}).ConfigureAwait(false);
};
public static string HelpString {
@ -91,7 +91,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: <http:
.Alias(Module.Prefix + "guide")
.Description($"Sends a readme and a guide links to the channel. | `{Prefix}readme` or `{Prefix}guide`")
.Do(async e =>
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
@"**Wiki with all info**: <https://github.com/Kwoth/NadekoBot/wiki>
**WINDOWS SETUP GUIDE**: <https://github.com/Kwoth/NadekoBot/blob/master/ComprehensiveGuide.md>
@ -105,7 +105,7 @@ $@"######For more information and how to setup your own NadekoBot, go to: <http:
.Description($"Instructions for helping the project! | `{Prefix}donate` or `~donate`")
.Do(async e =>
{
await channel.SendMessageAsync(
await imsg.Channel.SendMessageAsync(
$@"You can support the project on patreon. <https://patreon.com/nadekobot> or
You can send donations to `nadekodiscordbot@gmail.com`
Don't forget to leave your discord name or id in the message.

View File

@ -32,7 +32,7 @@ namespace NadekoBot.Modules.Help
.Description($"List all bot modules. | `{Prefix}modules` or `.modules`")
.Do(async e =>
{
await channel.SendMessageAsync("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService<ModuleService>().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`")
await imsg.Channel.SendMessageAsync("`List of modules:` \n• " + string.Join("\n• ", NadekoBot.Client.GetService<ModuleService>().Modules.Select(m => m.Name)) + $"\n`Type \"{Prefix}commands module_name\" to get a list of commands in that module.`")
.ConfigureAwait(false);
});
@ -52,20 +52,20 @@ namespace NadekoBot.Modules.Help
var cmdsArray = cmds as Command[] ?? cmds.ToArray();
if (!cmdsArray.Any())
{
await channel.SendMessageAsync("That module does not exist.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("That module does not exist.").ConfigureAwait(false);
return;
}
if (module != "customreactions" && module != "conversations")
{
await channel.SendMessageAsync("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode<Command>(cmdsArray,
await imsg.Channel.SendMessageAsync("`List Of Commands:`\n" + SearchHelper.ShowInPrettyCode<Command>(cmdsArray,
el => $"{el.Text,-15}{"[" + el.Aliases.FirstOrDefault() + "]",-8}"))
.ConfigureAwait(false);
}
else
{
await channel.SendMessageAsync("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}")));
await imsg.Channel.SendMessageAsync("`List Of Commands:`\n• " + string.Join("\n• ", cmdsArray.Select(c => $"{c.Text}")));
}
await channel.SendMessageAsync($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`You can type \"{Prefix}h command_name\" to see the help about that specific command.`").ConfigureAwait(false);
});
});
}

View File

@ -92,9 +92,9 @@ namespace NadekoBot.Modules.Music
return;
musicPlayer.TogglePause();
if (musicPlayer.Paused)
await channel.SendMessageAsync("🎵`Music Player paused.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎵`Music Player paused.`").ConfigureAwait(false);
else
await channel.SendMessageAsync("🎵`Music Player unpaused.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎵`Music Player unpaused.`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "queue")
@ -137,7 +137,7 @@ namespace NadekoBot.Modules.Music
MusicPlayer musicPlayer;
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
{
await channel.SendMessageAsync("🎵 No active music player.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎵 No active music player.").ConfigureAwait(false);
return;
}
@ -163,7 +163,7 @@ namespace NadekoBot.Modules.Music
const int itemsPerPage = 15;
int startAt = itemsPerPage * (page - 1);
var number = 1 + startAt;
await channel.SendMessageAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(toSend + string.Join("\n", musicPlayer.Playlist.Skip(startAt).Take(15).Select(v => $"`{number++}.` {v.PrettyName}"))).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "nowplaying")
@ -177,7 +177,7 @@ namespace NadekoBot.Modules.Music
var currentSong = musicPlayer.CurrentSong;
if (currentSong == null)
return;
await channel.SendMessageAsync($"🎵`Now Playing` {currentSong.PrettyName} " +
await imsg.Channel.SendMessageAsync($"🎵`Now Playing` {currentSong.PrettyName} " +
$"{currentSong.PrettyCurrentTime()}").ConfigureAwait(false);
});
@ -196,11 +196,11 @@ namespace NadekoBot.Modules.Music
int volume;
if (!int.TryParse(arg, out volume))
{
await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
return;
}
volume = musicPlayer.SetVolume(volume);
await channel.SendMessageAsync($"🎵 `Volume set to {volume}%`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵 `Volume set to {volume}%`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "defvol")
@ -214,12 +214,12 @@ namespace NadekoBot.Modules.Music
float volume;
if (!float.TryParse(arg, out volume) || volume < 0 || volume > 100)
{
await channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Volume number invalid.").ConfigureAwait(false);
return;
}
var conf = SpecificConfigurations.Default.Of(e.Server.Id);
conf.DefaultMusicVolume = volume / 100;
await channel.SendMessageAsync($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵 `Default volume set to {volume}%`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "mute")
@ -271,12 +271,12 @@ namespace NadekoBot.Modules.Music
return;
if (musicPlayer.Playlist.Count < 2)
{
await channel.SendMessageAsync("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 Not enough songs in order to perform the shuffle.").ConfigureAwait(false);
return;
}
musicPlayer.Shuffle();
await channel.SendMessageAsync("🎵 `Songs shuffled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎵 `Songs shuffled.`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "playlist")
@ -290,25 +290,25 @@ namespace NadekoBot.Modules.Music
return;
if (e.User.VoiceChannel?.Server != e.Server)
{
await channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
return;
}
var plId = await SearchHelper.GetPlaylistIdByKeyword(arg).ConfigureAwait(false);
if (plId == null)
{
await channel.SendMessageAsync("No search results for that query.");
await imsg.Channel.SendMessageAsync("No search results for that query.");
return;
}
var ids = await SearchHelper.GetVideoIDs(plId, 500).ConfigureAwait(false);
if (ids == null || ids.Count == 0)
{
await channel.SendMessageAsync($"🎵 `Failed to find any songs.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵 `Failed to find any songs.`").ConfigureAwait(false);
return;
}
var idArray = ids as string[] ?? ids.ToArray();
var count = idArray.Length;
var msg =
await channel.SendMessageAsync($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵 `Attempting to queue {count} songs".SnPl(count) + "...`").ConfigureAwait(false);
foreach (var id in idArray)
{
try
@ -383,7 +383,7 @@ namespace NadekoBot.Modules.Music
}
catch { }
}
await channel.SendMessageAsync("🎵 `Directory queue complete.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎵 `Directory queue complete.`").ConfigureAwait(false);
}
catch { }
});
@ -395,7 +395,7 @@ namespace NadekoBot.Modules.Music
{
if (e.User.VoiceChannel?.Server != e.Server)
{
await channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 You need to be in a voice channel on this server.\n If you are already in a voice channel, try rejoining it.").ConfigureAwait(false);
return;
}
await QueueSong(e.User, e.Channel, e.User.VoiceChannel, e.GetArg("radio_link"), musicType: MusicType.Radio).ConfigureAwait(false);
@ -448,7 +448,7 @@ namespace NadekoBot.Modules.Music
if (arg?.ToLower() == "all")
{
musicPlayer.ClearQueue();
await channel.SendMessageAsync($"🎵`Queue cleared!`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵`Queue cleared!`").ConfigureAwait(false);
return;
}
int num;
@ -460,7 +460,7 @@ namespace NadekoBot.Modules.Music
return;
var song = (musicPlayer.Playlist as List<Song>)?[num - 1];
musicPlayer.RemoveSongAt(num - 1);
await channel.SendMessageAsync($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵**Track {song.PrettyName} at position `#{num}` has been removed.**").ConfigureAwait(false);
});
//var msRegex = new Regex(@"(?<n1>\d+)>(?<n2>\d+)", RegexOptions.Compiled);
@ -487,7 +487,7 @@ namespace NadekoBot.Modules.Music
!int.TryParse(fromtoArr[1], out n2) || n1 < 1 || n2 < 1 || n1 == n2 ||
n1 > playlist.Count || n2 > playlist.Count)
{
await channel.SendMessageAsync("`Invalid input.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Invalid input.`").ConfigureAwait(false);
return;
}
@ -496,7 +496,7 @@ namespace NadekoBot.Modules.Music
var nn1 = n2 < n1 ? n1 : n1 - 1;
playlist.RemoveAt(nn1);
await channel.SendMessageAsync($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵`Moved` {s.PrettyName} `from #{n1} to #{n2}`").ConfigureAwait(false);
});
@ -520,7 +520,7 @@ namespace NadekoBot.Modules.Music
}
musicPlayer.MaxQueueSize = size;
await channel.SendMessageAsync($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`");
await imsg.Channel.SendMessageAsync($"🎵 `Max queue set to {(size == 0 ? ("unlimited") : size + " tracks")}`");
});
cgb.CreateCommand(Prefix + "cleanup")
@ -553,7 +553,7 @@ namespace NadekoBot.Modules.Music
if (currentSong == null)
return;
var currentValue = musicPlayer.ToggleRepeatSong();
await channel.SendMessageAsync(currentValue ?
await imsg.Channel.SendMessageAsync(currentValue ?
$"🎵🔂`Repeating track:`{currentSong.PrettyName}" :
$"🎵🔂`Current track repeat stopped.`")
.ConfigureAwait(false);
@ -568,7 +568,7 @@ namespace NadekoBot.Modules.Music
if (!MusicPlayers.TryGetValue(e.Server, out musicPlayer))
return;
var currentValue = musicPlayer.ToggleRepeatPlaylist();
await channel.SendMessageAsync($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵🔁`Repeat playlist {(currentValue ? "enabled" : "disabled")}`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "save")
@ -620,7 +620,7 @@ namespace NadekoBot.Modules.Music
SongInfoId = s.Id.Value
}), typeof(PlaylistSongInfo));
await channel.SendMessageAsync($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎵 `Saved playlist as {name}-{playlist.Id}`").ConfigureAwait(false);
});
@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Music
if (playlist == null)
{
await channel.SendMessageAsync("Can't find playlist under that name.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Can't find playlist under that name.").ConfigureAwait(false);
return;
}
@ -665,7 +665,7 @@ namespace NadekoBot.Modules.Music
var songInfos = psis.Select(psi => DbHandler.Instance
.FindOne<DataModels.SongInfo>(si => si.Id == psi.SongInfoId));
await channel.SendMessageAsync($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Attempting to load {songInfos.Count()} songs`").ConfigureAwait(false);
foreach (var si in songInfos)
{
try
@ -695,9 +695,9 @@ namespace NadekoBot.Modules.Music
return;
var result = DbHandler.Instance.GetPlaylistData(num);
if (result.Count == 0)
channel.SendMessageAsync($"`No saved playlists found on page {num}`").ConfigureAwait(false);
imsg.Channel.SendMessageAsync($"`No saved playlists found on page {num}`").ConfigureAwait(false);
else
channel.SendMessageAsync($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false);
imsg.Channel.SendMessageAsync($"```js\n--- List of saved playlists ---\n\n" + string.Join("\n", result.Select(r => $"'{r.Name}-{r.Id}' by {r.Creator} ({r.SongCnt} songs)")) + $"\n\n --- Page {num} ---```").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "deleteplaylist")
@ -714,7 +714,7 @@ namespace NadekoBot.Modules.Music
DbHandler.Instance.Delete<MusicPlaylist>(plnum);
else
DbHandler.Instance.DeleteWhere<MusicPlaylist>(mp => mp.Id == plnum && (long)e.User.Id == mp.CreatorId);
await channel.SendMessageAsync("`Ok.` :ok:").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`Ok.` :ok:").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "goto")
@ -751,7 +751,7 @@ namespace NadekoBot.Modules.Music
if (seconds.Length == 1)
seconds = "0" + seconds;
await channel.SendMessageAsync($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Skipped to {minutes}:{seconds}`").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "getlink")
@ -771,12 +771,12 @@ namespace NadekoBot.Modules.Music
var selSong = musicPlayer.Playlist.DefaultIfEmpty(null).ElementAtOrDefault(index - 1);
if (selSong == null)
{
await channel.SendMessageAsync("Could not select song, likely wrong index");
await imsg.Channel.SendMessageAsync("Could not select song, likely wrong index");
}
else
{
await channel.SendMessageAsync($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎶`Selected song {selSong.SongInfo.Title}:` <{selSong.SongInfo.Query}>").ConfigureAwait(false);
}
}
else
@ -784,7 +784,7 @@ namespace NadekoBot.Modules.Music
var curSong = musicPlayer.CurrentSong;
if (curSong == null)
return;
await channel.SendMessageAsync($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"🎶`Current song:` <{curSong.SongInfo.Query}>").ConfigureAwait(false);
}
});
@ -800,9 +800,9 @@ namespace NadekoBot.Modules.Music
return;
if (!musicPlayer.ToggleAutoplay())
await channel.SendMessageAsync("🎶`Autoplay disabled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎶`Autoplay disabled.`").ConfigureAwait(false);
else
await channel.SendMessageAsync("🎶`Autoplay enabled.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("🎶`Autoplay enabled.`").ConfigureAwait(false);
});
});
}

View File

@ -72,7 +72,7 @@ namespace NadekoBot.Modules.Permissions.Commands
? e.Channel
: PermissionHelper.ValidateChannel(e.Server, chanStr);
await PermissionsHandler.SetChannelFilterInvitesPermission(chan, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.")
await imsg.Channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.")
.ConfigureAwait(false);
return;
}
@ -82,13 +82,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{
await PermissionsHandler.SetChannelFilterInvitesPermission(curChannel, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.")
await imsg.Channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.")
.ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}")
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}")
.ConfigureAwait(false);
}
});
@ -103,13 +103,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerFilterInvitesPermission(e.Server, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.")
await imsg.Channel.SendMessageAsync($"Invite Filter has been **{(state ? "enabled" : "disabled")}** for this server.")
.ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
}

View File

@ -69,7 +69,7 @@ namespace NadekoBot.Modules.Permissions.Commands
? e.Channel
: PermissionHelper.ValidateChannel(e.Server, chanStr);
await PermissionsHandler.SetChannelWordPermission(chan, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **{chan.Name}** channel.").ConfigureAwait(false);
return;
}
//all channels
@ -78,11 +78,11 @@ namespace NadekoBot.Modules.Permissions.Commands
{
await PermissionsHandler.SetChannelWordPermission(curChannel, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** for **ALL** channels.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
@ -99,12 +99,12 @@ namespace NadekoBot.Modules.Permissions.Commands
if (string.IsNullOrWhiteSpace(word))
return;
await PermissionsHandler.AddFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully added new filtered word.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully added new filtered word.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
@ -121,12 +121,12 @@ namespace NadekoBot.Modules.Permissions.Commands
if (string.IsNullOrWhiteSpace(word))
return;
await PermissionsHandler.RemoveFilteredWord(e.Server, word.ToLowerInvariant().Trim()).ConfigureAwait(false);
await channel.SendMessageAsync($"Successfully removed filtered word.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Successfully removed filtered word.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
@ -141,12 +141,12 @@ namespace NadekoBot.Modules.Permissions.Commands
Classes.ServerPermissions serverPerms;
if (!PermissionsHandler.PermissionsDict.TryGetValue(e.Server.Id, out serverPerms))
return;
await channel.SendMessageAsync($"There are `{serverPerms.Words.Count}` filtered words.\n" +
await imsg.Channel.SendMessageAsync($"There are `{serverPerms.Words.Count}` filtered words.\n" +
string.Join("\n", serverPerms.Words)).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
@ -160,13 +160,13 @@ namespace NadekoBot.Modules.Permissions.Commands
{
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerWordPermission(e.Server, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.")
await imsg.Channel.SendMessageAsync($"Word filtering has been **{(state ? "enabled" : "disabled")}** on this server.")
.ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢 Error: {ex.Message}").ConfigureAwait(false);
}
});
}

View File

@ -39,7 +39,7 @@ namespace NadekoBot.Modules.Permissions
{
if (string.IsNullOrWhiteSpace(e.GetArg("role")))
{
await channel.SendMessageAsync($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Current permissions role is `{PermissionsHandler.GetServerPermissionsRoleName(e.Server)}`").ConfigureAwait(false);
return;
}
@ -52,11 +52,11 @@ namespace NadekoBot.Modules.Permissions
catch (Exception ex)
{
Console.WriteLine(ex.Message);
await channel.SendMessageAsync($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Role `{arg}` probably doesn't exist. Create the role with that name first.").ConfigureAwait(false);
return;
}
await PermissionsHandler.SetPermissionsRole(e.Server, role.Name).ConfigureAwait(false);
await channel.SendMessageAsync($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Role `{role.Name}` is now required in order to change permissions.").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "rolepermscopy")
@ -71,7 +71,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2)
{
await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
return;
}
try
@ -80,11 +80,11 @@ namespace NadekoBot.Modules.Permissions
var toRole = PermissionHelper.ValidateRole(e.Server, args[1]);
await PermissionsHandler.CopyRolePermissions(fromRole, toRole).ConfigureAwait(false);
await channel.SendMessageAsync($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Copied permission settings from **{fromRole.Name}** to **{toRole.Name}**.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢{ex.Message}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"💢{ex.Message}").ConfigureAwait(false);
}
});
cgb.CreateCommand(Prefix + "chnlpermscopy")
@ -99,7 +99,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2)
{
await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.");
await imsg.Channel.SendMessageAsync("💢Invalid number of '~'s in the argument.");
return;
}
try
@ -108,11 +108,11 @@ namespace NadekoBot.Modules.Permissions
var toChannel = PermissionHelper.ValidateChannel(e.Server, args[1]);
await PermissionsHandler.CopyChannelPermissions(fromChannel, toChannel).ConfigureAwait(false);
await channel.SendMessageAsync($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Copied permission settings from **{fromChannel.Name}** to **{toChannel.Name}**.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢{ex.Message}");
await imsg.Channel.SendMessageAsync($"💢{ex.Message}");
}
});
cgb.CreateCommand(Prefix + "usrpermscopy")
@ -127,7 +127,7 @@ namespace NadekoBot.Modules.Permissions
var args = arg.Split('~').Select(a => a.Trim()).ToArray();
if (args.Length > 2)
{
await channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢Invalid number of '~'s in the argument.").ConfigureAwait(false);
return;
}
try
@ -136,11 +136,11 @@ namespace NadekoBot.Modules.Permissions
var toUser = PermissionHelper.ValidateUser(e.Server, args[1]);
await PermissionsHandler.CopyUserPermissions(fromUser, toUser).ConfigureAwait(false);
await channel.SendMessageAsync($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Copied permission settings from **{fromUser.ToString()}**to * *{toUser.ToString()}**.").ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync($"💢{ex.Message}");
await imsg.Channel.SendMessageAsync($"💢{ex.Message}");
}
});
@ -153,7 +153,7 @@ namespace NadekoBot.Modules.Permissions
var arg = e.GetArg("arg");
var val = PermissionHelper.ValidateBool(arg);
await PermissionsHandler.SetVerbosity(e.Server, val).ConfigureAwait(false);
await channel.SendMessageAsync($"Verbosity set to {val}.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Verbosity set to {val}.").ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "srvrperms")
@ -163,8 +163,8 @@ namespace NadekoBot.Modules.Permissions
{
var perms = PermissionsHandler.GetServerPermissions(e.Server);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await channel.SendMessageAsync("No permissions set for this server.").ConfigureAwait(false);
await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No permissions set for this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "roleperms")
@ -182,15 +182,15 @@ namespace NadekoBot.Modules.Permissions
}
catch (Exception ex)
{
await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return;
}
var perms = PermissionsHandler.GetRolePermissionsById(e.Server, role.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await channel.SendMessageAsync($"No permissions set for **{role.Name}** role.").ConfigureAwait(false);
await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"No permissions set for **{role.Name}** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "chnlperms")
@ -208,14 +208,14 @@ namespace NadekoBot.Modules.Permissions
}
catch (Exception ex)
{
await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return;
}
var perms = PermissionsHandler.GetChannelPermissionsById(e.Server, channel.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await channel.SendMessageAsync($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false);
await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"No permissions set for **{channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "userperms")
@ -232,14 +232,14 @@ namespace NadekoBot.Modules.Permissions
}
catch (Exception ex)
{
await channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("💢 Error: " + ex.Message).ConfigureAwait(false);
return;
}
var perms = PermissionsHandler.GetUserPermissionsById(e.Server, user.Id);
if (string.IsNullOrWhiteSpace(perms?.ToString()))
await channel.SendMessageAsync($"No permissions set for user **{user.Name}**.").ConfigureAwait(false);
await channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"No permissions set for user **{user.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(perms.ToString()).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "srvrmdl")
@ -255,15 +255,15 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerModulePermission(e.Server, module, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -279,15 +279,15 @@ namespace NadekoBot.Modules.Permissions
var state = PermissionHelper.ValidateBool(e.GetArg("bool"));
await PermissionsHandler.SetServerCommandPermission(e.Server, command, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -309,23 +309,23 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
}
else
{
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
await PermissionsHandler.SetRoleModulePermission(role, module, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
}
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -347,23 +347,23 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **ALL** roles.").ConfigureAwait(false);
}
else
{
var role = PermissionHelper.ValidateRole(e.Server, e.GetArg("role"));
await PermissionsHandler.SetRoleCommandPermission(role, command, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
}
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -385,28 +385,28 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
}
else if (string.IsNullOrWhiteSpace(channelArg))
{
await PermissionsHandler.SetChannelModulePermission(e.Channel, module, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{e.Channel.Name}** channel.").ConfigureAwait(false);
}
else
{
var channel = PermissionHelper.ValidateChannel(e.Server, channelArg);
await PermissionsHandler.SetChannelModulePermission(channel, module, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
}
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -428,23 +428,23 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** on **ALL** channels.").ConfigureAwait(false);
}
else
{
var channel = PermissionHelper.ValidateChannel(e.Server, e.GetArg("channel"));
await PermissionsHandler.SetChannelCommandPermission(channel, command, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
}
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -462,15 +462,15 @@ namespace NadekoBot.Modules.Permissions
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
await PermissionsHandler.SetUserModulePermission(user, module, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Module **{module}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -488,15 +488,15 @@ namespace NadekoBot.Modules.Permissions
var user = PermissionHelper.ValidateUser(e.Server, e.GetArg("user"));
await PermissionsHandler.SetUserCommandPermission(user, command, state).ConfigureAwait(false);
await channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has been **{(state ? "enabled" : "disabled")}** for user **{user.Name}**.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -513,15 +513,15 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetServerModulePermission(e.Server, module.Name, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -540,15 +540,15 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetServerCommandPermission(e.Server, command.Text, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** on this server.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -568,15 +568,15 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetChannelModulePermission(channel, module.Name, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -596,15 +596,15 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetChannelCommandPermission(channel, command.Text, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{channel.Name}** channel.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -623,15 +623,15 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetRoleModulePermission(role, module.Name, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All modules have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -655,7 +655,7 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false);
}
}
await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **all roles** role.").ConfigureAwait(false);
}
else
{
@ -665,16 +665,16 @@ namespace NadekoBot.Modules.Permissions
{
await PermissionsHandler.SetRoleCommandPermission(role, command.Text, state).ConfigureAwait(false);
}
await channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"All commands from the **{module}** module have been **{(state ? "enabled" : "disabled")}** for **{role.Name}** role.").ConfigureAwait(false);
}
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -690,7 +690,7 @@ namespace NadekoBot.Modules.Permissions
var usr = e.Message.MentionedUsers.First();
NadekoBot.Config.UserBlacklist.Add(usr.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Sucessfully blacklisted user {usr.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false);
});
@ -708,11 +708,11 @@ namespace NadekoBot.Modules.Permissions
{
NadekoBot.Config.UserBlacklist.Remove(usr.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Sucessfully unblacklisted user {usr.Name}`").ConfigureAwait(false);
}
else
{
await channel.SendMessageAsync($"`{usr.Name} was not in blacklist`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`{usr.Name} was not in blacklist`").ConfigureAwait(false);
}
}).ConfigureAwait(false);
});
@ -728,7 +728,7 @@ namespace NadekoBot.Modules.Permissions
var ch = e.Message.MentionedChannels.First();
NadekoBot.Config.UserBlacklist.Add(ch.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false);
});
@ -743,7 +743,7 @@ namespace NadekoBot.Modules.Permissions
var ch = e.Message.MentionedChannels.First();
NadekoBot.Config.UserBlacklist.Remove(ch.Id);
await ConfigHandler.SaveConfig().ConfigureAwait(false);
await channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Sucessfully blacklisted channel {ch.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false);
});
@ -762,7 +762,7 @@ namespace NadekoBot.Modules.Permissions
NadekoBot.Client.FindServers(arg.Trim()).FirstOrDefault();
if (server == null)
{
await channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Cannot find that server").ConfigureAwait(false);
return;
}
var serverId = server.Id;
@ -774,7 +774,7 @@ namespace NadekoBot.Modules.Permissions
TypingGame typeracer;
SpeedTyping.RunningContests.TryRemove(serverId, out typeracer);
await channel.SendMessageAsync($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"`Sucessfully blacklisted server {server.Name}`").ConfigureAwait(false);
}).ConfigureAwait(false);
});
@ -797,17 +797,17 @@ namespace NadekoBot.Modules.Permissions
await PermissionsHandler.SetCommandCooldown(e.Server, command, secs).ConfigureAwait(false);
if(secs == 0)
await channel.SendMessageAsync($"Command **{command}** has no coooldown now.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** has no coooldown now.").ConfigureAwait(false);
else
await channel.SendMessageAsync($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Command **{command}** now has a **{secs} {(secs==1 ? "second" : "seconds")}** cooldown.").ConfigureAwait(false);
}
catch (ArgumentException exArg)
{
await channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(exArg.Message).ConfigureAwait(false);
}
catch (Exception ex)
{
await channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Something went terribly wrong - " + ex.Message).ConfigureAwait(false);
}
});
@ -823,10 +823,10 @@ namespace NadekoBot.Modules.Permissions
if (!perms.CommandCooldowns.Any())
{
await channel.SendMessageAsync("`No command cooldowns set.`").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("`No command cooldowns set.`").ConfigureAwait(false);
return;
}
await channel.SendMessageAsync(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(SearchHelper.ShowInPrettyCode(perms.CommandCooldowns.Select(c=>c.Key+ ": "+c.Value+" secs"),s=>$"{s,-30}",2)).ConfigureAwait(false);
});
});
}

View File

@ -92,12 +92,12 @@ namespace NadekoBot.Modules.Pokemon
var target = e.Server.FindUsers(targetStr).FirstOrDefault();
if (target == null)
{
await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return;
}
else if (target == e.User)
{
await channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("You can't attack yourself.").ConfigureAwait(false);
return;
}
// Checking stats first, then move
@ -109,17 +109,17 @@ namespace NadekoBot.Modules.Pokemon
//User not able if HP < 0, has made more than 4 attacks
if (userStats.Hp < 0)
{
await channel.SendMessageAsync($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} has fainted and was not able to move!").ConfigureAwait(false);
return;
}
if (userStats.MovesMade >= 5)
{
await channel.SendMessageAsync($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} has used too many moves in a row and was not able to move!").ConfigureAwait(false);
return;
}
if (userStats.LastAttacked.Contains(target.Id))
{
await channel.SendMessageAsync($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} can't attack again without retaliation!").ConfigureAwait(false);
return;
}
//get target stats
@ -129,7 +129,7 @@ namespace NadekoBot.Modules.Pokemon
//If target's HP is below 0, no use attacking
if (targetStats.Hp <= 0)
{
await channel.SendMessageAsync($"{target.Mention} has already fainted!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{target.Mention} has already fainted!").ConfigureAwait(false);
return;
}
@ -139,7 +139,7 @@ namespace NadekoBot.Modules.Pokemon
var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
{
await channel.SendMessageAsync($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} was not able to use **{move}**, use `{Prefix}ml` to see moves you can use").ConfigureAwait(false);
return;
}
@ -191,7 +191,7 @@ namespace NadekoBot.Modules.Pokemon
Stats[e.User.Id] = userStats;
Stats[target.Id] = targetStats;
await channel.SendMessageAsync(response).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(response).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "movelist")
@ -206,7 +206,7 @@ namespace NadekoBot.Modules.Pokemon
{
str += $"\n{userType.Icon}{m}";
}
await channel.SendMessageAsync(str).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync(str).ConfigureAwait(false);
});
cgb.CreateCommand(Prefix + "heal")
@ -220,7 +220,7 @@ namespace NadekoBot.Modules.Pokemon
var usr = e.Server.FindUsers(targetStr).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return;
}
if (Stats.ContainsKey(usr.Id))
@ -230,7 +230,7 @@ namespace NadekoBot.Modules.Pokemon
int HP = targetStats.Hp;
if (targetStats.Hp == targetStats.MaxHp)
{
await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
return;
}
//Payment~
@ -238,7 +238,7 @@ namespace NadekoBot.Modules.Pokemon
var pts = Classes.DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
return;
}
var target = (usr.Id == e.User.Id) ? "yourself" : usr.Name;
@ -249,16 +249,16 @@ namespace NadekoBot.Modules.Pokemon
{
//Could heal only for half HP?
Stats[usr.Id].Hp = (targetStats.MaxHp / 2);
await channel.SendMessageAsync($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Name} revived {usr.Name} with one {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
return;
}
var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
await channel.SendMessageAsync($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Name} healed {usr.Name} for {targetStats.MaxHp - HP} HP with {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
return;
}
else
{
await channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{usr.Name} already has full HP!").ConfigureAwait(false);
}
});
@ -273,11 +273,11 @@ namespace NadekoBot.Modules.Pokemon
var usr = e.Server.FindUsers(usrStr).FirstOrDefault();
if (usr == null)
{
await channel.SendMessageAsync("No such person.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("No such person.").ConfigureAwait(false);
return;
}
var pType = GetPokeType(usr.Id);
await channel.SendMessageAsync($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Type of {usr.Name} is **{pType.Name.ToLowerInvariant()}**{pType.Icon}").ConfigureAwait(false);
});
@ -292,12 +292,12 @@ namespace NadekoBot.Modules.Pokemon
var targetType = stringToPokemonType(targetTypeStr);
if (targetType == null)
{
await channel.SendMessageAsync("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Invalid type specified. Type must be one of:\n" + string.Join(", ", NadekoBot.Config.PokemonTypes.Select(t => t.Name.ToUpperInvariant()))).ConfigureAwait(false);
return;
}
if (targetType == GetPokeType(e.User.Id))
{
await channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Your type is already {targetType.Name.ToLowerInvariant()}{targetType.Icon}").ConfigureAwait(false);
return;
}
@ -306,7 +306,7 @@ namespace NadekoBot.Modules.Pokemon
var pts = DbHandler.Instance.GetStateByUserId((long)e.User.Id)?.Value ?? 0;
if (pts < amount)
{
await channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"{e.User.Mention} you don't have enough {NadekoBot.Config.CurrencyName}s! \nYou still need {amount - pts} {NadekoBot.Config.CurrencySign} to be able to do this!").ConfigureAwait(false);
return;
}
await FlowersHandler.RemoveFlowers(e.User, $"set usertype to {targetTypeStr}", amount).ConfigureAwait(false);
@ -327,7 +327,7 @@ namespace NadekoBot.Modules.Pokemon
//Now for the response
await channel.SendMessageAsync($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync($"Set type of {e.User.Mention} to {targetTypeStr}{targetType.Icon} for a {NadekoBot.Config.CurrencySign}").ConfigureAwait(false);
});
});
}

View File

@ -82,7 +82,7 @@ namespace NadekoBot.Modules.Trello
bound = e.Channel;
board = new Board(e.GetArg("board_id").Trim());
board.Refresh();
await channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name);
await imsg.Channel.SendMessageAsync("Successfully bound to this channel and board " + board.Name);
t.Start();
}
catch (Exception ex)
@ -100,7 +100,7 @@ namespace NadekoBot.Modules.Trello
t.Stop();
bound = null;
board = null;
await channel.SendMessageAsync("Successfully unbound trello from this channel.").ConfigureAwait(false);
await imsg.Channel.SendMessageAsync("Successfully unbound trello from this channel.").ConfigureAwait(false);
});
@ -111,7 +111,7 @@ namespace NadekoBot.Modules.Trello
{
if (!NadekoBot.IsOwner(e.User.Id)) return;
if (bound == null || board == null || bound != e.Channel) return;
await channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")))
await imsg.Channel.SendMessageAsync("Lists for a board '" + board.Name + "'\n" + string.Join("\n", board.Lists.Select(l => "**• " + l.ToString() + "**")))
.ConfigureAwait(false);
});
@ -133,10 +133,10 @@ namespace NadekoBot.Modules.Trello
if (list != null)
await channel.SendMessageAsync("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**")))
await imsg.Channel.SendMessageAsync("There are " + list.Cards.Count() + " cards in a **" + list.Name + "** list\n" + string.Join("\n", list.Cards.Select(c => "**• " + c.ToString() + "**")))
.ConfigureAwait(false);
else
await channel.SendMessageAsync("No such list.")
await imsg.Channel.SendMessageAsync("No such list.")
.ConfigureAwait(false);
});
});

View File

@ -17,7 +17,9 @@
"Microsoft.Extensions.DependencyInjection": "1.0.0",
"Discord.Net": "1.0.0-dev",
"Discord.Net.Commands": "1.0.0-dev",
"System.Resources.ResourceWriter": "4.0.0-beta-22816"
"System.Resources.ResourceWriter": "4.0.0-beta-22816",
"Google.Apis.YouTube.v3": "1.15.0.582",
"System.Diagnostics.Contracts": "4.0.1"
},
"frameworks": {

View File

@ -3,6 +3,104 @@
"version": 2,
"targets": {
".NETCoreApp,Version=v1.0": {
"Google.Apis/1.15.0": {
"type": "package",
"dependencies": {
"Google.Apis.Core": "1.15.0",
"System.Collections": "4.0.11",
"System.Diagnostics.Debug": "4.0.11",
"System.IO": "4.1.0",
"System.IO.Compression": "4.1.0",
"System.Linq": "4.1.0",
"System.Net.Http": "4.1.0",
"System.Net.Primitives": "4.0.11",
"System.Reflection": "4.1.0",
"System.Reflection.TypeExtensions": "4.1.0",
"System.Runtime": "4.1.0",
"System.Runtime.Extensions": "4.1.0",
"System.Text.Encoding": "4.0.11",
"System.Threading": "4.0.11",
"System.Threading.Tasks": "4.0.11"
},
"compile": {
"lib/netstandard1.3/Google.Apis.dll": {}
},
"runtime": {
"lib/netstandard1.3/Google.Apis.dll": {}
}
},
"Google.Apis.Auth/1.15.0": {
"type": "package",
"dependencies": {
"Google.Apis.Core": "1.15.0",
"Newtonsoft.Json": "9.0.1",
"Portable.BouncyCastle": "1.8.1.1",
"System.Collections": "4.0.11",
"System.Console": "4.0.0",
"System.Diagnostics.Debug": "4.0.11",
"System.Diagnostics.Process": "4.1.0",
"System.IO": "4.1.0",
"System.IO.FileSystem": "4.0.1",
"System.IO.FileSystem.Primitives": "4.0.1",
"System.Linq": "4.1.0",
"System.Net.Http": "4.1.0",
"System.Net.Primitives": "4.0.11",
"System.Net.Requests": "4.0.11",
"System.Runtime": "4.1.0",
"System.Runtime.Extensions": "4.1.0",
"System.Text.Encoding": "4.0.11",
"System.Threading": "4.0.11",
"System.Threading.Tasks": "4.0.11"
},
"compile": {
"lib/netstandard1.3/Google.Apis.Auth.PlatformServices.dll": {},
"lib/netstandard1.3/Google.Apis.Auth.dll": {}
},
"runtime": {
"lib/netstandard1.3/Google.Apis.Auth.PlatformServices.dll": {},
"lib/netstandard1.3/Google.Apis.Auth.dll": {}
}
},
"Google.Apis.Core/1.15.0": {
"type": "package",
"dependencies": {
"Newtonsoft.Json": "9.0.1",
"System.Collections": "4.0.11",
"System.Diagnostics.Debug": "4.0.11",
"System.Globalization": "4.0.11",
"System.IO": "4.1.0",
"System.Linq": "4.1.0",
"System.Net.Http": "4.1.0",
"System.Net.Primitives": "4.0.11",
"System.Reflection": "4.1.0",
"System.Reflection.Extensions": "4.0.1",
"System.Reflection.TypeExtensions": "4.1.0",
"System.Runtime": "4.1.0",
"System.Runtime.Extensions": "4.1.0",
"System.Text.RegularExpressions": "4.1.0",
"System.Threading": "4.0.11",
"System.Threading.Tasks": "4.0.11"
},
"compile": {
"lib/netstandard1.3/Google.Apis.Core.dll": {}
},
"runtime": {
"lib/netstandard1.3/Google.Apis.Core.dll": {}
}
},
"Google.Apis.YouTube.v3/1.15.0.582": {
"type": "package",
"dependencies": {
"Google.Apis": "1.15.0",
"Google.Apis.Auth": "1.15.0"
},
"compile": {
"lib/netstandard1.3/Google.Apis.YouTube.v3.dll": {}
},
"runtime": {
"lib/netstandard1.3/Google.Apis.YouTube.v3.dll": {}
}
},
"Libuv/1.9.0": {
"type": "package",
"dependencies": {
@ -323,7 +421,11 @@
"ref/netstandard1.3/_._": {}
},
"runtimeTargets": {
"runtimes/win/lib/netstandard1.3/_._": {
"runtimes/unix/lib/netstandard1.3/Microsoft.Win32.Registry.dll": {
"assetType": "runtime",
"rid": "unix"
},
"runtimes/win/lib/netstandard1.3/Microsoft.Win32.Registry.dll": {
"assetType": "runtime",
"rid": "win"
}
@ -411,6 +513,31 @@
"lib/netstandard1.0/Newtonsoft.Json.dll": {}
}
},
"Portable.BouncyCastle/1.8.1.1": {
"type": "package",
"dependencies": {
"System.Collections": "4.0.11",
"System.Diagnostics.Debug": "4.0.11",
"System.Globalization": "4.0.11",
"System.IO": "4.1.0",
"System.IO.FileSystem": "4.0.1",
"System.IO.FileSystem.Primitives": "4.0.1",
"System.Linq": "4.1.0",
"System.Reflection": "4.1.0",
"System.Reflection.Extensions": "4.0.1",
"System.Runtime": "4.1.0",
"System.Runtime.Extensions": "4.1.0",
"System.Text.Encoding": "4.0.11",
"System.Threading": "4.0.11",
"System.Threading.Tasks": "4.0.11"
},
"compile": {
"lib/netstandard1.3/crypto.dll": {}
},
"runtime": {
"lib/netstandard1.3/crypto.dll": {}
}
},
"runtime.native.System/4.0.0": {
"type": "package",
"dependencies": {
@ -602,6 +729,18 @@
"ref/netstandard1.3/System.Console.dll": {}
}
},
"System.Diagnostics.Contracts/4.0.1": {
"type": "package",
"dependencies": {
"System.Runtime": "4.1.0"
},
"compile": {
"ref/netstandard1.0/System.Diagnostics.Contracts.dll": {}
},
"runtime": {
"lib/netstandard1.0/System.Diagnostics.Contracts.dll": {}
}
},
"System.Diagnostics.Debug/4.0.11": {
"type": "package",
"dependencies": {
@ -681,9 +820,17 @@
"ref/netstandard1.4/System.Diagnostics.Process.dll": {}
},
"runtimeTargets": {
"runtimes/osx/lib/netstandard1.4/_._": {
"runtimes/linux/lib/netstandard1.4/System.Diagnostics.Process.dll": {
"assetType": "runtime",
"rid": "linux"
},
"runtimes/osx/lib/netstandard1.4/System.Diagnostics.Process.dll": {
"assetType": "runtime",
"rid": "osx"
},
"runtimes/win/lib/netstandard1.4/System.Diagnostics.Process.dll": {
"assetType": "runtime",
"rid": "win"
}
}
},
@ -1160,7 +1307,11 @@
"ref/netstandard1.3/System.Net.Requests.dll": {}
},
"runtimeTargets": {
"runtimes/win/lib/netstandard1.3/_._": {
"runtimes/unix/lib/netstandard1.3/System.Net.Requests.dll": {
"assetType": "runtime",
"rid": "unix"
},
"runtimes/win/lib/netstandard1.3/System.Net.Requests.dll": {
"assetType": "runtime",
"rid": "win"
}
@ -2073,7 +2224,7 @@
"ref/netstandard1.3/System.Threading.Thread.dll": {}
},
"runtime": {
"lib/netstandard1.3/_._": {}
"lib/netstandard1.3/System.Threading.Thread.dll": {}
}
},
"System.Threading.ThreadPool/4.0.10": {
@ -2253,6 +2404,126 @@
}
},
"libraries": {
"Google.Apis/1.15.0": {
"sha512": "B//vbZgUsR0jdJztCJ0ORmVcAzhoiisIsxwc1libVjoZzu+kxUKNJKUl5Wlkj7V28kauS56y3hJUj3FMsgaJZQ==",
"type": "package",
"path": "Google.Apis/1.15.0",
"files": [
"Google.Apis.1.15.0.nupkg.sha512",
"Google.Apis.nuspec",
"License.txt",
"lib/net45/Google.Apis.PlatformServices.dll",
"lib/net45/Google.Apis.PlatformServices.pdb",
"lib/net45/Google.Apis.PlatformServices.xml",
"lib/net45/Google.Apis.dll",
"lib/net45/Google.Apis.pdb",
"lib/net45/Google.Apis.xml",
"lib/netstandard1.3/Google.Apis.dll",
"lib/netstandard1.3/Google.Apis.pdb",
"lib/netstandard1.3/Google.Apis.xml",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.dll",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.pdb",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.xml",
"lib/win81/Google.Apis.PlatformServices.dll",
"lib/win81/Google.Apis.PlatformServices.pdb",
"lib/win81/Google.Apis.PlatformServices.xml",
"lib/win81/Google.Apis.dll",
"lib/win81/Google.Apis.pdb",
"lib/win81/Google.Apis.xml",
"lib/wp8/Google.Apis.PlatformServices.dll",
"lib/wp8/Google.Apis.PlatformServices.pdb",
"lib/wp8/Google.Apis.PlatformServices.xml",
"lib/wp8/Google.Apis.dll",
"lib/wp8/Google.Apis.pdb",
"lib/wp8/Google.Apis.xml",
"lib/wpa81/Google.Apis.PlatformServices.dll",
"lib/wpa81/Google.Apis.PlatformServices.pdb",
"lib/wpa81/Google.Apis.PlatformServices.xml",
"lib/wpa81/Google.Apis.dll",
"lib/wpa81/Google.Apis.pdb",
"lib/wpa81/Google.Apis.xml"
]
},
"Google.Apis.Auth/1.15.0": {
"sha512": "gBMi03/CjodxVVjByVvvaE4To9905Oe6o59oxzP6AI5uZaab9zNclR+2cu6OcnS5wOIpf5DKAWd+jlSshuZ/cw==",
"type": "package",
"path": "Google.Apis.Auth/1.15.0",
"files": [
"Google.Apis.Auth.1.15.0.nupkg.sha512",
"Google.Apis.Auth.nuspec",
"License.txt",
"lib/net45/Google.Apis.Auth.PlatformServices.dll",
"lib/net45/Google.Apis.Auth.PlatformServices.pdb",
"lib/net45/Google.Apis.Auth.PlatformServices.xml",
"lib/net45/Google.Apis.Auth.dll",
"lib/net45/Google.Apis.Auth.pdb",
"lib/net45/Google.Apis.Auth.xml",
"lib/netstandard1.3/Google.Apis.Auth.PlatformServices.dll",
"lib/netstandard1.3/Google.Apis.Auth.PlatformServices.pdb",
"lib/netstandard1.3/Google.Apis.Auth.PlatformServices.xml",
"lib/netstandard1.3/Google.Apis.Auth.dll",
"lib/netstandard1.3/Google.Apis.Auth.pdb",
"lib/netstandard1.3/Google.Apis.Auth.xml",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Auth.dll",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Auth.pdb",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Auth.xml",
"lib/win81/Google.Apis.Auth.PlatformServices.dll",
"lib/win81/Google.Apis.Auth.PlatformServices.pdb",
"lib/win81/Google.Apis.Auth.PlatformServices.xml",
"lib/win81/Google.Apis.Auth.dll",
"lib/win81/Google.Apis.Auth.pdb",
"lib/win81/Google.Apis.Auth.xml",
"lib/wp8/Google.Apis.Auth.PlatformServices.dll",
"lib/wp8/Google.Apis.Auth.PlatformServices.pdb",
"lib/wp8/Google.Apis.Auth.PlatformServices.xml",
"lib/wp8/Google.Apis.Auth.dll",
"lib/wp8/Google.Apis.Auth.pdb",
"lib/wp8/Google.Apis.Auth.xml",
"lib/wpa81/Google.Apis.Auth.PlatformServices.dll",
"lib/wpa81/Google.Apis.Auth.PlatformServices.pdb",
"lib/wpa81/Google.Apis.Auth.PlatformServices.xml",
"lib/wpa81/Google.Apis.Auth.dll",
"lib/wpa81/Google.Apis.Auth.pdb",
"lib/wpa81/Google.Apis.Auth.xml"
]
},
"Google.Apis.Core/1.15.0": {
"sha512": "izmsmat5RRL0bmJ2tr3SvlqEiGf40wDeOTHv0PJOVUvHoZBdAaVbbZFxtevOWOyo878mwpYGXfzMs5Zfoyfrfw==",
"type": "package",
"path": "Google.Apis.Core/1.15.0",
"files": [
"Google.Apis.Core.1.15.0.nupkg.sha512",
"Google.Apis.Core.nuspec",
"License.txt",
"lib/net45/Google.Apis.Core.dll",
"lib/net45/Google.Apis.Core.pdb",
"lib/net45/Google.Apis.Core.xml",
"lib/netstandard1.3/Google.Apis.Core.dll",
"lib/netstandard1.3/Google.Apis.Core.pdb",
"lib/netstandard1.3/Google.Apis.Core.xml",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Core.dll",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Core.pdb",
"lib/portable-net45+sl50+netcore45+wpa81+wp8/Google.Apis.Core.xml"
]
},
"Google.Apis.YouTube.v3/1.15.0.582": {
"sha512": "isR8FdI417PKLgLlNdOVDhduO+8yqPJ+vfID1Zx0MjAa/y3q655Plk2E/KNmsrjvXkqSSWwDCQHPz/Q1fat4tA==",
"type": "package",
"path": "Google.Apis.YouTube.v3/1.15.0.582",
"files": [
"Google.Apis.YouTube.v3.1.15.0.582.nupkg.sha512",
"Google.Apis.YouTube.v3.nuspec",
"lib/netstandard1.3/Google.Apis.YouTube.v3.dll",
"lib/netstandard1.3/Google.Apis.YouTube.v3.pdb",
"lib/netstandard1.3/Google.Apis.YouTube.v3.xml",
"lib/portable-net40+sl50+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.dll",
"lib/portable-net40+sl50+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.pdb",
"lib/portable-net40+sl50+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.xml",
"lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.dll",
"lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.pdb",
"lib/portable-net45+netcore45+wpa81+wp8/Google.Apis.YouTube.v3.xml"
]
},
"Libuv/1.9.0": {
"sha512": "9Q7AaqtQhS8JDSIvRBt6ODSLWDBI4c8YxNxyCQemWebBFUtBbc6M5Vi5Gz1ZyIUlTW3rZK9bIr5gnVyv0z7a2Q==",
"type": "package",
@ -2679,6 +2950,25 @@
"tools/install.ps1"
]
},
"Portable.BouncyCastle/1.8.1.1": {
"sha512": "bKqC2Me9ukybNYTBhlYd2sJ6j2kRV7SgB+JfiP2GueYq6QdM4Ym6PYV5eyrqb6KViOyd3zqQfJp0o6UW5ZG+GQ==",
"type": "package",
"path": "Portable.BouncyCastle/1.8.1.1",
"files": [
"Portable.BouncyCastle.1.8.1.1.nupkg.sha512",
"Portable.BouncyCastle.nuspec",
"Readme.html",
"lib/netstandard1.0/crypto.dll",
"lib/netstandard1.0/crypto.pdb",
"lib/netstandard1.0/crypto.xml",
"lib/netstandard1.3/crypto.dll",
"lib/netstandard1.3/crypto.pdb",
"lib/netstandard1.3/crypto.xml",
"lib/portable-net4+sl5+wp8+win8+wpa81/crypto.dll",
"lib/portable-net4+sl5+wp8+win8+wpa81/crypto.pdb",
"lib/portable-net4+sl5+wp8+win8+wpa81/crypto.xml"
]
},
"runtime.native.System/4.0.0": {
"sha512": "QfS/nQI7k/BLgmLrw7qm7YBoULEvgWnPI+cYsbfCVFTW8Aj+i8JhccxcFMu1RWms0YZzF+UHguNBK4Qn89e2Sg==",
"type": "package",
@ -3122,6 +3412,64 @@
"ref/xamarinwatchos10/_._"
]
},
"System.Diagnostics.Contracts/4.0.1": {
"sha512": "HvQQjy712vnlpPxaloZYkuE78Gn353L0SJLJVeLcNASeg9c4qla2a1Xq8I7B3jZoDzKPtHTkyVO7AZ5tpeQGuA==",
"type": "package",
"path": "System.Diagnostics.Contracts/4.0.1",
"files": [
"System.Diagnostics.Contracts.4.0.1.nupkg.sha512",
"System.Diagnostics.Contracts.nuspec",
"ThirdPartyNotices.txt",
"dotnet_library_license.txt",
"lib/MonoAndroid10/_._",
"lib/MonoTouch10/_._",
"lib/net45/_._",
"lib/netcore50/System.Diagnostics.Contracts.dll",
"lib/netstandard1.0/System.Diagnostics.Contracts.dll",
"lib/portable-net45+win8+wp8+wpa81/_._",
"lib/win8/_._",
"lib/wp80/_._",
"lib/wpa81/_._",
"lib/xamarinios10/_._",
"lib/xamarinmac20/_._",
"lib/xamarintvos10/_._",
"lib/xamarinwatchos10/_._",
"ref/MonoAndroid10/_._",
"ref/MonoTouch10/_._",
"ref/net45/_._",
"ref/netcore50/System.Diagnostics.Contracts.dll",
"ref/netcore50/System.Diagnostics.Contracts.xml",
"ref/netcore50/de/System.Diagnostics.Contracts.xml",
"ref/netcore50/es/System.Diagnostics.Contracts.xml",
"ref/netcore50/fr/System.Diagnostics.Contracts.xml",
"ref/netcore50/it/System.Diagnostics.Contracts.xml",
"ref/netcore50/ja/System.Diagnostics.Contracts.xml",
"ref/netcore50/ko/System.Diagnostics.Contracts.xml",
"ref/netcore50/ru/System.Diagnostics.Contracts.xml",
"ref/netcore50/zh-hans/System.Diagnostics.Contracts.xml",
"ref/netcore50/zh-hant/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/System.Diagnostics.Contracts.dll",
"ref/netstandard1.0/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/de/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/es/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/fr/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/it/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/ja/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/ko/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/ru/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/zh-hans/System.Diagnostics.Contracts.xml",
"ref/netstandard1.0/zh-hant/System.Diagnostics.Contracts.xml",
"ref/portable-net45+win8+wp8+wpa81/_._",
"ref/win8/_._",
"ref/wp80/_._",
"ref/wpa81/_._",
"ref/xamarinios10/_._",
"ref/xamarinmac20/_._",
"ref/xamarintvos10/_._",
"ref/xamarinwatchos10/_._",
"runtimes/aot/lib/netcore50/System.Diagnostics.Contracts.dll"
]
},
"System.Diagnostics.Debug/4.0.11": {
"sha512": "w5U95fVKHY4G8ASs/K5iK3J5LY+/dLFd4vKejsnI/ZhBsWS9hQakfx3Zr7lRWKg4tAw9r4iktyvsTagWkqYCiw==",
"type": "package",
@ -7080,11 +7428,13 @@
"": [
"Discord.Net >= 1.0.0-dev",
"Discord.Net.Commands >= 1.0.0-dev",
"Google.Apis.YouTube.v3 >= 1.15.0.582",
"Microsoft.Extensions.DependencyInjection >= 1.0.0",
"Microsoft.Extensions.DependencyInjection.Abstractions >= 1.0.0",
"Microsoft.Extensions.PlatformAbstractions >= 1.0.0",
"Microsoft.NETCore.App >= 1.0.0",
"Newtonsoft.Json >= 9.0.1",
"System.Diagnostics.Contracts >= 4.0.1",
"System.Resources.ResourceWriter >= 4.0.0-beta-22816"
],
".NETCoreApp,Version=v1.0": []