Exemplo n.º 1
0
 public void SwansonMe(Message message, IMessageClient client)
 {
     var httpclient = GetJsonServiceClient("http://ronsays.tumblr.com");
     var html = httpclient.Get<string>("/random");
     var linkMatch = Regex.Match(html, "<div class=\"stat-media-wrapper\"><a href=\"http://ronsays.tumblr.com/image/(\\d+)\"><img\\ssrc=\"(.*)\"\\salt");
     client.ReplyTo(message, linkMatch.Groups[2].Value);
 }
Exemplo n.º 2
0
        private object[] BuildParameters(MethodInfo method, Message message, IMessageClient client, Dictionary<string, string> inputParameters)
        {
            ParameterInfo[] methodParameters = method.GetParameters();
            var result = new object[methodParameters.Count()];

            for (int parameterIndex = 0; parameterIndex < result.Length; parameterIndex++)
            {
                ParameterInfo parameter = methodParameters[parameterIndex];

                if (parameter.ParameterType.IsAssignableFrom(typeof(Message)))
                {
                    result[parameterIndex] = message;
                }
                else if (parameter.ParameterType == typeof(IMessageClient))
                {
                    result[parameterIndex] = client;
                }
                else if (parameter.ParameterType == typeof(IBrain))
                {
                    result[parameterIndex] = _brain;
                }
                else if (inputParameters.ContainsKey(parameter.Name))
                {
                    result[parameterIndex] = Convert.ChangeType(inputParameters[parameter.Name], parameter.ParameterType);
                }
            }

            return result;
        }
Exemplo n.º 3
0
 public void Recieve(Message message, IMessageClient client)
 {
     IRestClient httpClient = GetJsonServiceClient("http://facepalm.org");
     var response = httpClient.Get<HttpWebResponse>("/img.php");
     var imageUrl = response.ResponseUri.AbsoluteUri;
     client.ReplyTo(message, imageUrl);
 }
Exemplo n.º 4
0
        public void PityTheFool(Message message, IMessageClient client, string phrase)
        {
            var pity = GetRandomItem(new List<string>
                {
                    "I Pity The Fool",
                    "Pity The Fool",
                    "Thou Shalt pity the fool",
                    "Pity thee",
                    "Be pitiful for those",
                    "cast pity towards those"
                });

            if (string.IsNullOrEmpty(phrase))
            {
                phrase = GetRandomItem(new List<string>
                    {
                        "who breaks the build",
                        "who doesn't test before check-in",
                        "who is last to the dessert tray",
                        "who doesn't login to campfire",
                        "who isn't nBot"
                    });
            }

            MemeGen(message, client, "1646", "5353", pity, phrase);
        }
