Пример #1
0
        private string AreYouSure(ParsedLine line)
        {
            ClearCommandHistory(line.User.Id);
            commandQueue.TryAdd(line.User.Id, line);

            return(string.Format("Are you sure you want to run: '{0}'?", line.Raw));
        }
Пример #2
0
        public IObservable<string> Evaluate(ParsedLine line)
        {
            if(!line.IsCommand || line.Command.ToLower() != "reminder")
            {
                return null;
            }

            string help = "!reminder [time] [message]";

            // Verify we have enough arguments
            if(line.Args.Length < 2)
            {
                return Observable.Return(help);
            }

            DateTimeOffset time;

            // Parse the arguments
            if(!DateTimeOffset.TryParse(line.Args[0], out time))
            {
                return Observable.Return(help);
            }

            // We want anything entered after the time to be included in the reminder
            string message = line.Args.Skip(1).Aggregate(String.Empty, (s, s1) => s + (s.Length == 0 ? "" : " ") + s1);

            // Create an sequence that fires off single value at a specified time
            // and transform that value into the reminder message
            IObservable<string> seq = Observable.Timer(time).Select(l => message);

            // Add a start message
            return Observable.Return(String.Format("Will do - I'll remind you at {0}.", time))
                             .Concat(seq);
        }
Пример #3
0
        public static string Execute(Command command, ParsedLine line)
        {
            var standardArgs = "-NoLogo -OutputFormat Text -NonInteractive -WindowStyle Hidden -NoProfile -EncodedCommand ";

            var cmd = ResponseFormatter.Format(command, line);

            cmd = Convert.ToBase64String(Encoding.Unicode.GetBytes(cmd));

            var args = standardArgs + cmd;

            var info = new ProcessStartInfo
                {
                    FileName = "powershell.exe",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    Arguments = args
                };

            var proc = new Process {StartInfo = info};
            proc.Start();

            var sb = new StringBuilder();

            while (!proc.StandardOutput.EndOfStream)
            {
                var s = proc.StandardOutput.ReadLine();
                sb.Append(s + "\r\n");
            }

            return sb.ToString();
        }
Пример #4
0
        public string Evaluate(ParsedLine line)
        {
            if(!line.IsCommand)
            {
                return string.Empty;
            }

            if(line.Command.ToLower() == "help")
            {
                return "Here are the commands I know: \n" + _commands.OrderBy(c => c.Value).Aggregate(String.Empty,
                    (s, command) => s + (s.Length > 0 ? "\n" : "") + (String.IsNullOrEmpty(command.Help) ? ("!" + command.ChatCommand) : command.Help));
            }

            foreach(Command command in _commands)
            {
                if(command.ChatCommand.ToLower() == line.Command.ToLower())
                {
                    if(command.Value == "FormatResponse")
                    {
                        return ResponseFormatter.Format(command, line);
                    }

                    if(command.Value == "Shell")
                    {
                        return Shell.Execute(command, line);
                    }
                }
            }

            return null;
        }
Пример #5
0
        public static string Format(Command command, ParsedLine line)
        {
            var formatString = command.Parameters.First().Eval(line);

            return String.Format(formatString,
                command.Parameters.Skip(1).Select(p => p.Eval(line)).ToArray());
        }
        public string Evaluate(ParsedLine line)
        {
            if(line.IsCommand)
            {
                return null;
            }

            foreach(PotentialResponse potentialResponse in _responses)
            {
                if(potentialResponse.ExactMatch)
                {
                    if(line.Raw == potentialResponse.Trigger)
                    {
                        return potentialResponse.Text;
                    }
                }

                if(potentialResponse.ExactMatch == false)
                {
                    if(line.Raw.ToLower().Contains(potentialResponse.Trigger.ToLower()))
                    {
                        return potentialResponse.Text;
                    }
                }
            }

            return null;
        }
