private void ResolveHost(string hostname, CommandArgs command) { IPHostEntry hostEntry; try { hostEntry = Dns.GetHostEntry(hostname); } catch (SocketException e) { command.ReturnMessage(e.Message); return; } catch (Exception) { command.ReturnMessage("It looks like you entered a wrong domain name."); return; } if (hostEntry.AddressList.Length > 0) { var addr = string.Join(", ", hostEntry.AddressList.Select(host => host.ToString())); command.Reply($"IP address(es) belonging to {command.Args[0]}: {addr}"); } }
public override void Use(CommandArgs command) { if (command.FullArgument == null) { InformUsage(command); return; } var match = Regex.Match(command.FullArgument, @"^((?:\d*(?:\.|,)\d+)|(?:\d+))\s*([a-z]{3}).*\s([a-z]{3})$", RegexOptions.IgnoreCase); if (match.Success) { decimal fromAmount; if (!decimal.TryParse(match.Groups[1].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out fromAmount)) { command.Reply($"I don't know how to turn {match.Groups[1].Value} into a number."); return; } else { if (exchangeRates == null) { command.Reply("please wait a moment, I'm still looking up the exchange rates."); return; } var fromCurrency = match.Groups[2].Value.ToUpper(); var toCurrency = match.Groups[3].Value.ToUpper(); if (toCurrency != "EUR" && !exchangeRates.ContainsKey(toCurrency)) { command.Reply($"I don't know the exchange rate of {toCurrency}"); return; } if (fromCurrency != "EUR" && !exchangeRates.ContainsKey(fromCurrency)) { command.Reply($"I don't know the exchange rate of {fromCurrency}"); return; } decimal result; // The base currency is EUR, so if we're converting to or from EUR, no additional conversion is necessary. if (fromCurrency == "EUR") { result = fromAmount * exchangeRates[toCurrency]; } else if (toCurrency == "EUR") { result = fromAmount / exchangeRates[fromCurrency]; } // First convert from the source currency to EUR, then convert from EUR to the target currency. else { result = fromAmount / exchangeRates[fromCurrency] * exchangeRates[toCurrency]; } command.Reply($"{fromAmount} {fromCurrency} = {result:F} {toCurrency}"); } } else { InformUsage(command); } }
public override void Use(CommandArgs command) { var cmdParser = new CommandParser(new Operation()) .AddOperation("cfg", new Operation() .AddArgument("config-key", string.Empty)) .AddOperation("uid", new Operation() .AddArgument("user", command.Sender.Nick)) .AddOperation("users", new Operation() .AddArgument("channel", command.Channel)); OperationResult result; try { result = cmdParser.Parse(command.FullArgument); } catch (InvalidCommandException e) { command.ReturnMessage(e.Message); return; } switch (result.OperationName) { case "default": InformUsage(command); break; case "cfg": if (!UserTools.Validate(command.Sender)) { command.Reply(Messages.CmdNotAuthorised); return; } var key = result.Arguments["config-key"]; var value = MiscTools.GetDynamic(key.Split('.').Select(k => k.ToPascalCase()).ToArray(), ConfigManager.Config); command.Reply($"{(string.IsNullOrEmpty(key)? "config" : "config." + key)} = {value}"); break; case "uid": var uid = command.Client.StatsDatabase.GetIdFromNick(result.Arguments["user"]); if (uid == -2) command.Reply($"I don't know a user with {result.Arguments["user"]} as their primary name"); else command.Reply($"the user Id belonging to {result.Arguments["user"]} is {uid}"); break; case "users": var channel = result.Arguments["channel"]; if (command.Client.InChannel(channel)) { var ircChannel = command.Client.GetChannel(channel); command.Reply($"users in {channel}: {string.Join(", ", ircChannel.UserCount)}"); } else { command.Reply("I'm not in that channel."); } break; } }
public override void Use(CommandArgs command) { var diff = DateTime.Now - startTime; var d = diff.Days + (diff.Days == 1 ? " day" : " days"); var h = diff.Hours + (diff.Hours == 1 ? " hour" : " hours"); var m = diff.Minutes + (diff.Minutes == 1 ? " minute" : " minutes"); var s = diff.Seconds + (diff.Seconds == 1 ? " second" : " seconds"); command.Reply("I have been running for {0}, {1}, {2} and {3}", d, h, m, s); }
// TODO: Candidate for porting to CommandParsing public override void Use(CommandArgs command) { if (command.Args.Length == 2 && command.Args[0] == "set") { if (UserTools.Validate(command.Sender)) { var uid = command.Client.StatsDatabase.GetIdFromNick(command.Args[1]); if (uid < 0) uid = command.Client.StatsDatabase.GetIdFromUser(command.Client.DoWhoisCall(command.Args[1])); var nickserv = command.Client.NickservLookup(command.Args[1]); command.Client.StatsDatabase.SetNsLogin(uid, nickserv.AccountName); command.ReturnMessage("Nickserv updated to {0} for {1}.", nickserv, command.Args[1]); return; } command.ReturnMessage(Messages.CmdNotAuthorised); return; } if(command.Args.Length == 1 && command.Args[0] == "update") { var uid = command.Client.StatsDatabase.GetIdFromNick(command.Sender.Nick); if (uid < 0) uid = command.Client.StatsDatabase.GetIdFromUser(command.Sender); var nickserv = command.Client.NickservLookup(command.Sender.Nick); var rows = command.Client.StatsDatabase.SetNsLogin(uid, nickserv?.AccountName); command.Reply($"NickServ reports that your account name is '{nickserv?.AccountName}'. I've updated the database to reflect that ({rows} record(s) affected)."); return; } if (command.Args.Length == 1 && command.Args[0] == "-f") { command.ReturnMessage("Sending a NickServ call"); var username = command.Client.NickservLookup(command.Sender.Nick); if (username == null) { command.Reply("you don't appear to be registered with NickServ"); } else { command.Reply("your NickServ username is " + username); return; } } if (command.Args.Length != 0) { command.Reply("Usage: -ns; -ns add <username>"); return; } var ns = command.Client.StatsDatabase.GetNickserv(command.Client.StatsDatabase.GetIdFromUser(command.Sender)); if (ns == null) { command.Reply("According to my database, you don't use NickServ. If that's not right, try running -ns update"); } else { command.Reply("your NickServ username is " + ns); } }
public override void Use(CommandArgs command) { if (command.Args.Length == 1) { var target = command.Args[0]; var reply = new System.Net.NetworkInformation.Ping().Send(target); if (reply.Status == IPStatus.Success) { command.ReturnMessage("Reply from {0} in {1}ms{2}", reply.Address.ToString(), Colourise(reply.RoundtripTime) + reply.RoundtripTime, Colour(null)); } else { command.ReturnMessage("Ping failed ({0})", reply.Status); } } else if (command.Args.Length == 2) { var target = command.Args[0]; var attempts = int.Parse(command.Args[1]); var pings = new List<PingReply>(); long total = 0; var successCount = 0; for (var i = 0; i < attempts; i++) { pings.Add(new System.Net.NetworkInformation.Ping().Send(target)); if (pings[i].Status == IPStatus.Success) { successCount++; total += pings[i].RoundtripTime; if (pings[i].RoundtripTime < 500) { Thread.Sleep(500 - (int)pings[i].RoundtripTime); } } } var average = Math.Round(total / (double)successCount, 2); var raw = string.Join(", ", pings.Select(reply => (reply.Status == IPStatus.Success ? Colourise(reply.RoundtripTime) + reply.RoundtripTime + "ms" + Colour(null) : Colour(4) + "failed" + Colour(null)))); var word = successCount == 1 ? "reply" : "replies"; var address = pings[0].Address == null ? "Unknown IP Address" : pings[0].Address.ToString(); var number = double.IsNaN(average) ? "NaN " : average.ToString(); command.ReturnMessage("{0} {1} from {2}, averaging {3} ({4})", successCount, word, address, Colourise(average) + number + "ms" + Colour(null), raw); } else { command.ReturnMessage("Pong!"); } }
public override void Use(CommandArgs command) { if (command.Args.Length != 1) { command.Reply("Usage: -rdns <ip>"); return; } IPAddress hostIpAddress; try { hostIpAddress = IPAddress.Parse(command.Args[0]); } catch (FormatException) { command.ReturnMessage("I was unable to parse the IP address you entered."); return; } IPHostEntry hostEntry; try { hostEntry = Dns.GetHostEntry(hostIpAddress); } catch (ArgumentException) { command.ReturnMessage("I can't do a lookup on 0.0.0.0 or ::0"); return; } catch (SocketException) { command.ReturnMessage($"Unable to do a lookup on {hostIpAddress}. Most likely a reverse DNS entry does not exist for this address."); return; } // Get the IP address list that resolves to the host names contained in // the Alias property. var address = hostEntry.AddressList; // Get the alias names of the addresses in the IP address list. var alias = hostEntry.Aliases; Console.WriteLine("Host name : " + hostEntry.HostName); command.Reply($"{command.Args[0]} resolves to {hostEntry.HostName}"); Console.WriteLine("\nAliases :"); for (var index = 0; index < alias.Length; index++) { Console.WriteLine(alias[index]); } Console.WriteLine("\nIP address list : "); for (var index = 0; index < address.Length; index++) { Console.WriteLine(address[index]); } }
public override void Use(CommandArgs command) { if (command.Args.Length < 3) { command.Reply("Usage: -set <property> [key] <value>"); return; } switch (command.Args[0]) { case "name": int uid; if (int.TryParse(command.Args[1], out uid)) { command.Client.StatsDatabase.SetPrimary(uid, command.Args[2]); command.Reply("Done."); } else { if (command.Client.StatsDatabase.SetPrimary(command.Args[1], command.Args[2])) { command.Reply("Done."); } else { command.ReturnMessage("Name entry not found. Did you spell the username correctly?"); } } break; case "-s": /*string data; if (command.Args.Length > 3) { data = string.Join(" ", command.Args.Skip(2)); } else { data = command.Args[2]; }*/ throw new NotImplementedException("Runtime modification of the settings file is not supported yet."); //TODO: Allow runtime modification of settings file /*if (Settings.Instance.SettingExists(command.Args[1])) { command.Reply(command.Args[1] + " set to " + data); } else { command.ReturnMessage("New key \"{0}\" created. Value set to {1}", command.Args[1], data); }*/ default: command.ReturnMessage("The property \"{0}\" does not exist.", command.Args[0]); break; } }
public override void Use(CommandArgs command) { var uri = new Uri( $"http://en.wikipedia.org/w/api.php?format=json&action=query&titles={command.FullArgument}&prop=revisions&rvprop=content"); var rq = WebRequest.Create(uri); var response = rq.GetResponse(); using (var sr = new StreamReader(response.GetResponseStream())) { var data = sr.ReadToEnd(); dynamic jsonObj = JObject.Parse(data); Console.WriteLine("Title: " + jsonObj.query.pages[0].title); } }
public override void Use(CommandArgs command) { // TODO: Reimplement regeneration of graphs throw new NotImplementedException("Regenerating the graphs on the stats page is currently not possible."); /*var diff = DateTime.Now - lastUsage; if (diff.TotalSeconds < MinWaitTime) { command.ReturnMessage("This command may not be used more than once every {0} seconds. Please try again in {1} seconds.", MinWaitTime, (int)(MinWaitTime - diff.TotalSeconds)); return; } const string args = "regenerate_graphs.sh"; Process.Start("sh", args); lastUsage = DateTime.Now; command.ReturnMessage("I have regenerated the graphs on the stats page.");*/ }
public override void Use(CommandArgs command) { if (command.Args.Length == 0) { InformUsage(command); } else { if (command.FullArgument.Contains(',')) { command.ReturnMessage("Reading the Input Buffer is not supported yet."); } command.ReturnMessage(interpreter.ProcessCode(command.FullArgument)); } }
public override void Use(CommandArgs command) { if (string.IsNullOrWhiteSpace(command.FullArgument)) { command.ReturnMessage("usage: -ur <search term>"); return; } var term = command.FullArgument.Replace(' ', '+'); var rq = WebRequest.Create(@"http://api.urbandictionary.com/v0/define?term=" + term); var response = rq.GetResponse(); var text = new StreamReader(response.GetResponseStream()).ReadToEnd(); dynamic obj = JObject.Parse(text); if (obj.result_type == "no_results") { command.Reply("no results found."); } else { string name = obj.list[0].word; string definition = obj.list[0].definition; string example = obj.list[0].example; string permalink = obj.list[0].permalink; name = Regex.Replace(name, @"\t|\n|\r", " "); definition = Regex.Replace(definition, @"\t|\n|\r", " "); example = Regex.Replace(example, @"\t|\n|\r", " "); if (definition.Length > 255) { definition = definition.Substring(0, 250); definition += " (...)"; } if (example.Length > 255) { example = example.Substring(0, 250); example += " (...)"; } var exampleString = string.IsNullOrWhiteSpace(example) ? string.Empty : $" - \u001d{example}\u001d"; command.ReturnMessage("\u0002{0}\u0002: {1}{2} - {3}", name, definition, exampleString, permalink); } }
public override void Use(CommandArgs command) { if (command.Args.Length > 1) { var key = command.Args[0]; var value = string.Join(" ", command.Args.Skip(1)); if (value.StartsWith("-")) { value = value.Substring(1); } command.Client.StatsDatabase.UpsertMiscData("alias", key, value); command.Reply("I've aliased {0} to \"{1}\"", key, value); } else { InformUsage(command); } }
public override void Use(CommandArgs command) { if(command.FullArgument == null) { InformUsage(command); return; } var parser = new CommandParser(new Operation().AddKey("max-results", "1", 'n').AddRestArgument()); var result = parser.Parse(command.FullArgument); var numDisplayed = int.Parse(result.Keys["max-results"]); if (numDisplayed > 3 && !UserTools.Validate(command.Sender)) { command.Reply("only bot operators may request more than three results."); return; } var query = result.RestArgument; var matches = command.Client.StatsDatabase.FindLine(query); switch (matches.Count) { case 0: command.Reply("no matches found."); break; case 1: command.Reply("1 match found: " + matches[0]); break; default: if (numDisplayed == 1) command.Reply($"{matches.Count} matches (1 displayed): {matches[0]}"); else { int matchNumber = 0; foreach (var match in matches.Take(numDisplayed)) { command.Reply($"match {++matchNumber} of {numDisplayed}: {match}"); } } break; } }
public override void Use(CommandArgs command) { if (command.Args.Length == 0) { var availableCommands = string.Join(", ", commandList.Select(pair => pair.Key)); command.ReturnMessage($"Use -help <command> to get help about a specific command. -- Available commands: {availableCommands}"); } else if (command.Args.Length == 1) { if (commandList.ContainsKey(command.Args[0])) { var cmd = commandList[command.Args[0]]; command.Reply($"{command.Args[0]}: {cmd.Description} (usable by {cmd.Permissions}) -- Usage: \x02{command.Args[0]} {cmd.Usage}\x0F"); } } else { } }
public override void Use(CommandArgs command) { var search = command.FullArgument; var searchResults = command.Client.StatsDatabase.FindQuote(search); if (searchResults == null) { command.ReturnMessage("No such quote found."); return; } var quoteListBuiler = new StringBuilder(); quoteListBuiler.Append("Multiple quotes found: "); var max = searchResults.Count > 12 ? 12 : searchResults.Count; for (var i = 0; i < max; i++) { quoteListBuiler.Append("\""); quoteListBuiler.Append(searchResults[i].Text.Substring(0, 25)); quoteListBuiler.Append("\""); if (i != max - 1) { quoteListBuiler.Append(", "); } } var diff = searchResults.Count - max; if (diff > 0) { quoteListBuiler.Append($" and {diff} more."); } if (searchResults.Count > 1) { command.Reply(quoteListBuiler.ToString()); return; } command.ReturnMessage("The following quote has been featured: \"" + searchResults[0].Text + "\""); command.Client.StatsDatabase.SetVar("featured_quote", searchResults[0].Id); }
public override void Use(CommandArgs command) { var query = command.FullArgument; if (query == null) { InformUsage(command); return; } var rq = WebRequest.Create($@"https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={Uri.EscapeDataString(query)}&rsz=1&hl=en"); dynamic obj; using (var response = rq.GetResponse()) { var text = new StreamReader(response.GetResponseStream()).ReadToEnd(); obj = JObject.Parse(text); } dynamic result = obj.responseData.results[0]; command.ReturnMessage($"{result.url} - \x02{WebUtility.HtmlDecode((string)result.titleNoFormatting)}\x02"); }
public override void Use(CommandArgs command) { var parser = new CommandParser(new Operation().AddArgument("hostname", null)); OperationResult result; try { result = parser.Parse(command.FullArgument); } catch (InvalidCommandException e) { command.ReturnMessage(e.Message); return; } if (result.Arguments["hostname"] == null) { command.Reply("Usage: -resolve <hostname>"); } else { ResolveHost(result.Arguments["hostname"], command); } }
public override void Use(CommandArgs command) { var showDebugInfo = false; if (command.Args[0] == "-d") { command.Args = command.Args.Skip(1).ToArray(); showDebugInfo = true; } if (command.Args.Length == 0) { ShowTopics(command.Sender.Nick, command.Channel, command, showDebugInfo); } else if (command.Args.Length > 2) { command.ReturnMessage("Usage: -topics [nick]"); } else if (command.Args.Length == 2) { ShowTopics(command.Args[0], command.Args[1], command, showDebugInfo); } else { ShowTopics(command.Args[0], command.Channel, command, showDebugInfo); } }
private void ShowTopics(string nick, string channel, CommandArgs command, bool showDebugInfo) { Logger.Log(this, "Showing topics for " + nick); var userId = command.Client.StatsDatabase.GetIdFromNick(nick); var topics = command.Client.StatsDatabase.FindTopics(userId, channel); if (topics == null) { command.Reply("could not find any IRC data by {0}. Did you spell their name correctly?", nick); return; } string topicString; if (showDebugInfo) { topicString = string.Join(", ", topics.Take(20).Select(pair => $"\x02{pair.Name}\x02 ({pair.UserCount}/{pair.GlobalCount}: {pair.Score:N2})")); } else { topicString = string.Join(", ", topics.Take(20).Select(pair => pair.Name)); } command.Reply("words associated with {0}: {1}", nick, topicString); }
public override void Use(CommandArgs command) { var method = command.Args[0].ToUpper(); var url = command.Args[1]; if (url.StartsWith("file://")) { command.Reply("you sneaky bastard; you didn't think I was going to allow that, did you?"); return; } if (!url.StartsWith("http")) { url = "http://" + url; } var body = string.Join(" ", command.Args.Skip(2)); string response; using (var client = new WebClient()) { client.Headers.Add("User-Agent", $"BaggyBot/{Bot.Version} ({Environment.OSVersion}) IRC stats bot"); try { if (method == "GET") { response = client.DownloadString(url); } else { response = client.UploadString(url, method, body); } command.ReturnMessage("Response: " + response); } catch (WebException e) { command.ReturnMessage("The HTTP request failed ({0}).", e.Message); } } }
private void ProcessCommand(CommandArgs cmdInfo) { // Inject bot information, but do not return. if (new[] { "help", "about", "info", "baggybot", "stats" }.Contains(cmdInfo.Command.ToLower()) && cmdInfo.Args.Length == 0) { cmdInfo.ReturnMessage(string.Format(Messages.CmdGeneralInfo, Bot.Version, ConfigManager.Config.StatsPage)); } if (!commands.ContainsKey(cmdInfo.Command)) { if (cmdInfo.Command == "rem") { Logger.Log(this, "Saving rem"); var value = cmdInfo.Args.ToList(); value.Insert(1, "say"); ((Alias)commands["alias"]).Use( new CommandArgs("alias", value.ToArray(), cmdInfo.Sender, cmdInfo.Channel, string.Join(" ", value))); } else if (((Alias)commands["alias"]).ContainsKey(cmdInfo.Client.StatsDatabase, cmdInfo.Command)) { var aliasedCommand = ((Alias)commands["alias"]).GetAlias(cmdInfo.Client.StatsDatabase, cmdInfo.Command); if(cmdInfo.FullArgument == null) { aliasedCommand = aliasedCommand.Replace(" $args", ""); } else { aliasedCommand = aliasedCommand.Replace("$args", cmdInfo.FullArgument); } Logger.Log(this, $"Calling aliased command: -{aliasedCommand}"); ProcessCommand(CommandArgs.FromMessage(new IrcMessage(cmdInfo.Client, cmdInfo.Sender, cmdInfo.Channel, "-" + aliasedCommand))); //ProcessCommand(new IrcMessage(message.Sender, message.Channel, "-" + aliasedCommand, message.ReplyCallback, message.Action)); } return; } if (commands[cmdInfo.Command].Permissions == PermissionLevel.All || commands[cmdInfo.Command].Permissions == PermissionLevel.BotOperator && UserTools.Validate(cmdInfo.Sender)) { // Don't gobble up exceptions when debugging if (ConfigManager.Config.DebugMode) { commands[cmdInfo.Command].Use(cmdInfo); } else { try { commands[cmdInfo.Command].Use(cmdInfo); } catch (Exception e) { var exceptionMessage = $"An unhandled exception (type: {e.GetType()}) occurred while trying to process your command! Exception message: \"{e.Message}\""; cmdInfo.ReturnMessage(exceptionMessage); // Previously, debugging information (filename and line number) were put in the error message. // That's dubm, no reason to bother the user with information that's useless to them. Log the exception instead. Logger.LogException(commands[cmdInfo.Command], e, $"processing the command \"{cmdInfo.Command} {cmdInfo.FullArgument}\""); } } } else { cmdInfo.ReturnMessage(Messages.CmdNotAuthorised); } }
public override void Use(CommandArgs command) { // TODO: Implemenent self-updating throw new NotImplementedException(); }
public static CommandArgs FromPrevious(string newCommand, string newArguments, CommandArgs context) { var args = newArguments.Split(' '); return(new CommandArgs(newCommand, args, context.Sender, context.Channel, newArguments, context.replyCallback, context.returnMessageCallback)); }
public override void Use(CommandArgs command) { var useUnicode = Client.Capabilities.SupportsSpecialCharacters; if (string.IsNullOrWhiteSpace(command.FullArgument)) { InformUsage(command); return; } if (command.FullArgument == "more") { var more = ShowMore(); if (more == null) { command.ReturnMessage("No more information available."); } else { var secondItem = ShowMore(); if (secondItem != null) { more += " -- " + secondItem; } command.ReturnMessage(ReplaceNewlines(more)); } return; } lastDisplayedResult = null; var appid = ConfigManager.Config.Integrations.WolframAlpha.AppId; var uri = $"http://api.wolframalpha.com/v2/query?appid={appid}&input={Uri.EscapeDataString(command.FullArgument)}&format=plaintext&units=metric"; // TODO: find out a way to get a user's IP address from their messages when it makes sense //var uri = $"http://api.wolframalpha.com/v2/query?appid={appid}&input={Uri.EscapeDataString(command.FullArgument)}&ip={command.Sender.Hostmask}&format=plaintext&units=metric"; //var escaped = Uri.EscapeDataString(uri); var rq = WebRequest.Create(uri); var response = rq.GetResponse(); var xmd = new XmlDocument(); xmd.Load(response.GetResponseStream()); var queryresult = xmd.GetElementsByTagName("queryresult").Item(0); if (queryresult.Attributes["success"].Value == "false") { var error = queryresult.Attributes["error"].Value; if (error == "false") { command.Reply("Unable to compute the answer."); var didyoumeans = GetDidYouMeans(xmd.GetElementsByTagName("didyoumean")); if (!string.IsNullOrEmpty(didyoumeans)) { command.ReturnMessage("Did you mean: " + didyoumeans + "?"); } } else { var errorCode = xmd.GetElementsByTagName("error").Item(0).FirstChild; var errorMessage = errorCode.NextSibling; command.Reply($"An error occurred: Error {errorCode.InnerText}: {errorMessage.InnerText}"); } return; } if (queryresult.FirstChild.Name == "assumptions") { var options = queryresult.FirstChild.FirstChild.ChildNodes; var descriptions = new List <string>(); for (var i = 0; i < options.Count; i++) { var node = options[i]; descriptions.Add("\"" + node.Attributes["desc"].Value + "\""); } var first = string.Join(", ", descriptions.Take(descriptions.Count - 1)); command.Reply($"Ambiguity between {first} and {descriptions.Last()}. Please try again."); return; } var input = queryresult.FirstChild; var title = ReplaceNewlines(input.Attributes["title"].Value); var result = ReadPod(input.NextSibling); lastDisplayedResult = input.NextSibling; if (result == null) { result = ShowMore(); } if (result.Length < 100) { result += " -- " + ShowMore(); } command.Reply($"({WaReplace(title, useUnicode)}: {ReplaceNewlines(WaReplace(input.InnerText, useUnicode))}): {ReplaceNewlines(WaReplace(result, useUnicode))}"); }
public override void Use(CommandArgs command) { if (command.Args.Length == 1) { var target = command.Args[0]; PingReply reply; try { reply = new System.Net.NetworkInformation.Ping().Send(target); } catch (PingException e) { command.ReturnMessage($"Unable to ping {target}: {e.InnerException.Message}"); return; } if (reply.Status == IPStatus.Success) { command.ReturnMessage($"Reply from {reply.Address} in {Colourise(reply.RoundtripTime)}ms{reply.RoundtripTime}{Colour(null)}"); } else { command.ReturnMessage($"Ping failed ({reply.Status})"); } } else if (command.Args.Length == 2) { var target = command.Args[0]; var attempts = int.Parse(command.Args[1]); var pings = new List <PingReply>(); long total = 0; var successCount = 0; for (var i = 0; i < attempts; i++) { pings.Add(new System.Net.NetworkInformation.Ping().Send(target)); if (pings[i].Status == IPStatus.Success) { successCount++; total += pings[i].RoundtripTime; if (pings[i].RoundtripTime < 500) { Thread.Sleep(500 - (int)pings[i].RoundtripTime); } } } var average = Math.Round(total / (double)successCount, 2); var raw = string.Join(", ", pings.Select(reply => (reply.Status == IPStatus.Success ? Colourise(reply.RoundtripTime) + reply.RoundtripTime + "ms" + Colour(null) : Colour(4) + "failed" + Colour(null)))); var word = successCount == 1 ? "reply" : "replies"; var address = pings[0].Address == null ? "Unknown IP Address" : pings[0].Address.ToString(); var number = double.IsNaN(average) ? "NaN " : average.ToString(); command.ReturnMessage($"{successCount} {word} from {address}, averaging {Colourise(average) + number + "ms" + Colour(null)} ({raw})"); } else { command.ReturnMessage("Pong!"); } }
protected abstract void Threads(CommandArgs command);
protected void ProcessControlCommand(CommandArgs command) { if (!Client.Validate(command.Sender)) { command.ReturnMessage("Python Interpreter control commands may only be used by the bot operator"); return; } var control = command.Args[0].Substring(2); switch (control) { case "security": switch (command.Args.Length) { case 1: command.Reply($"the current security level is {Security}"); break; case 2: try { SetSecurity(command.Args[1]); command.ReturnMessage("Security level set to " + Security); } catch (ArgumentException) { command.ReturnMessage($"Invalid security level: \"{string.Join(" ", command.Args.Skip(1))}\""); } break; default: command.ReturnMessage($"Invalid security level: \"{string.Join(" ", command.Args.Skip(1))}\""); break; } break; case "abort": Abort(command); break; case "toggle": ControlVariables.QueryConsole = !ControlVariables.QueryConsole; command.ReturnMessage("Interactive query console: " + (ControlVariables.QueryConsole ? "On" : "Off")); break; case "help": command.ReturnMessage("The following control commands are available: security, abort, toggle"); break; case "threads": Threads(command); break; case "buffer": GetBuffer(command); break; default: command.ReturnMessage("That is not a valid control command."); break; } }
public override void Use(CommandArgs command) { var isOperator = Client.Validate(command.Sender); if (!commandBuilders.ContainsKey(command.Sender.Nickname)) { commandBuilders.Add(command.Sender.Nickname, new StringBuilder()); } if (command.FullArgument == null) { command.Reply("Usage: -cs <C# code>"); return; } if (command.FullArgument.Contains("Console.Write")) { command.ReturnMessage("Console.Write calls are not supported yet."); return; } if (!(isOperator || RestrictionsCheck(command))) { return; } if (command.FullArgument.StartsWith("--")) { ProcessControlCommand(CommandArgs.FromPrevious(command.Command, command.FullArgument.Substring(2), command)); return; } try { var fullInput = commandBuilders[command.Sender.Nickname] + " " + command.FullArgument; fullInput = fullInput.TrimStart(); bool resultSet; object result; var input = evaluator.Evaluate(fullInput, out result, out resultSet); if (resultSet) { var output = CodeFormatter.PrettyPrint(result); command.ReturnMessage("--> " + output); commandBuilders[command.Sender.Nickname].Clear(); } else if (input == null) { if (reportPrinter.HasMessage) { while (reportPrinter.HasMessage) { var message = reportPrinter.GetNextMessage(); command.ReturnMessage($"{message.MessageType} at column {message.Location.Column}: {message.Text}"); } } else { command.ReturnMessage("Done (No result)"); } commandBuilders[command.Sender.Nickname].Clear(); } else { commandBuilders[command.Sender.Nickname].Append(input); command.ReturnMessage(">>>"); } } catch (InternalErrorException e) { command.ReturnMessage("Exception: " + e); } }
protected override void Threads(CommandArgs command) { throw new NotImplementedException("Cs.Threads"); }
protected override void GetBuffer(CommandArgs command) { command.ReturnMessage($"{command.Sender.Nickname}, \"{commandBuilders[command.Sender.Nickname].ToString().Replace('\n', '\\')}\""); }
private bool RestrictionsCheck(CommandArgs command) { if (!command.Channel.StartsWith("#")) { command.ReturnMessage("Only the bot operator is allowed to execute Python code in non-channels"); return false; } if (Security == InterpreterSecurity.Block) { command.ReturnMessage("For security reasons, the interactive C# interpreter is currently blocked. Please try again later or ask baggerboot to unblock it."); return false; } if (Security == InterpreterSecurity.Notify) { // Do not return anything yet, but do notify the bot operator. bot.NotifyOperator("-cs used by " + command.Sender.Nick + ": " + command.FullArgument); } if (command.FullArgument != null && (command.FullArgument.ToLower().Contains("ircinterface") || command.FullArgument.ToLower().Contains("datafunctionset"))) { command.ReturnMessage("Access to my guts is restricted to the operator."); return false; } if (command.FullArgument != null && command.FullArgument.Contains("Process")) { command.ReturnMessage("Process control is restricted to the operator."); return false; } if (command.FullArgument != null && command.FullArgument.Contains("GetMethod")) { command.ReturnMessage("Method invocation trough reflection is restricted to the operator."); return false; } if (command.FullArgument != null && command.FullArgument.Contains("Environment.Exit")) { command.ReturnMessage("Calls to Environment.Exit are not allowed"); return false; } return true; }
protected override void GetBuffer(CommandArgs command) { command.ReturnMessage($"{command.Sender.Nick}, \"{commandBuilders[command.Sender.Nick].ToString().Replace('\n', '\\')}\""); }
public override void Use(CommandArgs command) { ThreadId++; var isOperator = Client.Validate(command.Sender); if (!(isOperator || RestrictionsCheck(command))) { return; } if (command.FullArgument != null) { if (command.FullArgument.StartsWith("--")) { ProcessControlCommand(CommandArgs.FromPrevious(command.Command, command.FullArgument.Substring(2), command)); return; } if (command.FullArgument.EndsWith(":") || command.FullArgument.StartsWith(" ")) { commandBuilder.AppendLine(command.FullArgument); command.ReturnMessage(">>>"); return; } /*if (command.FullArgument == "import antigravity") { * command.ReturnMessage("--> https://xkcd.com/353/"); * return; * }*/ } string code; if (command.FullArgument == null && commandBuilder.ToString() != string.Empty) { code = commandBuilder.ToString(); commandBuilder.Clear(); } else if (command.FullArgument != null) { code = command.FullArgument; } else { command.Reply("Usage: -py [python code] - Leave the [python code] parameter out if you want to close the last indented block of a multi-line script."); return; } var source = engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement); threads.Add(Thread.CurrentThread); try { source.Execute(scope); var line = outputStreamReader.ReadLine(); if (line == null) { command.ReturnMessage("Done (No result)"); } else { for (var i = 0; line != null; i++) { if (i > 3 && !isOperator) { // i starts at 0, so when i=4, that would be the 5th line command.ReturnMessage("Spam prevention triggered. Sending more than 4 lines is not allowed."); outputStreamReader.ReadToEnd(); break; } command.ReturnMessage("--> " + line); line = outputStreamReader.ReadLine(); if (line != null && line.Contains("connection_string")) { line = outputStreamReader.ReadLine(); } Thread.Sleep(250); // make sure we don't spam the receiving end too much } } } catch (UnboundNameException e) { command.ReturnMessage("Error: " + e.Message); } catch (SyntaxErrorException e) { command.ReturnMessage("Syntax Error: " + e.Message); } catch (ImportException e) { command.ReturnMessage("Import Error: " + e.Message); } catch (MissingMemberException e) { command.ReturnMessage("Missing member: " + e.Message); } catch (DivideByZeroException) { command.ReturnMessage("A DivideByZeroException occurred"); } catch (Exception e) { command.ReturnMessage("Unhandled exception: " + e.GetType() + ": " + e.Message); } threads.Remove(Thread.CurrentThread); }
public void Use(CommandArgs command) { }
public override void Use(CommandArgs command) { command.ReturnMessage(interpreter.Interpret(command.FullArgument)); }
protected abstract void GetBuffer(CommandArgs command);
public override void Use(CommandArgs command) { ThreadId++; var isOperator = UserTools.Validate(command.Sender); if (!(isOperator || RestrictionsCheck(command))) { return; } if (command.FullArgument != null) { if (command.FullArgument.StartsWith("--")) { command.FullArgument = command.FullArgument.Substring(2); ProcessControlCommand(command); return; } if (command.FullArgument.EndsWith(":") || command.FullArgument.StartsWith(" ")) { commandBuilder.AppendLine(command.FullArgument); command.ReturnMessage(">>>"); return; } /*if (command.FullArgument == "import antigravity") { command.ReturnMessage("--> https://xkcd.com/353/"); return; }*/ } string code; if (command.FullArgument == null && commandBuilder.ToString() != string.Empty) { code = commandBuilder.ToString(); commandBuilder.Clear(); } else if (command.FullArgument != null) { code = command.FullArgument; } else { command.Reply("Usage: -py [python code] - Leave the [python code] parameter out if you want to close the last indented block of a multi-line script."); return; } var source = engine.CreateScriptSourceFromString(code, SourceCodeKind.SingleStatement); threads.Add(Thread.CurrentThread); try { source.Execute(scope); var line = outputStreamReader.ReadLine(); if (line == null) { command.ReturnMessage("Done (No result)"); } else { for (var i = 0; line != null; i++) { if (i > 3 && !isOperator) { // i starts at 0, so when i=4, that would be the 5th line command.ReturnMessage("Spam prevention triggered. Sending more than 4 lines is not allowed."); outputStreamReader.ReadToEnd(); break; } command.ReturnMessage("--> " + line); line = outputStreamReader.ReadLine(); if (line != null && line.Contains("connection_string")) { line = outputStreamReader.ReadLine(); } Thread.Sleep(250); // make sure we don't spam the receiving end too much } } } catch (UnboundNameException e) { command.ReturnMessage("Error: " + e.Message); } catch (SyntaxErrorException e) { command.ReturnMessage("Syntax Error: " + e.Message); } catch (ImportException e) { command.ReturnMessage("Import Error: " + e.Message); } catch (MissingMemberException e) { command.ReturnMessage("Missing member: " + e.Message); } catch (DivideByZeroException) { command.ReturnMessage("A DivideByZeroException occurred"); } catch (Exception e) { command.ReturnMessage("Unhandled exception: " + e.GetType() + ": " + e.Message); } threads.Remove(Thread.CurrentThread); }
protected abstract void Abort(CommandArgs command);
protected override void GetBuffer(CommandArgs command) { command.ReturnMessage($"{command.Sender.Nickname}, \"{commandBuilder}\""); }
protected override void Abort(CommandArgs command) { evaluator.Interrupt(); }
public override void Use(CommandArgs command) { StatsDatabase.Reset(); command.Reply("the database has been reset successfully."); }
protected override void Threads(CommandArgs command) { throw new NotImplementedException("Cs.Threads"); }
public override void Use(CommandArgs command) { // TODO: Implemenent self-updating throw new NotImplementedException(); }
public override void Use(CommandArgs command) { var isOperator = UserTools.Validate(command.Sender); if (!commandBuilders.ContainsKey(command.Sender.Nick)) { commandBuilders.Add(command.Sender.Nick, new StringBuilder()); } if (command.FullArgument == null) { command.Reply("Usage: -cs <C# code>"); return; } if (command.FullArgument.Contains("Console.Write")) { command.ReturnMessage("Console.Write calls are not supported yet."); return; } if (!(isOperator || RestrictionsCheck(command))) { return; } if (command.FullArgument.StartsWith("--")) { command.FullArgument = command.FullArgument.Substring(2); ProcessControlCommand(command); return; } try { var fullInput = commandBuilders[command.Sender.Nick] + " " + command.FullArgument; fullInput = fullInput.TrimStart(); bool resultSet; object result; var input = evaluator.Evaluate(fullInput, out result, out resultSet); if (resultSet) { var output = CodeFormatter.PrettyPrint(result); command.ReturnMessage("--> " + output); commandBuilders[command.Sender.Nick].Clear(); } else if (input == null) { if (reportPrinter.HasMessage) { while (reportPrinter.HasMessage) { var message = reportPrinter.GetNextMessage(); command.ReturnMessage($"{message.MessageType} at column {message.Location.Column}: {message.Text}"); } } else { command.ReturnMessage("Done (No result)"); } commandBuilders[command.Sender.Nick].Clear(); } else { commandBuilders[command.Sender.Nick].Append(input); command.ReturnMessage(">>>"); } } catch (InternalErrorException e) { command.ReturnMessage("Exception: " + e); } }
protected override void Abort(CommandArgs command) { evaluator.Interrupt(); }