Esempio n. 1
0
        public override void Use(CommandArgs command)
        {
            var query = command.FullArgument;

            if (query == null)
            {
                InformUsage(command);
                return;
            }
            var image = bing.ImageSearch(query);

            if (image == null)
            {
                command.Reply("there don't seem to be any results.");
            }
            else
            {
                var imageUrl = WebUtility.UrlEncode(image.contentUrl);
                var title    = WebUtility.UrlEncode(image.name);
                var descr    = WebUtility.UrlEncode("From " + image.hostPageDisplayUrl);

                var result = Post <UploadResponse>($"https://api.imgur.com/3/image?type=url&image={imageUrl}&title={title}&description={descr}");


                command.Reply($"{result?.data?.link ?? image.contentUrl}");
            }
        }
Esempio n. 2
0
        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);
            }
        }
Esempio n. 3
0
        private void ShowTopics(string nick, string channel, CommandArgs command, bool showDebugInfo)
        {
            Logger.Log(this, "Showing topics for " + nick);
            var user   = StatsDatabase.GetUserByNickname(nick);
            var topics = StatsDatabase.FindTopics(user.Id, channel);

            if (topics == null)
            {
                command.Reply($"could not find any IRC data by {nick}. Did you spell their name correctly?");
                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 {nick}: {topicString}");
        }
Esempio n. 4
0
        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);
            }
        }
Esempio n. 5
0
        private void GetCfg(CommandArgs command, OperationResult result)
        {
            if (!Client.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}");
        }
Esempio n. 6
0
 public override void Use(CommandArgs command)
 {
     if (command.Args.Length == 1)
     {
         command.Reply($"Joining {command.Args[0]}");
         Client.JoinChannel(command.Args[0]);
     }
     else
     {
         command.Reply("Usage: -join <channel>");
     }
 }
Esempio n. 7
0
        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]);
            }
        }
Esempio n. 8
0
        private void GetUsers(CommandArgs command, OperationResult result)
        {
            var channel = result.Arguments["channel"];

            if (Client.InChannel(Client.FindChannel(channel)))
            {
                var ircChannel = Client.FindChannel(channel);
                command.Reply($"users in {channel}: {string.Join(", ", ircChannel.Users.Count)}");
            }
            else
            {
                command.Reply("I'm not in that channel.");
            }
        }
Esempio n. 9
0
        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;
            }
        }
Esempio n. 10
0
        public override void Use(CommandArgs command)
        {
            var parser = new CommandParser(new Operation()
                                           .AddKey("rows", 3, 'r')
                                           .AddFlag("tables", 't')
                                           .AddRestArgument(string.Empty));
            var parsed = parser.Parse(command.FullArgument);

            if (parsed.Flags["tables"])
            {
                command.Reply($"the following tables are available: {string.Join(", ", StatsDatabase.GetTableNames())}");
                return;
            }
            if (string.IsNullOrWhiteSpace(parsed.RestArgument))
            {
                InformUsage(command);
                return;
            }

            var table = StatsDatabase.ExecuteQuery(parsed.RestArgument);

            if (table.Rows.Count == 0)
            {
                command.Reply("done.");
                return;
            }

            var maxRows = parsed.GetKey <int>("rows");

            var columnLengths = GetColumnLengths(table, maxRows);

            if (Client.Capabilities.AllowsMultilineMessages)
            {
                var dividerLength = columnLengths.Sum() + (columnLengths.Length - 1) * " | ".Length;
                var divider       = string.Concat(Enumerable.Repeat('=', dividerLength));
                command.ReturnMessage($"{Frm.MMultiline}{PrintHeader(table, columnLengths)}\n{divider}\n{PrintBody(table, columnLengths, maxRows)}{Frm.MMultiline}");
            }
            else
            {
                var header = $"{Frm.U}{PrintHeader(table, columnLengths)}{Frm.U}";
                var lines  = PrintBody(table, columnLengths, maxRows).Split('\n');
                command.ReturnMessage(header);
                foreach (var line in lines)
                {
                    command.ReturnMessage(line);
                }
            }
        }
Esempio n. 11
0
        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}");
            }
        }