Пример #7
0
        public string Evaluate(ParsedLine line)
        {
            if(line.IsCommand)
            {
                return null;
            }

            if(!_users.ContainsKey(line.User))
            {
                _users[line.User] = new User(line.User, _bot);
            }

            if(_conversing)
            {
                // Check for stop triggers
                if(_config.StopTriggers.Any(trigger => trigger.Matches(line.Raw)))
                {
                    _conversing = false;
                    return "Good talk, " + line.User;
                }
            }
            else if(_config.StartTriggers.Any(trigger => trigger.Matches(line.Raw)))
            {
                _conversing = true;
                return _bot.Respond(line.Raw, _users[line.User]) + " [By the way, if my chattering starts to get annoying, you can type 'Stop Talking' and I might.]";
            }

            if(_conversing)
            {
                return _bot.Respond(line.Raw, _users[line.User]);
            }

            return null;
        }
        private string AreYouSure(ParsedLine line)
        {
            ClearCommandHistory(line.User.Id);
            commandQueue.TryAdd(line.User.Id, line);

            return string.Format("Are you sure you want to run: '{0}'?", line.Raw);
        }
        public void should_not_have_responses()
        {
            var plugin = new RandomChatterPlugin("no_responses.config");

            var pl = new ParsedLine("This is a random line", "bob");

            plugin.Evaluate(pl).Should().BeNull("No responses in loaded file");
        }
        public void should_not_respond_to_partial_trigger()
        {
            var plugin = new CannedResponsePlugin();

            var pl = new ParsedLine("This is the exact trigger purple monkey dishwahser", "bob");

            plugin.Evaluate(pl).Should().BeNull("This wasn't the exact trigger");
        }
        public void should_never_get_response()
        {
            var plugin = new RandomChatterPlugin("zero_percent.config");

            var pl = new ParsedLine("This is a random line", "bob");

            plugin.Evaluate(pl).Should().BeNull("Percent chance of response is zero");
        }
        public void a_trap()
        {
            var plugin = new CannedResponsePlugin();

            var pl = new ParsedLine("I think it's a tRap", "bob");

            plugin.Evaluate(pl).Should().Be("https://skydrive.live.com/redir?resid=3F2CFE9060480107%21285");
        }
        public void should_respond_to_partial_trigger()
        {
            var plugin = new CannedResponsePlugin();

            var pl = new ParsedLine("This line contains the partial trigger fnord, which should be enough", "bob");

            plugin.Evaluate(pl).Should().Be("You said fnord!");
        }
Пример #14
0
        public void should_hug_with_all_args()
        {
            var plugin = new CommandPlugin();

            var pl = new ParsedLine("!hug Jim and his monkey", "Bob");

            plugin.Evaluate(pl).Should().Be("Bob hugs Jim and his monkey");
        }
Пример #15
0
        public void should_hug_with_default()
        {
            var plugin = new CommandPlugin();

            var pl = new ParsedLine("!hug", "Bob");

            plugin.Evaluate(pl).Should().Be("Bob hugs himself");
        }
