示例#1
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}");
            }
        }
示例#2
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}");
            }
        }
示例#3
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]);
            }
        }
示例#4
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);
            }
        }
示例#5
0
        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!");
            }
        }
示例#6
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]);
            }
        }
示例#7
0
        protected override void Threads(CommandArgs command)
        {
            var result = string.Join(", ", threads.Select(t => t.Name));

            if (result.Length == 0)
            {
                command.ReturnMessage("Active threads: " + threads);
            }
            else
            {
                command.ReturnMessage("No Python threads running right now.");
            }
        }
示例#8
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;
            }
        }
示例#9
0
 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));
     }
 }
示例#10
0
 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));
     }
 }
示例#11
0
文件: Sql.cs 项目: lulzzz/BaggyBot-2
        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);
                }
            }
        }
示例#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())}");
            }
        }
示例#13
0
        public override void Use(CommandArgs command)
        {
            var showDebugInfo = false;
            var args          = command.Args;

            if (command.Args.Length > 0 && command.Args[0] == "-d")
            {
                args          = command.Args.Skip(1).ToArray();
                showDebugInfo = true;
            }
            if (args.Length == 0)
            {
                ShowTopics(command.Sender.Nickname, command.Channel.Identifier, command, showDebugInfo);
            }
            else if (args.Length > 2)
            {
                command.ReturnMessage("Usage: -topics [nick]");
            }
            else if (args.Length == 2)
            {
                ShowTopics(args[0], Client.FindChannel(args[1]).Identifier, command, showDebugInfo);
            }
            else
            {
                ShowTopics(args[0], command.Channel.Identifier, command, showDebugInfo);
            }
        }
示例#14
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;
            }
        }
示例#15
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);
            }
        }
示例#16
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);
        }
示例#17
0
文件: Part.cs 项目: lulzzz/BaggyBot-2
 public override void Use(CommandArgs command)
 {
     if (command.Args.Length == 0 || command.Args.Length > 2)
     {
         command.ReturnMessage("usage: -part <channel> [reason]");
     }
     else
     {
         Client.Part(command.Args[0], command.Args.Length == 2 ? command.Args[1] : null);
     }
 }
示例#18
0
 protected override void Abort(CommandArgs command)
 {
     Security = InterpreterSecurity.Block;
     commandBuilder.Clear();
     foreach (var thread in threads)
     {
         thread.Abort();
     }
     command.ReturnMessage($"Done. {threads.Count} running threads have been aborted.");
     threads.Clear();
 }
示例#19
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);
        }
示例#20
0
        public override void Use(CommandArgs command)
        {
            var botBit      = Environment.Is64BitProcess ? "64" : "32";
            var osBit       = Environment.Is64BitOperatingSystem ? "64" : "32";
            var hasDebugger = Debugger.IsAttached ? "(Debugger attached)" : "";

#if DEBUG
            var build = "Debug Build";
#else
            var build = "Release Build";
#endif
            var message = $"BaggyBot {Bot.Version} ({botBit}-bit) -- Running on {Environment.OSVersion.VersionString} ({osBit}-bit) -- {build} {hasDebugger}";
            command.ReturnMessage(message);
        }
示例#21
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);
         }
     }
 }
示例#22
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");
        }
示例#23
0
        public override void Use(CommandArgs command)
        {
            var user = command.Sender;
            var sb   = new StringBuilder();

            if (user.PreferredName == null)
            {
                sb.Append($"Your nickname appears to be {user.Nickname}.");
            }
            else
            {
                sb.Append($"Your nickname appears to be {user.Nickname}, though you prefer to call yourself {user.PreferredName}.");
            }
            sb.Append($" Your unique userID is {user.UniqueId}, and you're posting in the channel \"{command.Channel.Name}\" ({command.Channel.Identifier}).");
            command.ReturnMessage(sb.ToString());
        }
示例#24
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;
            }
        }
示例#25
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}");
            }
        }
示例#26
0
文件: Help.cs 项目: lulzzz/BaggyBot-2
 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
     {
     }
 }
示例#27
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
            {

            }
        }
示例#28
0
 /// <summary>
 /// This method checks if a regular user (non-operator) is allowed to execute the given command.
 /// </summary>
 /// <param name="command">The command that should be checked.</param>
 /// <returns>True if the user is allowed to execute the command, false if only the bot operator may execute it.</returns>
 private bool RestrictionsCheck(CommandArgs command)
 {
     if (command.Channel.IsPrivateMessage)
     {
         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 Python interpreter is currently blocked. Please try again later or ask Baggykiin to unblock it.");
         return(false);
     }
     if (Security == InterpreterSecurity.Notify)
     {
         // Do not return anything yet, but do notify the bot operator.
         Client.NotifyOperators("-py used by " + command.Sender.Nickname + ": " + 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("System.Diagnostics.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("import posix"))
     {
         command.ReturnMessage("Posix module calls are restricted to the operator.");
         return(false);
     }
     if (command.FullArgument != null && ((command.FullArgument.Contains("putenv") || command.FullArgument.Contains("listdir") || command.FullArgument.Contains("mkdir") || command.FullArgument.Contains("makedirs") || command.FullArgument.Contains("remove") || command.FullArgument.Contains("rename") || command.FullArgument.Contains("rmdir") || command.FullArgument.Contains("exit")) && command.FullArgument.Contains("os")))
     {
         command.ReturnMessage("Posix module calls are restricted to the operator.");
         return(false);
     }
     return(true);
 }
示例#29
0
        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");
        }
示例#30
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);
     }
 }