Esempio n. 12
0
        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=info&inprop=url");

            var         rq = WebRequest.Create(uri);
            WebResponse response;

            try
            {
                response = rq.GetResponse();
            }
            catch (WebException e)
            {
                command.Reply($"Unable to query Wikipedia. {e.Message}");
                return;
            }
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                var     data    = sr.ReadToEnd();
                dynamic jsonObj = JObject.Parse(data);
                var     page    = ((JObject)jsonObj.query.pages).First.First;
                var     title   = page["title"];

                command.ReturnMessage($"{title} ({page["canonicalurl"]}): {GetContent(page["canonicalurl"].ToString())}");
            }
        }
Esempio n. 13
0
        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}");
            }
        }
Esempio n. 14
0
        public override void Use(CommandArgs command)
        {
            var parser = new CommandParser(new Operation())
                         .AddOperation("name", new Operation()
                                       .AddFlag("uid", 'u')
                                       .AddArgument("match"))
                         .AddOperation("cfg", new Operation()
                                       .AddArgument("key")
                                       .AddRestArgument("value"));

            var cmd = parser.Parse(command.FullArgument);

            switch (cmd.OperationName)
            {
            case "name":
                SetName(cmd.Arguments["match"], cmd.Flags["uid"], cmd.RestArgument);
                command.Reply("Done");
                break;

            case "cfg":
                SetCfg();
                break;

            default:
                InformUsage(command);
                break;
            }
        }
Esempio n. 15
0
        public override void Use(CommandArgs command)
        {
            if (command.FullArgument == null)
            {
                InformUsage(command);
                return;
            }

            var parser = new CommandParser(new Operation()
                                           .AddKey("max-results", 1, 'r')
                                           .AddKey("uid", -1, 'u')
                                           .AddKey("nickname", null, 'n')
                                           .AddRestArgument());

            var result       = parser.Parse(command.FullArgument);
            var numDisplayed = result.GetKey <int>("max-results");

            if (numDisplayed > 3 && !Client.Validate(command.Sender))
            {
                command.Reply("only bot operators may request more than three results.");
                return;
            }
            var uid      = result.GetKey <int>("uid");
            var nickname = result.Keys["nickname"];
            var query    = result.RestArgument;

            var matches = StatsDatabase.FindLine(query, uid, nickname);

            switch (matches.Count)
            {
            case 0:
                command.Reply("no matches found.");
                break;

            case 1:
                command.Reply("1 match found: " + matches[0]);
                break;

            default:
                command.Reply($"{matches.Count} matches ({numDisplayed} displayed):");
                foreach (var match in matches.Take(numDisplayed))
                {
                    command.ReturnMessage($"{match}");
                }
                break;
            }
        }
Esempio n. 16
0
        private void GetUid(CommandArgs command, OperationResult result)
        {
            var users = StatsDatabase.GetUsersByNickname(result.Arguments["user"]);

            if (users.Length == 0)
            {
                command.Reply($"I don't know a user with {result.Arguments["user"]} as their primary name");
            }
            else if (users.Length == 1)
            {
                command.Reply($"I found the following user for {result.Arguments["user"]}: {users[0]}");
            }
            else
            {
                command.Reply($"Multiple matches found for {result.Arguments["user"]}: {string.Join(", ", users.Select(u => u.Id))}");
            }
        }
Esempio n. 17
0
        public override void Use(CommandArgs command)
        {
            var messages = StatsDatabase.GetMessages();

            var usage = messages.SelectMany(m => WordTools.GetWords(m.Message)).GroupBy(w => w).ToDictionary(g => g.Key, g => g.Count());

            StatsDatabase.IncrementWords(usage);
            command.Reply("done.");
        }
Esempio n. 18
0
 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);
 }
Esempio n. 19
0
        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 {d}, {h}, {m} and {s}");
        }
Esempio n. 20
0
        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;
            }
        }
Esempio n. 21
0
        public override void Use(CommandArgs command)
        {
            if (command.Args.Length != 1)
            {
                InformUsage(command);
                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]);
            }
        }