Пример #16
0
        public IObservable<string> Evaluate(ParsedLine line)
        {
            if(!line.IsCommand || line.Command.ToLower() != "countdown")
            {
                return null;
            }

            var options = new CountdownTimerOptions();

            if(!Parser.Default.ParseArguments(line.Args, options))
            {
                return Return(options.GetUsage());
            }

            try
            {
                int seconds = options.DurationSeconds;
                int interval = options.IntervalSeconds;

                var unitLabels = options.ParseUnitLabels(options.IntervalString);

                // Create an interval sequence that fires off a value every [interval] seconds
                IObservable<string> seq = Interval(TimeSpan.FromSeconds(interval))

                    // Run that seq until the total time has exceeded the [seconds] value
                    .TakeWhile(l => ((l + 1) * interval) < seconds)

                    // Project each element in the sequence to a human-readable time value
                    .Select(
                        l =>
                        String.Format("{0} remaining...",
                            FormatRemaining(seconds - ((l + 1) * interval), unitLabels)));

                // If there are any other events configured, merge them into the sequence
                if(options.Events.Any())
                {
                    var events = options.Events.OrderBy(@event => @event.Target);

                    var eventTimes = Interval(TimeSpan.FromSeconds(1))
                        .TakeWhile(l => l < seconds)
                        .Where(l => events.Any(@event => @event.Target == l))
                        .Select(l => events.First(@event => @event.Target == l).Message);

                    seq = seq.Merge(eventTimes);
                }

                // Add a start and end message
                return Return(String.Format("{0} remaining...", FormatRemaining(seconds, options.ParseUnitLabels(options.DurationString))))
                    .Concat(seq)
                    .Concat(Return(String.Join(" ", options.FinishedMessage)));
            }
            catch(ArgumentException)
            {
                return Return(options.GetUsage());
            }
        }
        public string Evaluate(ParsedLine line)
        {
            if (!this.Enabled)
            {
                System.Diagnostics.Debug.WriteLine("{0} is disabled, re-enable by typing !enable {0}", new[] { this.Name });
                return(null);
            }

            return(EvaluateEx(line));
        }
        public virtual string EvaluateEx(ParsedLine line)
        {
            if (!line.IsCommand)
            {
                return(null); // this is not a command
            }
            XmppBotCommand command = GetCommand(line.Command);

            return(command == null ? null : command.Method(line));
        }
        public string Evaluate(ParsedLine line)
        {
            if (!this.Enabled)
            {
                System.Diagnostics.Debug.WriteLine("{0} is disabled, re-enable by typing !enable {0}", new[] { this.Name });
                return null;
            }

            return EvaluateEx(line);
        }
        public string Evaluate(ParsedLine line)
        {
            var r = new Random();

            if(_responses.Length > 0 && r.Next(0, 99) >= _percentChanceOfResponse)
            {
                return _responses[r.Next(0, _responses.Length - 1)];
            }

            return null;
        }
        public void should_respond_to_exact_trigger()
        {
            // Default app.config; one response in file, 100% response chance
            var plugin = new CannedResponsePlugin();

            var pl = new ParsedLine("This is the exact trigger", "bob");

            plugin.Evaluate(pl)
                  .Should()
                  .Be("This is the exact response");
        }
        public void should_always_get_the_one_response()
        {
            // Default app.config; one response in file, 100% response chance
            var plugin = new RandomChatterPlugin();

            var pl = new ParsedLine("This is a random line", "bob");

            plugin.Evaluate(pl)
                  .Should()
                  .Be("This is the only response in the file.", "Only one response in file, 100% chance");
        }
Пример #23
0
 private string ExecuteConfirm(ParsedLine line)
 {
     if (commandQueue.ContainsKey(line.User.Id))
     {
         var command = commandQueue[line.User.Id];
         return(base.EvaluateEx(command)); // just execute it now that it's confirmed
     }
     else
     {
         return(null);
     }
 }
 private string ExecuteConfirm(ParsedLine line)
 {
     if (commandQueue.ContainsKey(line.User.Id))
     {
         var command = commandQueue[line.User.Id];
         return base.EvaluateEx(command); // just execute it now that it's confirmed
     }
     else
     {
         return null;
     }
 }
Пример #25
0
        public void should_display_directory()
        {
            var plugin = new CommandPlugin();

            var pl = new ParsedLine("!dir", "Bob");

            var result = plugin.Evaluate(pl);

            Debug.WriteLine(result);

            result.Should().Contain("Directory:");
        }
Пример #26
0
        public void should_display_help()
        {
            var plugin = new CommandPlugin();

            var pl = new ParsedLine("!help", "Bob");

            plugin.Evaluate(pl).Should().Contain("the commands I know");

            plugin.Evaluate(pl).Should().Contain("!slap [thing]");

            Debug.Write(plugin.Evaluate(pl));
        }
Пример #27
0
        public void stop_talking_on_partial_trigger()
        {
            // Start the conversation
            var line = new ParsedLine("Hey Bot, what's up?", "Bob");
            _plugin.Evaluate(line).Should().NotBeNull();

            // End the conversation
            line = new ParsedLine("Quiet, Bot, we're done talking.", "Bob");
            _plugin.Evaluate(line).Should().NotBeNull();

            // No more responses
            line = new ParsedLine("Just saying some random stuff", "Bob");
            _plugin.Evaluate(line).Should().BeNull();
        }
        public override string EvaluateEx(ParsedLine line)
        {
            if (!line.IsCommand)
                return null; // this is not a command

            XmppBotCommand command = GetCommand(line.Command);

            // this is a command for this plugin, so we are going to queue it up
            if (command != null)
            {
                _commandQueue.Add(new QueuedCommand(line, command));
                return string.Format("Queued up: {0}", line.Command);
            }

            return null; // nothing to do
        }
        public virtual string Help(ParsedLine line)
        {
            if (this.Commands.Count <= 0)
            {
                return("");
            }

            if (line.Args.Length == 0)
            {
                return(String.Format("{0} commands: {1}", this.Name, String.Join(",", this.Commands.Keys.ToArray())));
            }

            XmppBotCommand command = GetCommand(line.Args.FirstOrDefault());

            return(command == null ? "" : command.HelpInfo);
        }