示例#31
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);
            }
        }
示例#32
0
 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);
     }
 }
示例#33
0
 private bool RestrictionsCheck(CommandArgs command)
 {
     if (command.Channel.IsPrivateMessage)
     {
         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 Baggykiin to unblock it.");
         return(false);
     }
     if (Security == InterpreterSecurity.Notify)
     {
         // Do not return anything yet, but do notify the bot operator.
         Client.NotifyOperators("-cs used by " + command.Sender.Nickname + ": " + 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);
 }
示例#34
0
 protected override void GetBuffer(CommandArgs command)
 {
     command.ReturnMessage($"{command.Sender.Nickname}, \"{commandBuilder}\"");
 }
示例#35
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());
                }
            }
        }
示例#36
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)));
        }
示例#37
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))}");
        }
示例#38
0
 public override void Use(CommandArgs command)
 {
     command.ReturnMessage(interpreter.Interpret(command.FullArgument));
 }
示例#39
0
 protected override void Abort(CommandArgs command)
 {
     Security = InterpreterSecurity.Block;
     commandBuilder.Clear();
     foreach (var thread in threads)
     {
         thread.Abort();
     }
     command.ReturnMessage($"Done. {threads.Count} running threads have been aborted.");
     threads.Clear();
 }
示例#40
0
        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;
            }
        }
示例#41
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);
            }
        }
示例#42
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);
        }
示例#43
0
        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);
            }
        }
示例#44
0
 /// <summary>
 /// This method checks if a regular user (non-operator) is allowed to execute the given command.
 /// </summary>
 /// <param name="command">The command that should be checked.</param>
 /// <returns>True if the user is allowed to execute the command, false if only the bot operator may execute it.</returns>
 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 Python 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("-py 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("System.Diagnostics.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("import posix"))
     {
         command.ReturnMessage("Posix module calls are restricted to the operator.");
         return false;
     }
     if (command.FullArgument != null && ((command.FullArgument.Contains("putenv") || command.FullArgument.Contains("listdir") || command.FullArgument.Contains("mkdir") || command.FullArgument.Contains("makedirs") || command.FullArgument.Contains("remove") || command.FullArgument.Contains("rename") || command.FullArgument.Contains("rmdir") || command.FullArgument.Contains("exit")) && command.FullArgument.Contains("os")))
     {
         command.ReturnMessage("Posix module calls are restricted to the operator.");
         return false;
     }
     return true;
 }
示例#45
0
 protected override void Threads(CommandArgs command)
 {
     var result = string.Join(", ", threads.Select(t => t.Name));
     if (result.Length == 0)
     {
         command.ReturnMessage("Active threads: " + threads);
     }
     else
     {
         command.ReturnMessage("No Python threads running right now.");
     }
 }
示例#46
0
 protected override void GetBuffer(CommandArgs command)
 {
     command.ReturnMessage($"{command.Sender.Nick}, \"{commandBuilder}\"");
 }
示例#47
0
        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);
        }
示例#48
0
文件: Ping.cs 项目: lulzzz/BaggyBot-2
        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!");
            }
        }
示例#49
0
        public override void Use(CommandArgs command)
        {
            var cmdParser = new CommandParser(new Operation())
                            .AddOperation("cfg", new Operation()
                                          .AddArgument("config-key"))
                            .AddOperation("uid", new Operation()
                                          .AddArgument("user", command.Sender.Nickname))
                            .AddOperation("users", new Operation()
                                          .AddArgument("channel", command.Channel.Name))
                            .AddOperation("channels", new Operation())
                            .AddOperation("channel", new Operation()
                                          .AddArgument("query", command.Channel.Identifier)
                                          .AddFlag("by-name"))
                            .AddOperation("messages", new Operation()
                                          .AddKey("channel", null, 'c')
                                          .AddKey("channel-id", command.Channel.Identifier, 'C')
                                          .AddKey("count", 5, 'n')
                                          .AddKey("before", DateTime.MaxValue, 'b')
                                          .AddKey("after", DateTime.MinValue, 'a'));

            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":
                GetCfg(command, result);
                break;

            case "channel":
                GetChannel(command, result);
                break;

            case "uid":
                GetUid(command, result);
                break;

            case "users":
                GetUsers(command, result);
                break;

            case "channels":
                GetChannels(command);
                break;

            case "messages":
                GetMessages(command, result);
                break;
            }
        }
示例#50
0
 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;
 }
示例#51
0
 protected override void GetBuffer(CommandArgs command)
 {
     command.ReturnMessage($"{command.Sender.Nick}, \"{commandBuilders[command.Sender.Nick].ToString().Replace('\n', '\\')}\"");
 }
示例#52
0
 public override void Use(CommandArgs command)
 {
     command.ReturnMessage(interpreter.Interpret(command.FullArgument));
 }
示例#53
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);
            }
        }
示例#54
0
 protected override void GetBuffer(CommandArgs command)
 {
     command.ReturnMessage($"{command.Sender.Nickname}, \"{commandBuilders[command.Sender.Nickname].ToString().Replace('\n', '\\')}\"");
 }