improvements to getresponse, prune and clr (performance/ratelimit)

This commit is contained in:
Master Kwoth 2016-02-05 18:17:48 +01:00
parent 95cc71b787
commit 62b2f0c869
3 changed files with 74 additions and 42 deletions

View File

@ -12,7 +12,7 @@ namespace NadekoBot
{ {
public class NadekoStats public class NadekoStats
{ {
public string BotVersion = "0.8-beta7"; public string BotVersion = "0.8-beta8";
private static readonly NadekoStats _instance = new NadekoStats(); private static readonly NadekoStats _instance = new NadekoStats();
public static NadekoStats Instance => _instance; public static NadekoStats Instance => _instance;

View File

@ -9,12 +9,13 @@ using NadekoBot.Extensions;
using System.Threading.Tasks; using System.Threading.Tasks;
using NadekoBot.Commands; using NadekoBot.Commands;
using System.IO; using System.IO;
using System.Collections.Concurrent;
namespace NadekoBot.Modules { namespace NadekoBot.Modules {
class Administration : DiscordModule { class Administration : DiscordModule {
public Administration() : base() { public Administration() : base() {
commands.Add(new HelpCommand()); commands.Add(new HelpCommand());
if(NadekoBot.ParseActive) if (NadekoBot.ParseActive)
commands.Add(new ServerGreetCommand()); commands.Add(new ServerGreetCommand());
else else
Console.WriteLine("Parse not active. Server greet disabled."); Console.WriteLine("Parse not active. Server greet disabled.");
@ -148,7 +149,7 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(".roles") cgb.CreateCommand(".roles")
.Description("List all roles on this server") .Description("List all roles on this server")
.Do(async e => { .Do(async e => {
await e.Send("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles).Replace("@everyone","[everyone]")); await e.Send("`List of roles:` \n• " + string.Join("\n• ", e.Server.Roles).Replace("@everyone", "[everyone]"));
}); });
cgb.CreateCommand(".b").Alias(".ban") cgb.CreateCommand(".b").Alias(".ban")
@ -375,28 +376,37 @@ namespace NadekoBot.Modules {
}); });
ConcurrentDictionary<Server, bool> pruneDict = new ConcurrentDictionary<Server, bool>();
cgb.CreateCommand(".prune") cgb.CreateCommand(".prune")
.Parameter("num", ParameterType.Required) .Parameter("num", ParameterType.Required)
.Description("Prunes a number of messages from the current channel.\n**Usage**: .prune 50") .Description("Prunes a number of messages from the current channel.\n**Usage**: .prune 50")
.Do(async e => { .Do(async e => {
if (!e.User.ServerPermissions.ManageMessages) return; if (!e.User.ServerPermissions.ManageMessages) return;
if (pruneDict.ContainsKey(e.Server))
return;
int num; int num;
if (!Int32.TryParse(e.GetArg("num"), out num) || num < 1) { if (!Int32.TryParse(e.GetArg("num"), out num) || num < 1) {
await e.Send("Incorrect amount."); await e.Send("Incorrect amount.");
return; return;
} }
try { pruneDict.TryAdd(e.Server, true);
Message last = null; await Task.Factory.StartNew(async () => {
while (num > 0) { try {
var msgs = await e.Channel.DownloadMessages(num, last?.Id); Message last = null;
last = msgs.LastOrDefault(); while (num > 0) {
msgs.ForEach(async m => await m.Delete()); var msgs = await e.Channel.DownloadMessages(num, last?.Id);
num -= 100; last = msgs.LastOrDefault();
} foreach (var m in msgs) {
} catch (Exception) { await e.Send("Failed pruning. Make sure the bot has correct permissions."); } await m.Delete();
await Task.Delay(500);
}
num -= 100;
}
} catch (Exception) { await e.Send("Failed pruning. Make sure the bot has correct permissions."); }
}, TaskCreationOptions.LongRunning);
bool throwAway;
pruneDict.TryRemove(e.Server, out throwAway);
}); });
cgb.CreateCommand(".die") cgb.CreateCommand(".die")
@ -412,13 +422,25 @@ namespace NadekoBot.Modules {
} }
}); });
ConcurrentDictionary<Server, bool> clearDictionary = new ConcurrentDictionary<Server, bool>();
cgb.CreateCommand(".clr") cgb.CreateCommand(".clr")
.Description("Clears some of nadeko's messages from the current channel.") .Description("Clears some of nadeko's messages from the current channel.")
.Do(async e => { .Do(async e => {
try {
if (clearDictionary.ContainsKey(e.Server))
return;
clearDictionary.TryAdd(e.Server, true);
var msgs = await e.Channel.DownloadMessages(100); var msgs = await e.Channel.DownloadMessages(100);
await Task.Run(async () => {
msgs.Where(msg => msg.User.Id == client.CurrentUser.Id) var ms = msgs.Where(msg => msg.User.Id == client.CurrentUser.Id);
.ForEach(async m => { try { await m.Delete(); } catch (Exception) { } }); foreach (var m in ms) {
try { await m.Delete(); } catch (Exception) { }
await Task.Delay(500);
}
});
} catch (Exception) {}
bool throwaway;
clearDictionary.TryRemove(e.Server, out throwaway);
}); });
cgb.CreateCommand(".newname") cgb.CreateCommand(".newname")
.Description("Give the bot a new name.") .Description("Give the bot a new name.")
@ -506,27 +528,27 @@ namespace NadekoBot.Modules {
cgb.CreateCommand(".menrole") cgb.CreateCommand(".menrole")
.Alias(".mentionrole") .Alias(".mentionrole")
.Description("Mentions every person from the provided role or roles (separated by a ',') on this server. Requires you to have mention @everyone permission.") .Description("Mentions every person from the provided role or roles (separated by a ',') on this server. Requires you to have mention @everyone permission.")
.Parameter("roles", ParameterType.Unparsed) .Parameter("roles", ParameterType.Unparsed)
.Do(async e => { .Do(async e => {
if (!e.User.ServerPermissions.MentionEveryone) return; if (!e.User.ServerPermissions.MentionEveryone) return;
var arg = e.GetArg("roles").Split(',').Select(r => r.Trim()); var arg = e.GetArg("roles").Split(',').Select(r => r.Trim());
string send = $"--{e.User.Mention} has invoked a mention on the following roles--"; string send = $"--{e.User.Mention} has invoked a mention on the following roles--";
foreach (var roleStr in arg) { foreach (var roleStr in arg) {
if (string.IsNullOrWhiteSpace(roleStr)) continue; if (string.IsNullOrWhiteSpace(roleStr)) continue;
var role = e.Server.FindRoles(roleStr).FirstOrDefault(); var role = e.Server.FindRoles(roleStr).FirstOrDefault();
if (role == null) continue; if (role == null) continue;
send += $"\n`{role.Name}`\n"; send += $"\n`{role.Name}`\n";
send += string.Join(", ", role.Members.Select(r => r.Mention)); send += string.Join(", ", role.Members.Select(r => r.Mention));
} }
while (send.Length > 2000) { while (send.Length > 2000) {
var curstr = send.Substring(0, 2000); var curstr = send.Substring(0, 2000);
await e.Channel.Send(curstr.Substring(0, curstr.LastIndexOf(", ") + 1)); await e.Channel.Send(curstr.Substring(0, curstr.LastIndexOf(", ") + 1));
send = curstr.Substring(curstr.LastIndexOf(", ") + 1) + send.Substring(2000); send = curstr.Substring(curstr.LastIndexOf(", ") + 1) + send.Substring(2000);
} }
await e.Channel.Send(send); await e.Channel.Send(send);
}); });
/*cgb.CreateCommand(".voicetext") /*cgb.CreateCommand(".voicetext")
.Description("Enabled or disabled voice to text channel connection. Only people in a certain voice channel will see ") .Description("Enabled or disabled voice to text channel connection. Only people in a certain voice channel will see ")

View File

@ -183,14 +183,14 @@ namespace NadekoBot.Modules {
await e.Send($":anger: Error {ex}"); await e.Send($":anger: Error {ex}");
} }
}); });
/*
cgb.CreateCommand("~osu") cgb.CreateCommand("~osu")
.Description("desc") .Description("desc")
.Parameter("arg", ParameterType.Required) .Parameter("arg", ParameterType.Required)
.Do(async e => { .Do(async e => {
var arg = e.GetArg("arg"); var arg = e.GetArg("arg");
//make request to osu var res = await GetResponseStream($"http://lemmmy.pw/osusig/sig.php?uname=kwoth&flagshadow&xpbar&xpbarhex&pp=2");
//print useful data await e.Channel.SendFile($"_{e.GetArg("arg")}.png", res);
}); });
cgb.CreateCommand("~osubind") cgb.CreateCommand("~osubind")
@ -209,11 +209,21 @@ namespace NadekoBot.Modules {
//if exists save bind pair to parse.com //if exists save bind pair to parse.com
//if not valid error //if not valid error
}); });
*/
}); });
} }
public static async Task<Stream> GetResponseStream(string v) => public static async Task<Stream> GetResponseStream(string v) {
(await ((HttpWebRequest)WebRequest.Create(v)).GetResponseAsync()).GetResponseStream(); var wr = (HttpWebRequest)WebRequest.Create(v);
try {
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
wr.UserAgent = @"Mozilla/5.0 (Windows NT 6.2; Win64; x64)";
return (await (wr).GetResponseAsync()).GetResponseStream();
} catch (Exception ex) {
Console.WriteLine("error in getresponse stream " + ex);
return null;
}
}
public static async Task<string> GetResponseAsync(string v) => public static async Task<string> GetResponseAsync(string v) =>
await new StreamReader((await ((HttpWebRequest)WebRequest.Create(v)).GetResponseAsync()).GetResponseStream()).ReadToEndAsync(); await new StreamReader((await ((HttpWebRequest)WebRequest.Create(v)).GetResponseAsync()).GetResponseStream()).ReadToEndAsync();