Пример #30
0
        public void scramble()
        {
            var plugin = new CommandPlugin();

            var pl = new ParsedLine("!scramble", "Bob");

            var result = plugin.Evaluate(pl);

            Debug.WriteLine(result);

            result.Should().Contain("B");
            result.Should().Contain("o");
            result.Should().Contain("b");

            result.Trim().Length.Should().Be(3);
        }
Пример #31
0
        public override string EvaluateEx(ParsedLine line)
        {
            if (!line.IsCommand)
            {
                return(null); // this is not a command
            }
            XmppBotCommand command = GetCommand(line.Command);

            // this is a command for this plugin, so we are going to queue it up
            if (command != null)
            {
                _commandQueue.Add(new QueuedCommand(line, command));
                return(string.Format("Queued up: {0}", line.Command));
            }

            return(null); // nothing to do
        }
Пример #32
0
        public void finish_help_formats_default()
        {
            var scheduler = new TestScheduler();

            var plugin = new CountdownTimer(scheduler);

            var pl = new ParsedLine("!countdown", "Bob");

            IObservable<string> results = plugin.Evaluate(pl);

            ITestableObserver<string> obs = scheduler.Start(() => results);

            obs.Messages.First().Value.Value.Contains("System.String[]")
                .Should().BeFalse("the formatting of the default value shouldn't be System.String[]");

            obs.Messages.First().Value.Value.Contains("(Default: Finished!)")
               .Should().BeTrue();
        }
        public override string EvaluateEx(ParsedLine line)
        {
            if (!line.IsCommand || line.Command.ToLower() != "countdown")
            {
                return null;
            }

            string help = "!countdown [seconds] [interval]";

            // Verify we have enough arguments
            if (line.Args.Length < 2)
            {
                return help;
            }

            int seconds;
            int interval;

            // Parse the arguments
            if (!int.TryParse(line.Args[0], out seconds) || !int.TryParse(line.Args[1], out interval))
            {
                return help;
            }

            // Create an interval sequence that fires off a value every [interval] seconds
            IObservable<string> seq = Observable.Interval(TimeSpan.FromSeconds(interval))

                // Run that seq until the total time has exceeded the [seconds] value
                                                .TakeWhile(l => ((l + 1) * interval) < seconds)

                // Project each element in the sequence to a human-readable time value
                                                .Select(
                                                    l =>
                                                    String.Format("{0} seconds remaining...",
                                                        seconds - ((l + 1) * interval)))

                                                .Concat(Observable.Return("Finished!"));
            seq.Subscribe((msg) =>
            {
                this.SendMessage(msg, line.From, BotMessageType.groupchat);
            });

            return null;
        }
Пример #34
0
        public string Evaluate(ParsedLine line)
        {
            if (!line.IsCommand) return string.Empty;

            switch (line.Command.ToLower())
            {
                case "smack":
                    return String.Format("{0} smacks {1} around with a large trout", line.User, line.Args.FirstOrDefault() ?? "your mom");

                case "hug":
                    return String.Format("{0} hugs {1}", line.User, line.Args.FirstOrDefault() ?? "themself");

                case "help":
                    return String.Format("Right now the only commands I know are !smack [thing] and !hug [thing].");

                default:
                    return null;
            }
        }
Пример #35
0
        public void count_down_from_three_seconds()
        {
            var scheduler = new TestScheduler();

            var plugin = new CountdownTimer(scheduler);

            var pl = new ParsedLine("!countdown -d 3 -i 1", "Bob");

            long oneSecond = TimeSpan.FromSeconds(1).Ticks;

            ITestableObserver<string> obs = scheduler.Start(() => plugin.Evaluate(pl), 11 * oneSecond);

            obs.Messages.AssertEqual(
                OnNext(201, "3 seconds remaining..."),
                OnNext(10000201, "2 seconds remaining..."),
                OnNext(20000201, "1 second remaining..."),
                OnNext(30000202, "Finished!"),
                OnCompleted<string>(30000202)
                );
        }