Esempio n. 22
0
        public override void Use(CommandArgs command)
        {
            var query = command.FullArgument;

            if (query == null)
            {
                InformUsage(command);
                return;
            }
            var url = bing.WebSearch(query);

            if (url == null)
            {
                command.Reply("there don't seem to be any results.");
            }
            else
            {
                command.Reply($"{url.displayUrl} -- {url.snippet}");
            }
        }
Esempio n. 23
0
        private void GetChannel(CommandArgs command, OperationResult result)
        {
            ChatChannel channel;

            if (result.Flags["by-name"])
            {
                try
                {
                    channel = Client.FindChannel(result.Arguments["query"]);
                }
                catch (ArgumentException e)
                {
                    command.Reply(e.Message);
                    return;
                }
            }
            else
            {
                channel = Client.GetChannel(result.Arguments["query"]);
            }
            command.Reply($"{result.Arguments["query"]} maps to {channel.Name}:{channel.Identifier} {(channel.IsPrivateMessage ? "(private message)" : "")}");
        }
Esempio n. 24
0
        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;
            }
        }
Esempio n. 25
0
        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);
        }
Esempio n. 26
0
        public override void Use(CommandArgs command)
        {
            var parser = new CommandParser(new Operation()
                                           .AddKey("channel-name", null, 'c')
                                           .AddKey("channel-id", command.Channel.Identifier, 'C'));

            var result      = parser.Parse(command.FullArgument);
            var channelName = result.Keys["channel-name"];
            var channelId   = result.Keys["channel-id"];

            var channel = channelName != null?Client.FindChannel(channelName) : Client.GetChannel(channelId);

            var cutoff = DateTime.Now;

            // TODO: we probably want to drop any messages before the cutoff point to prevent duplicates

            command.Reply("this might take a while...");

            var messages = Client.GetBacklog(channel, cutoff, DateTime.MinValue).Select(m =>
            {
                m.Sender.BindDbUser(StatsDatabase.UpsertUser(m.Sender));
                return(m);
            }).ToList();

            var sorted   = messages.OrderBy(m => m.SentAt).ToList();
            var inserted = StatsDatabase.Import(sorted);

            if (sorted.Count == inserted)
            {
                command.Reply("done!");
            }
            else
            {
                command.Reply($"something went wrong. {inserted} out of {messages.Count} messages have been inserted.");
            }
        }
Esempio n. 27
0
        private void GetMessages(CommandArgs command, OperationResult result)
        {
            var channelId   = result.Keys["channel-id"];
            var channelName = result.Keys["channel"];
            var count       = result.GetKey <int>("count");
            var before      = result.GetKey <DateTime>("before");
            var after       = result.GetKey <DateTime>("after");

            var channel = channelName != null?Client.FindChannel(channelName) : Client.GetChannel(channelId);

            foreach (var message in Client.GetBacklog(channel, before, after).Take(count))
            {
                command.ReturnMessage($"{message}");
            }
            command.Reply("Done");
        }
Esempio n. 28
0
        public override void Use(CommandArgs command)
        {
            if (string.IsNullOrWhiteSpace(command.FullArgument))
            {
                InformUsage(command);
                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 : $" - {Frm.I}{example}{Frm.I}";


                command.ReturnMessage($"\u0002{name}\u0002: {definition}{exampleString} - {permalink}");
            }
        }
Esempio n. 29
0
        // 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);
            }
        }
Esempio n. 30
0
        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);
            }
        }
Esempio n. 31
0
 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);
     }
 }
Esempio n. 32
0
 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);
         }
         StatsDatabase.UpsertMiscData("alias", key, value);
         command.Reply($"I've aliased {key} to \"{value}\"");
     }
     else
     {
         InformUsage(command);
     }
 }
Esempio n. 33
0
        public override void Use(CommandArgs command)
        {
            var search = command.FullArgument;

            var searchResults = StatsDatabase.FindQuote(search);

            if (searchResults.Count == 0)
            {
                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 + "\"");
            StatsDatabase.SetVar("featured_quote", searchResults[0].Id);
        }
Esempio n. 34
0
 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($"{Frm.B}{command.Args[0]}{Frm.B}: {cmd.Description} (usable by {cmd.Permissions}) -- {Frm.B}Usage{Frm.B}: {Frm.M}{command.Args[0]} {cmd.Usage}{Frm.M}");
         }
     }
     else
     {
     }
 }