Exemplo n.º 5
0
        public void SearchStackOverflow(Message message, IMessageClient client, string query)
        {
            try
            {
                var authCode = Robot.GetSetting<string>("StackappsApiKey");

                if (string.IsNullOrEmpty(authCode))
                    throw new ArgumentException("Please supply the StackappsApiKey");

                var result = GetGZipedJsonServiceClient(string.Format("http://api.stackoverflow.com/1.1/search?intitle={0}&key={1}",
                                                                Uri.EscapeDataString(query),
                                                                Uri.EscapeDataString(authCode)))
                                                                .Get<SearchResult>("/");

                if (result.Questions.Any())
                {
                    client.ReplyTo(message, string.Format("Top 5 Search results for: {0}", query));

                    foreach (Question question in result.Questions.OrderByDescending(q => q.answer_count).Take(5))
                    {
                        client.ReplyTo(message, string.Format("{0} responses to: {1} {2}", question.answer_count, question.title, "http://stackoverflow.com" + question.question_answers_url));
                    }
                }
                else
                {
                    client.ReplyTo(message, string.Format("No results found for {0}", query));
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("NBot-Sosearch", ex.ToString());
                client.ReplyTo(message, "Error in searching Stack Overflow.");
            }
        }
Exemplo n.º 6
0
        public void XkcdMe(Message message, IMessageClient client, string number)
        {
            IRestClient jsonClient = GetJsonServiceClient("http://xkcd.com");
            var result = new RootObject();

            string jsonResponse;

            try
            {
                jsonResponse = (string.IsNullOrEmpty(number) || number == "xkcd me")
                    ? jsonClient.Get<string>("/info.0.json")
                    : jsonClient.Get<string>(string.Format("/{0}/info.0.json", number));
            }
            catch (Exception)
            {
                jsonResponse = jsonClient.Get<string>("/1/info.0.json");
            }

            result.Value = JsonObject.Parse(jsonResponse);
            string imgUrl = result.Value.Child("img").Replace("\\", "");
            string altText = result.Value.Child("alt");

            //Reply with two messages back to back
            client.ReplyTo(message, imgUrl);
            client.ReplyTo(message, altText);
        }
Exemplo n.º 7
0
        public void RollDice(Message message, IMessageClient client, string sides)
        {
            var dice = new Random(DateTime.Now.Millisecond);

            //default to typical 6 side die
            int numSides = 6;

            if (string.IsNullOrEmpty(sides) || int.TryParse(sides, out numSides))
            {
                if (numSides <= 0)
                {
                    //negative number
                    var result = "I'm sorry, i will not roll a " + numSides.ToString() +
                                 " sided dice without adult supervision. That would tear a hole in the universe...";

                    client.ReplyTo(message, result);

                    Thread.Sleep(5000);

                    client.ReplyTo(message, "No... you don't qualify as an adult");
                }
                else
                {
                    //good number
                    var result = "You rolled a " + dice.Next(1, numSides + 1) + " on a " + numSides.ToString() + " sided dice";
                    client.ReplyTo(message, result);
                }
            }
            else
            {
                //non number, or too large a number
                var result = "I can't roll a " + sides + " I am but a meager .net bot";
                client.ReplyTo(message, result);
            }
        }
Exemplo n.º 8
0
        public void Hear(Message message, IMessageClient client, IBrain brain)
        {
            string time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            string result = time + " in the room " + message.RoomId;
            var userName = client.GetUser(message.UserId).Name;

            brain.SetValue(LastSpokeKey(userName), result);
        }
Exemplo n.º 9
0
 public void DoExcuseMe(Message mesage, IMessageClient client)
 {
     IEntity user = client.GetUser(mesage.UserId);
     IRestClient httpClient = GetJsonServiceClient("http://developerexcuses.com/");
     var result = httpClient.Get<string>("/");
     Match matches = Regex.Match(result, "<a href=\"/\" .*>(.*)</a>");
     string excuse = matches.Groups[1].Value;
     client.ReplyTo(mesage, string.Format("{0}, your excuse is \"{1}\".", user.Name, excuse));
 }
Exemplo n.º 10
0
        private void InnerMessageProducerOnMessageProduced(Message message)
        {
            if (MessageProduced != null)
            {
                if (_filters.Any(filter => filter.FilterMessage(message)))
                {
                    return;
                }

                MessageProduced(message);
            }
        }
Exemplo n.º 11
0
        public void FindMemeGenerator(Message message, IMessageClient client, string url)
        {
            IRestClient httpClient =
                GetJsonServiceClient(
                    string.Format(
                        "http://version1.api.memegenerator.net/Generator_Select_ByUrlNameOrGeneratorID?generatorID=&urlName={0}",
                        url));

            var response = httpClient.Get<string>("");

            client.ReplyTo(message, response);
        }
Exemplo n.º 12
0
        public void PingMe(Message message, IMessageClient client, string location)
        {
            var startInfo = new ProcessStartInfo();
            startInfo.FileName = "ping.exe";
            startInfo.Arguments = location;
            startInfo.RedirectStandardOutput = true;
            startInfo.UseShellExecute = false;
            var process = Process.Start(startInfo);
            process.WaitForExit(5000);
            var result = process.StandardOutput.ReadToEnd();

            client.ReplyTo(message, result);
        }
Exemplo n.º 13
0
        public void PageUser(Message message, IMessageClient client, string name)
        {
            string regex = string.Format("(.*)({0})(.*)", name);
            List<IEntity> rooms = client.GetAllRooms().ToList();

            string sentFrom = client.GetUser(message.UserId).Name;
            IEntity requestedRoom = rooms.Single(r => r.Id == message.RoomId);
            const string pageMessage = "Paging {0} ... Paging {0} ... Your presence is requested by {1} in the \"{2}\" room.";
            const string failureMessage = "Sorry, nobody by the name {0} could be found.";
            const string userIsInYourRoom = "Lulz!! {0} is in your room.";
            var roomsUserIsIn = new List<IEntity>();

            bool hasMatch = false;
            foreach (IEntity room in rooms)
            {
                IEnumerable<IEntity> usersInRoom = client.GetUsersInRoom(room.Id);
                foreach (IEntity user in usersInRoom)
                {
                    if (Regex.IsMatch(user.Name, regex, RegexOptions.IgnoreCase))
                    {
                        roomsUserIsIn.Add(room);
                        string response = string.Format(pageMessage, user.Name, sentFrom, requestedRoom.Name);

                        if (room.Id == requestedRoom.Id)
                            response = string.Format(userIsInYourRoom, user.Name);

                        client.Send(response, room.Id);
                        hasMatch = true;
                    }
                }
            }

            if (!hasMatch)
            {
                string response = string.Format(failureMessage, name);
                client.Send(response, requestedRoom.Id);
            }
            else
            {
                var responseMessage = new StringBuilder();
                responseMessage.AppendLine(string.Format("{0}, \"{1}\" was found in the following rooms:", sentFrom, name));

                foreach (IEntity room in roomsUserIsIn)
                {
                    responseMessage.AppendLine(string.Format("- {0}", room.Name));
                }

                client.Send(responseMessage.ToString(), requestedRoom.Id);
            }
        }
Exemplo n.º 14
0
 public void DoIsItDownForYou(Message message, IMessageClient client, string site)
 {
     try
     {
         IRestClient jsonClient = GetJsonServiceClient(DownForMeSite);
         var result = jsonClient.Get<string>(site);
         Match match = Regex.Match(result, SiteIsUpReges);
         client.ReplyTo(message, match.Success ? string.Format("It's just you. {0} is up for me.", site) : string.Format("Oh no {0} is down for me too!!!!! *PANIC*", site));
     }
     catch (Exception e)
     {
         client.Send("Oh no I am Down!!! *UberPanic*", message.RoomId);
     }
 }
Exemplo n.º 15
0
        private void MemeGen(Message message, IMessageClient client, string generatorId, string imageId, string text0, string text1)
        {
            IRestClient httpClient =
                GetJsonServiceClient(
                    string.Format(
                        "http://version1.api.memegenerator.net/Instance_Create?username=test&password=test&languageCode=en&generatorID={0}&imageID={3}&text0={1}&text1={2}",
                        generatorId,
                        text0,
                        text1,
                        imageId));

            var response = httpClient.Get<MemeGeneratorResponse>("");

            client.ReplyTo(message, response.Result.InstanceImageUrl);
        }
Exemplo n.º 16
0
        private void Translate(Message message, IMessageClient client, string textToTranslate)
        {
            try
            {
                var result = GetJsonServiceClient(string.Format("http://isithackday.com/arrpi.php?text={0}&format=json", UrlEncode(textToTranslate)))
                    .Get<string>("pirate");

                client.ReplyTo(message, result);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("NBot-PirateTranslator", ex.ToString());
                client.ReplyTo(message, "PirateTranslator crashed!");
            }
        }
Exemplo n.º 17
0
        private void MemeGen(Message message, IMessageClient client, string urlString, string text1, string text2)
        {
            try
            {
                var result = GetJsonServiceClient(string.Format("http://memecaptain.com/g?u={0}&t1={1}&t2={2}", UrlEncode(urlString), UrlEncode(text1), UrlEncode(text2)))
                    .Get<string>("");

                string startOfUrl = result.Substring(result.IndexOf("http"));
                string imgUrl = startOfUrl.Substring(0, startOfUrl.IndexOf("\""));
                client.ReplyTo(message, imgUrl);
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("NBot-MemeCaptain", ex.ToString());
                client.ReplyTo(message, "MemGenerator crashed!");
            }
        }
Exemplo n.º 18
0
        public void ChuckNorrisJoke(Message message, IMessageClient client, string name)
        {
            IRestClient jsonClient = GetJsonServiceClient("http://api.icndb.com/jokes/");

            RootObject result;

            if (!string.IsNullOrEmpty(name))
            {
                result = jsonClient.Get<string>("random?firstName=" + name + "&lastName=").FromJson<RootObject>();
            }
            else
            {
                result = jsonClient.Get<string>("random").FromJson<RootObject>();
            }

            client.ReplyTo(message, result.Value.Joke);
        }
Exemplo n.º 19
0
        public void HandlePowerShellCommand(Message message, IMessageClient client, string command, string parameters)
        {
            if (_commands.ContainsKey(command))
            {
                var filePath = _commands[command];
                var scriptParameters = string.IsNullOrEmpty(parameters) ? string.Empty : parameters;

                var startInfo = new ProcessStartInfo();
                startInfo.FileName = "powershell.exe";
                startInfo.Arguments = string.Format("-File {0} {1}", filePath, scriptParameters);
                startInfo.RedirectStandardOutput = true;
                startInfo.UseShellExecute = false;
                var process = Process.Start(startInfo);
                process.WaitForExit(5000);
                var result = process.StandardOutput.ReadToEnd();
                client.ReplyTo(message, result);
            }
        }
Exemplo n.º 20
0
 public void HandleStatusChange(Message message, IMessageClient client, IBrain brain, string query)
 {
     string time = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
     //string result = "wut";
     var userName = client.GetUser(message.UserId).Name;
     if (query.ToLower().StartsWith("in"))
     {
         //result = "i recognize " + message.UserId + " checked in at " + time;
         brain.SetValue(LastCheckinKey(userName), time);
         brain.RemoveKey(LastCheckoutKey(userName));
     }
     else if (query.ToLower().StartsWith("out"))
     {
         //result = "i recognize " + message.UserId + " checked out at " + time;
         brain.SetValue(LastCheckoutKey(userName), time);
         brain.RemoveKey(LastCheckinKey(userName));
     }
     //client.ReplyTo(message, result);
 }
Exemplo n.º 21
0
        public void HandleGetStatus(Message message, IMessageClient client, IBrain brain, string userName)
        {
            string result = userName;
            bool needsAnd = false;
            bool neverSeenThem = true;

            if (brain.ContainsKey(LastCheckinKey(userName)))
            {
                result += " last checked in at " + brain.GetValue(LastCheckinKey(userName));
                neverSeenThem = false;
                needsAnd = true;
            }

            if (brain.ContainsKey(LastCheckoutKey(userName)))
            {
                if (needsAnd)
                {
                    result += ",";
                }
                result += " last checked out at " + brain.GetValue(LastCheckoutKey(userName));
                neverSeenThem = false;
                needsAnd = true;
            }

            if (brain.ContainsKey(LastSpokeKey(userName)))
            {
                if (needsAnd)
                {
                    result += " and";
                }
                result += " last spoke at " + brain.GetValue(LastSpokeKey(userName));
                neverSeenThem = false;
            }

            if (neverSeenThem)
            {
                result = "I ain't never seen " + userName + " come round these parts";
            }

            client.ReplyTo(message, result);
        }
Exemplo n.º 22
0
        public void StarProduction()
        {
            Console.Clear();
            Action<string> messageRcieved = line =>
            {
                var message = new Message
                {
                    Channel = Channel,
                    Type = "TestMessage",
                    RoomId = "ConsoleRoom",
                    UserId = "ConsoleUser",
                    Content = line
                };

                FireMessageProduced(message);
            };

            _listner = new ConsoleListner(messageRcieved);

            _listner.StartListening();
        }
Exemplo n.º 23
0
        public void CreateJoinMe(Message message, IMessageClient client)
        {
            var authCode = Robot.GetSetting<string>("JoinMeAuthCode");

            if (string.IsNullOrEmpty(authCode))
            {
                throw new ArgumentException("Please set the JoinMeAuthCode.");
            }

            var result = GetJsonServiceClient(string.Format("https://secure.join.me/API/requestCode?authCode={0}", authCode))
                .Get<String>("/");

            string[] stuff = result.Split(new[] { ':', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);

            string code = stuff[2].Trim();
            string ticket = stuff[4].Trim();
            string presenter = string.Format("Presenter: https://secure.join.me/download.aspx?code={0}&ticket={1}", code, ticket);
            string viewer = string.Format("Viewer: http://join.me/{0}", code);

            client.ReplyTo(message, presenter);
            client.ReplyTo(message, viewer);
        }
Exemplo n.º 24
0
 public void InsanityWolf(Message message, IMessageClient client, string phrase1, string phrase2)
 {
     MemeGen(message, client, "45", "20", phrase1, phrase2);
 }
Exemplo n.º 25
0
 public void CourageWolf(Message message, IMessageClient client, string phrase1, string phrase2)
 {
     MemeGen(message, client, "303", "24", phrase1, phrase2);
 }
Exemplo n.º 26
0
 public void SayHello(Message message, IMessageClient client)
 {
     var user = client.GetUser(message.UserId);
     client.ReplyTo(message, string.Format(GetRandomItem(_hellos), user.Name));
 }
Exemplo n.º 27
0
 public void SayGoodMorning(Message message, IMessageClient client)
 {
     var user = client.GetUser(message.UserId);
     client.ReplyTo(message, string.Format(GetRandomItem(_mornings), user.Name));
 }
Exemplo n.º 28
0
 private void Manatee(Message message, IMessageClient client)
 {
     client.ReplyTo(message, string.Format("http://calmingmanatee.com/img/manatee{0}.jpg", GetRandomNumber(1, 30)));
 }
Exemplo n.º 29
0
 public void DoAchievement(Message message, IMessageClient client, string caption)
 {
     string encodedCaption = UrlEncode(caption);
     string url = string.Format("http://achievement-unlocked.heroku.com/xbox/{0}.png", encodedCaption);
     client.ReplyTo(message, url);
 }
Exemplo n.º 30
0
        private void OnMessageProduced(Message message)
        {
            try
            {
                IAdapter adapter = _adapters[message.Channel];
                var pipeline = message.Content.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                IMessageClient client = null;
                string[] previousSegmentOutput = new string[] { };

                for (int segmentIndex = 0; segmentIndex < pipeline.Length; segmentIndex++)
                {
                    var segment = message.CloneWithNewContent(pipeline[segmentIndex]);
                    var pipedMessageClient = client as PipedMessageClient;

                    // Replace the input to the next command with the output of the previous
                    if (pipedMessageClient != null)
                    {
                        var content = pipedMessageClient.ReplaceInput(segment.Content.Trim());
                        previousSegmentOutput = pipedMessageClient.Output;
                        segment = segment.CloneWithNewContent(content);
                    }

                    client = segmentIndex == pipeline.Length - 1 ? adapter.Client : new PipedMessageClient(adapter.Client);

                    foreach (var route in _routes.Where(r => r.IsMatch(segment)))
                    {
                        var inputParameters = new Dictionary<string, string>();

                        IRoute routeToProcess = route;

                        var roomSecurityRoute = route as IRoomSecurityRoute;

                        if (roomSecurityRoute != null)
                        {
                            routeToProcess = roomSecurityRoute.InnerRoute;
                        }

                        if (routeToProcess is IMessageParameterProvider)
                        {
                            inputParameters = ((IMessageParameterProvider)routeToProcess).GetInputParameters(segment);
                        }
                        else if (routeToProcess is IPipedParameterProvider)
                        {
                            inputParameters = ((IPipedParameterProvider)routeToProcess).GetInputParameters(previousSegmentOutput);
                        }

                        var routeParameters = BuildParameters(route.EndPoint, segment, client, inputParameters);
                        routeToProcess.EndPoint.Invoke(routeToProcess.Handler, routeParameters);
                    }

                }
            }
            catch (Exception e)
            {
                Robot.Log.WriteError(string.Format("An error has occurred while processing message \"{0}\"", message.Content), e);
            }
        }