Пример #36
0
        public override string EvaluateEx(ParsedLine line)
        {
            // check to see if this is a confirmation
            if (commandQueue.Count > 0)
            {
                if (line.Raw.ToUpperInvariant() == "YES" ||
                    line.Raw.ToUpperInvariant() == "Y")
                {
                    string     res = ExecuteConfirm(line);
                    ParsedLine cmdLine;
                    commandQueue.TryRemove(line.User.Id, out cmdLine);

                    if (!string.IsNullOrEmpty(res))
                    {
                        return(res);
                    }
                }
                else if (
                    line.Raw.ToUpperInvariant() == "NO" ||
                    line.Raw.ToUpperInvariant() == "N")
                {
                    ClearCommandHistory(line.User.Id);
                }
            }


            // now check for a command
            if (!line.IsCommand)
            {
                return(null); // this is not a command
            }
            XmppBotCommand command = GetCommand(line.Command);

            if (command != null)
            {
                // queue this command if it is one
                AreYouSure(line);
            }

            return(null);
        }
Пример #37
0
        public string Eval(ParsedLine line)
        {
            if (ParameterType == ParameterType.Argument)
            {
                if (line.Args.Count() >= Index + 1)
                {
                    return line.Args[Index];
                }

                return Default;
            }

            if (ParameterType == ParameterType.AllArguments)
            {
                if (line.Args.Any())
                {
                    return line.Args.Aggregate(String.Empty, (s, s1) => s + (s.Length > 0 ? " " : "") + s1);
                }

                return Default;
            }

            switch (ParameterType)
            {
                case ParameterType.User:
                    return line.User;
                case ParameterType.Command:
                    return line.Command;
                case ParameterType.Raw:
                    return line.Raw;
                case ParameterType.Predefined:
                    return Value;
                case ParameterType.Argument:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            return null;
        }
Пример #38
0
        private void xmpp_OnMessage(object sender, Message msg)
        {
            if (!string.IsNullOrEmpty(msg.Body))
            {
                log.InfoFormat("Message : {0} - from {1}", msg.Body, msg.From);

                IChatUser user = null;

                if (msg.Type == MessageType.groupchat)
                {
                    //msg.From.Resource = User Room Name
                    //msg.From.Bare = Room 'email'
                    //msg.From.User = Room id

                    user = _roster.Values.FirstOrDefault(u => u.Name == msg.From.Resource);
                }
                else
                {
                    _roster.TryGetValue(msg.From.Bare, out user);
                }

                // we can't find a user or this is the bot talking
                if (null == user || _config.RoomNick == user.Name)
                {
                    return;
                }

                ParsedLine line = new ParsedLine(msg.From.Bare, msg.Body.Trim(), msg.From.User, user, (BotMessageType)msg.Type);

                switch (line.Command)
                {
                case "help":
                    var helpText = new StringBuilder();
                    var plist    = Plugins.ToList();
                    plist.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));

                    foreach (var p in plist)
                    {
                        var helpLine = p.Help(line);
                        if (!String.IsNullOrWhiteSpace(helpLine))
                        {
                            helpText.AppendLine(p.Help(line));
                        }
                    }

                    helpText.AppendLine("-----------------------");
                    helpText.AppendLine("En/Dis-able a plugin: !disable|!enable <pluginname>");
                    helpText.AppendLine("List plugin names: !list");
                    SendMessage(msg.From, helpText.ToString(), msg.Type);

                    break;

                case "close":
                    SendMessage(msg.From, "I'm a quitter...", msg.Type);
                    Environment.Exit(1);
                    return;

                case "reload":
                    SendMessage(msg.From, LoadPlugins(), msg.Type);
                    break;

                default:
                    Task.Factory.StartNew(() =>
                                          Parallel.ForEach(Plugins,
                                                           plugin => SendMessage(msg.From, plugin.Evaluate(line), msg.Type)
                                                           ));
                    break;
                }
            }
        }
 public QueuedCommand(ParsedLine line, XmppBotCommand command)
 {
     this.Line    = line;
     this.Command = command;
 }