Esempio n. 35
0
        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
            {

            }
        }
Esempio n. 36
0
        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);
        }
Esempio n. 37
0
 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);
     }
 }
Esempio n. 38
0
        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);
            }
        }
Esempio n. 39
0
 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);
         }
     }
 }
Esempio n. 40
0
        private void GetChannels(CommandArgs command)
        {
            var channels = string.Join(", ", Client.Channels.Select(c => c.Name));

            command.Reply("I am a member of the following channels: " + channels);
        }
Esempio n. 41
0
 public void InformUsage(CommandArgs cmd)
 {
     cmd.Reply($"usage: {Frm.M}{Bot.CommandIdentifiers.First()}{cmd.Command} {Usage}{Frm.M} -- {Description}");
 }
Esempio n. 42
0
        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);
            }
        }
Esempio n. 43
0
        public override void Use(CommandArgs command)
        {
            var server = ConfigManager.Config.Servers.FirstOrDefault(s => s.ServerName == command.Client.ServerName);
            var useUnicode = server?.UseUnicode ?? true;

            if (string.IsNullOrWhiteSpace(command.FullArgument))
            {
                command.Reply(
                    "Usage: '-wa <WolframAlpha query>' -- Displays information acquired from http://www.wolframalpha.com. In addition to this, you can use the command '-wa more' to display additional information about the last subject");
                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)}&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 {0}: {1}", 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 {0} and {1}. Please try again.", first, descriptions.Last());
                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("({0}: {1}): {2}", WaReplace(title, useUnicode), ReplaceNewlines(WaReplace(input.InnerText, useUnicode)), ReplaceNewlines(WaReplace(result, useUnicode)));
        }
Esempio n. 44
0
        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))}");
        }
Esempio n. 45
0
 public override void Use(CommandArgs command)
 {
     StatsDatabase.Reset();
     command.Reply("the database has been reset successfully.");
 }
Esempio n. 46
0
        public override void Use(CommandArgs command)
        {
            if (command.Args.Length == 0)
            {
                InformUsage(command);
            }
            var parser = new CommandParser(new Operation()
                                           .AddArgument("method", "GET")
                                           .AddArgument("url")
                                           .AddFlag("follow-redirects", 'f')
                                           .AddFlag("show-headers", 'h')
                                           .AddKey("content-type", 'c')
                                           .AddRestArgument());

            var cmd = parser.Parse(command.FullArgument);

            var url = cmd.Arguments["url"];

            if (!url.Contains("://"))
            {
                url = "http://" + url;
            }

            var request = WebRequest.CreateHttp(url);

            request.Method            = cmd.Arguments["method"].ToUpper();
            request.AllowAutoRedirect = cmd.Flags["follow-redirects"];
            request.ContentType       = cmd.Keys["content-type"] ?? request.ContentType;
            if (cmd.RestArgument != null)
            {
                using (var sw = new StreamWriter(request.GetRequestStream()))
                {
                    sw.Write(cmd.RestArgument);
                }
            }
            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                response = (HttpWebResponse)e.Response;
            }
            if (response == null)
            {
                command.Reply("failed to connect to the server.");
            }
            else
            {
                var sb = new StringBuilder();
                if (cmd.Flags["show-headers"] || request.Method == "HEAD")
                {
                    foreach (var header in response.Headers.AllKeys)
                    {
                        sb.AppendLine($"{header}: {response.Headers[header]}");
                    }
                }
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    var text = reader.ReadToEnd();
                    if (string.IsNullOrEmpty(text))
                    {
                        sb.AppendLine("(Empty response)");
                    }
                    else
                    {
                        sb.AppendLine(text);
                    }
                }
                if (Client.Capabilities.AllowsMultilineMessages)
                {
                    command.ReturnMessage($"{Frm.MMultiline}{sb}{Frm.MMultiline}");
                }
                else
                {
                    command.ReturnMessage(sb.Replace("\n", "").Replace("\r", "\n").ToString());
                }
            }
        }
Esempio n. 47
0
        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);
            }
        }
Esempio n. 48
0
        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);
        }