fixed ~ani and ~mang

This commit is contained in:
Master Kwoth 2016-03-03 10:10:08 +01:00
parent ffb63f9e81
commit 4c0e832463
9 changed files with 60 additions and 55 deletions

View File

@ -13,8 +13,8 @@ namespace NadekoBot {
public string BotVersion => $"{Assembly.GetExecutingAssembly().GetName().Name} v{Assembly.GetExecutingAssembly().GetName().Version}";
private int _commandsRan = 0;
private string _statsCache = "";
private int commandsRan = 0;
private string statsCache = "";
private readonly Stopwatch statsStopwatch = new Stopwatch();
public int ServerCount { get; private set; } = 0;
@ -98,19 +98,19 @@ namespace NadekoBot {
sb.Append($"`Servers: {ServerCount}");
sb.Append($" | TextChannels: {TextChannelsCount}");
sb.AppendLine($" | VoiceChannels: {VoiceChannelsCount}`");
sb.AppendLine($"`Commands Ran this session: {_commandsRan}`");
sb.AppendLine($"`Commands Ran this session: {commandsRan}`");
sb.AppendLine($"`Message queue size:{NadekoBot.Client.MessageQueue.Count}`");
sb.AppendLine($"`Greeted {Commands.ServerGreetCommand.Greeted} times.`");
_statsCache = sb.ToString();
statsCache = sb.ToString();
});
public string Heap() => Math.Round((double)GC.GetTotalMemory(true) / 1.MiB(), 2).ToString();
public async Task<string> GetStats() {
if (statsStopwatch.Elapsed.Seconds <= 5) return _statsCache;
if (statsStopwatch.Elapsed.Seconds <= 5) return statsCache;
await LoadStats();
statsStopwatch.Restart();
return _statsCache;
return statsCache;
}
private async Task StartCollecting() {
@ -136,24 +136,26 @@ namespace NadekoBot {
}
}
}
//todo - batch save this
private void StatsCollector_RanCommand(object sender, CommandEventArgs e) {
try {
_commandsRan++;
Classes.DbHandler.Instance.InsertData(new Classes._DataModels.Command {
ServerId = (long)e.Server.Id,
ServerName = e.Server.Name,
ChannelId = (long)e.Channel.Id,
ChannelName = e.Channel.Name,
UserId = (long)e.User.Id,
UserName = e.User.Name,
CommandName = e.Command.Text,
DateAdded = DateTime.Now
});
}
catch {
Console.WriteLine("Error in ran command DB write.");
}
private async void StatsCollector_RanCommand(object sender, CommandEventArgs e) {
await Task.Run(() => {
try {
commandsRan++;
Classes.DbHandler.Instance.InsertData(new Classes._DataModels.Command {
ServerId = (long) e.Server.Id,
ServerName = e.Server.Name,
ChannelId = (long) e.Channel.Id,
ChannelName = e.Channel.Name,
UserId = (long) e.User.Id,
UserName = e.User.Name,
CommandName = e.Command.Text,
DateAdded = DateTime.Now
});
}
catch {
Console.WriteLine("Error in ran command DB write.");
}
});
}
}
}

View File

@ -7,6 +7,7 @@ using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Authentication;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
@ -56,47 +57,51 @@ namespace NadekoBot.Classes {
}
}
public static async Task<AnimeResult> GetAnimeQueryResultLink(string query) {
public static async Task<AnimeResult> GetAnimeData(string query) {
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
await RefreshAnilistToken();
var link = "http://anilist.co/api/anime/search/" + Uri.EscapeUriString(query);
try {
var headers = new Dictionary<string, string> {{"'access_token'", "'"+token+"'"}};
var smallContent = await GetResponseStringAsync(link, headers);
var smallObj = JArray.Parse(smallContent)[0];
var content = await GetResponseStringAsync("http://anilist.co/api/anime/" + smallObj["id"], headers);
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];
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
rq = new RestSharp.RestRequest("/anime/" + smallObj["id"]);
rq.AddParameter("access_token", token);
var content = cl.Execute(rq).Content;
}
catch (Exception ex) {
Console.WriteLine(ex);
return new AnimeResult();
}
return await Task.Run(() => JsonConvert.DeserializeObject<AnimeResult>(content));
}
public static async Task<MangaResult> GetMangaQueryResultLink(string query) {
public static async Task<MangaResult> GetMangaData(string query) {
if (string.IsNullOrWhiteSpace(query))
throw new ArgumentNullException(nameof(query));
await RefreshAnilistToken();
var link = "http://anilist.co/api/manga/search/" + Uri.EscapeUriString(query);
var headers = new Dictionary<string, string> { { "access_token", token } };
var smallContent = await GetResponseStringAsync(link, headers);
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];
var content = await GetResponseStringAsync("http://anilist.co/api/manga/" + smallObj["id"], headers);
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));
}
private static async Task RefreshAnilistToken() {
if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29))
lastRefreshed=DateTime.Now;
if (DateTime.Now - lastRefreshed > TimeSpan.FromMinutes(29))
lastRefreshed = DateTime.Now;
else {
return;
}
@ -144,10 +149,9 @@ namespace NadekoBot.Classes {
if (string.IsNullOrWhiteSpace(NadekoBot.Creds.GoogleAPIKey))
throw new ArgumentNullException(nameof(query));
var link = $"https://www.googleapis.com/youtube/v3/search?part=snippet" +
$"&maxResults=1" +
var link = "https://www.googleapis.com/youtube/v3/search?part=snippet" +
"&maxResults=1&type=playlist" +
$"&q={Uri.EscapeDataString(query)}" +
$"&type=playlist" +
$"&key={NadekoBot.Creds.GoogleAPIKey}";
var response = await GetResponseStringAsync(link);

View File

@ -143,8 +143,7 @@ namespace NadekoBot.Commands {
//get skill order data<API_KEY>
var orderArr = (data["skills"]["mostGames"]["order"] as JArray);
//todo save this for at least 1 hour
var img = Image.FromFile("data/lol/bg.png");
using (var g = Graphics.FromImage(img)) {
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
@ -162,7 +161,7 @@ namespace NadekoBot.Commands {
champName = "Wukong";
g.DrawString($"{champName}", new Font("Times New Roman", 24, FontStyle.Regular), Brushes.WhiteSmoke, margin + imageSize + margin, margin);
//draw champ surname
//todo
//draw skill order
float orderFormula = 120 / orderArr.Count;
const float orderVerticalSpacing = 10;

View File

@ -19,7 +19,7 @@ namespace NadekoBot.Commands {
public string GetRequests() {
var task = Classes.DbHandler.Instance.GetAllRows<Classes._DataModels.Request>();
string str = "Here are all current requests for NadekoBot:\n\n";
var str = "Here are all current requests for NadekoBot:\n\n";
foreach (var reqObj in task) {
str += $"{reqObj.Id}. by **{reqObj.UserName}** from **{reqObj.ServerName}** at {reqObj.DateAdded.ToLocalTime()}\n" +
$"**{reqObj.RequestText}**\n----------\n";
@ -48,7 +48,7 @@ namespace NadekoBot.Commands {
.Description("Requests a feature for nadeko.\n**Usage**: @NadekoBot req new_feature")
.Parameter("all", ParameterType.Unparsed)
.Do(async e => {
string str = e.Args[0];
var str = e.Args[0];
try {
SaveRequest(e, str);
@ -62,7 +62,7 @@ namespace NadekoBot.Commands {
cgb.CreateCommand("lr")
.Description("PMs the user all current nadeko requests.")
.Do(async e => {
string str = GetRequests();
var str = await Task.Run(() => GetRequests());
if (str.Trim().Length > 110)
await e.User.Send(str);
else

View File

@ -44,7 +44,7 @@ namespace NadekoBot.Modules {
if (!(await SearchHelper.ValidateQuery(e.Channel, e.GetArg("query")))) return;
string result;
try {
result = (await SearchHelper.GetAnimeQueryResultLink(e.GetArg("query"))).ToString();
result = (await SearchHelper.GetAnimeData(e.GetArg("query"))).ToString();
} catch {
await e.Channel.SendMessage("Failed to find that anime.");
return;
@ -61,7 +61,7 @@ namespace NadekoBot.Modules {
if (!(await SearchHelper.ValidateQuery(e.Channel, e.GetArg("query")))) return;
string result;
try {
result = (await SearchHelper.GetMangaQueryResultLink(e.GetArg("query"))).ToString();
result = (await SearchHelper.GetMangaData(e.GetArg("query"))).ToString();
} catch {
await e.Channel.SendMessage("Failed to find that anime.");
return;

Binary file not shown.