Esempio n. 1
0
        public string RunAction(string[] args)
        {
            var sb = new StringBuilder();

            sb.AppendLine("KajaBot információk:");

            // Obtain assembly version
            var             assembly = Assembly.GetExecutingAssembly();
            FileVersionInfo fvi      = FileVersionInfo.GetVersionInfo(assembly.Location);

            sb.Append("Verzió: ");
            sb.AppendLine(fvi.FileVersion);

            // Add statistics
            var stats = StatisticsCollector.GetInstance();

            sb.AppendLine();
            sb.AppendLine("Statisztika:");

            sb.AppendFormat("Bejövő üzenetek: {0:D}\n", stats.IncomingMessageCount);
            sb.AppendFormat("Futtatott parancsok: {0:D}\n", stats.ExecutedCommandCount);
            sb.AppendFormat("Étlap lekérdezések: {0:D}\n", stats.ExecutedRestaurantMenuRequestCount);
            sb.AppendFormat("OCR által feldolgozott képek: {0:D}\n", stats.OcredPageCount);
            sb.AppendFormat("Kimenő web-hívások: {0:D}\n", stats.OutgoingWebRequestCount);
            sb.AppendFormat("Ismeretlen parancsok: {0:D}\n", stats.UnknownCommandCount);

            return(sb.ToString());
        }
Esempio n. 2
0
        private void OnSlackMessageReceived(NewMessage obj)
        {
            if (!IsMessageForMe(obj))
            {
                return;
            }

            StatisticsCollector.GetInstance().IncrementIncomingMessageCount();

            // Find sender user name
            string senderName = "<unknown>";

            foreach (User user in _loginResponse.users)
            {
                if (user.id == obj.user)
                {
                    senderName = user.name;
                    break;
                }
            }

            _log.Info("Incoming message from " + senderName + " for me: " + obj.text);

            ParseBotMessage(obj);
        }
Esempio n. 3
0
        public string RunAction(string[] args)
        {
            const string errorMessage   = "Mára ennyi. Hiba. Menjetek dolgozni!";
            const string warningMessage = "Nem kéne inkább dolgozni? ;)";

            // Only show warning on workdays from 10 to 18
            if (DateTime.Today.DayOfWeek >= DayOfWeek.Monday && DateTime.Today.DayOfWeek <= DayOfWeek.Friday &&
                DateTime.Now.Hour >= 10 && DateTime.Now.Hour < 18)
            {
                ++_requestCount;
                if (_requestCount % 10 == 0)
                {
                    return(warningMessage);
                }
            }

            string html;

            try
            {
                var webCient = new WebClient();
                html = webCient.DownloadString("http://thecodinglove.com/random");
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();

                webCient.Dispose();
            }
            catch (Exception e)
            {
                _log.Error("Failed to get random GIF. Error: " + e);
                return(errorMessage);
            }

            //var titleRegex = new Regex(@"\<div.class=.centre.\>.*\<h3\>.*\<a.href.*\>(.*)\<\/a\>.*\<\/h3\>.*\<\/div\>");
            var   titleRegex = new Regex(@"\<div.class=.centre.\>.*\<h3\>(.*)\<\/h3\>.*\<\/div\>");
            Match titleMatch = titleRegex.Match(html);

            if (!titleMatch.Success)
            {
                _log.Error("Failed to find title.");
                return(errorMessage);
            }

            var   pictureLinkRegex = new Regex("\\<div class=\"bodytype\"\\>.{0,50}?\\<img.{0,30}?src=\"(.{0,50}?)\"");
            Match pictureLinkMatch = pictureLinkRegex.Match(html);

            if (!pictureLinkMatch.Success)
            {
                _log.Error("Failed to find picture.");
                return(errorMessage);
            }

            var pictureLink = pictureLinkMatch.Groups[1].ToString().Replace(".jpg", ".gif");

            var sb = new StringBuilder();

            sb.AppendLine(titleMatch.Groups[1].ToString());
            sb.AppendLine(pictureLink);

            return(sb.ToString());
        }
Esempio n. 4
0
        public string GetCurrentMenu()
        {
            const string feedUrl = "https://www.facebook.com/feeds/page.php?format=atom10&id=268952226502652";

            // Download RSS feed
            MemoryStream xmlData;

            try
            {
                var webClient = new WebClient();
                webClient.Headers.Set(HttpRequestHeader.UserAgent,
                                      "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0");
                byte[] buf = webClient.DownloadData(new Uri(feedUrl));
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
                xmlData = new MemoryStream(buf);
            }
            catch (Exception)
            {
                return("Hiba: nem lehet letölteni az aktuális étlapot.");
            }

            // Load the RSS feed from the XML
            SyndicationFeed feed = SyndicationFeed.Load(XmlReader.Create(xmlData));

            // Try to find the last menu in the feed
            if (feed != null)
            {
                foreach (SyndicationItem syndicationItem in feed.Items)
                {
                    var    textContent   = (TextSyndicationContent)syndicationItem.Content;
                    string textLowerCase = textContent.Text.ToLower();

                    // Find the last item which contains some specific words and not older than 2 days
                    if ((textLowerCase.Contains("menü") ||
                         textLowerCase.Contains("főétel") ||
                         textLowerCase.Contains("leves")) &&
                        syndicationItem.PublishDate >= DateTime.Today.Subtract(new TimeSpan(2, 0, 0, 0)))
                    {
                        CultureInfo defaultCulture = Thread.CurrentThread.CurrentCulture;
                        Thread.CurrentThread.CurrentCulture = new CultureInfo("hu-HU");

                        string text = textContent.Text.Replace("<br />", "\n");
                        text = "A (feltételezett) aktuális menü a Kekszben (" +
                               syndicationItem.PublishDate.ToLocalTime().ToString("yyyy. MM. dd. dddd") +
                               "):\n" + text;

                        Thread.CurrentThread.CurrentCulture = defaultCulture;

                        return(text);
                    }
                }
            }

            return("Hiba: nem található az aktuális étlap.");
        }
Esempio n. 5
0
        /// <summary>
        ///     Processes the message sent to the bot and runs the command if it's valid.
        /// </summary>
        /// <param name="msg"></param>
        private void ParseBotMessage(NewMessage msg)
        {
            string text    = msg.text.ToLower().Trim();
            var    words   = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string command = "";

            if (words.Any())
            {
                command = words[0];
                string userId = "<@" + _loginResponse.self.id.ToLower() + ">";
                command = command.Replace(userId + ":", "");
                command = command.Replace(userId, "");

                if (command.Length == 0)
                {
                    words = words.Skip(1).ToArray();
                }

                if (words.Any())
                {
                    command = words[0];
                }
            }

            command = command.Trim();

            string[] args = null;
            if (words.Count() > 1)
            {
                args = words.Skip(1).ToArray();
            }

            string targetUser = "******" + msg.user + ">";
            string answer     = targetUser + ": ";

            if (_restaurantManager.ContainsRestaurant(command))
            {
                answer += _restaurantManager.GetMenu(command);
            }
            else if (IsCommandKnown(command))
            {
                answer += RunCommand(command, args);
            }
            else
            {
                StatisticsCollector.GetInstance().IncrementUnknownCommandCount();
                answer = GetRandomUnknownCommandAnswer(targetUser);
            }

            if (answer.Length > 0)
            {
                _slackClient.SendMessage(received => { }, msg.channel, answer);
            }
        }
Esempio n. 6
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            StatisticsCollector.GetInstance();
            LoggingModel.GetInstance();

            var mainWindow = new MainWindow();

            mainWindow.Show();

            _bot = new Bot("<your-slack-api-token-comes-here>");
            _bot.Start();
        }
Esempio n. 7
0
        /// <summary>
        ///     Returns the current menu of the given restaurant.
        /// </summary>
        /// <param name="restaurantCommand"></param>
        /// <returns></returns>
        public string GetMenu(string restaurantCommand)
        {
            IRestaurant restaurant = _restaurants.Find(x => x.GetCommand().Equals(restaurantCommand));

            if (restaurant == null)
            {
                throw new Exception("Unknown restaurant: " + restaurantCommand.Substring(0, 100));
            }

            StatisticsCollector.GetInstance().IncrementExecutedRestaurantMenuRequestCount();

            _log.Info("Getting menu of restaurant: " + restaurant.GetName());

            return(restaurant.GetCurrentMenu());
        }
Esempio n. 8
0
        public string GetCurrentMenu()
        {
            string content = "";

            // Download the menu page
            try
            {
                var webClient = new WebClient();
                content = webClient.DownloadString(new Uri("http://noiretlor.hu/napi-menu"));
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
            }
            catch (Exception e)
            {
                _log.Error("Failed to download menu of Noir. Error: " + e);
                return("Hiba: nem lehet letölteni az aktuális étlapot.");
            }

            // Try to find the URI of the menu image
            var   regex = new Regex(@".*(\/upload\/image\/.*\.jpg)");
            Match match = regex.Match(content);

            if (!match.Success)
            {
                return("Hiba: nem található a napi menü URL-je.");
            }

            var imageUri = new Uri("http://noiretlor.hu" + match.Groups[1]);

            // Calculate OCR region
            var region = new Rect {
                X = 0, Y = 0.216, Width = 1, Height = 0.46
            };

            string text = "";

            // Download and process the image
            try
            {
                var ocr = new Ocr(AppDomain.CurrentDomain.BaseDirectory + "TesseractData");
                text = ocr.DownloadAndProcessImage(imageUri, region);
            }
            catch (Exception e)
            {
                _log.Error("Failed to process menu image. Error: " + e);
            }

            return("Heti menü a Noirban:\n" + text);
        }
Esempio n. 9
0
        /// <summary>
        ///     Runs the given command.
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public string RunCommand(string command, string[] args)
        {
            IBotCommand cmd =
                _commands.Find(x => x.GetCommand().Equals(command, StringComparison.OrdinalIgnoreCase));

            if (cmd == null)
            {
                return("Hiba: nincs ilyen parancs.");
            }

            _log.Info("Running command: " + command);

            StatisticsCollector.GetInstance().IncrementExecutedCommandCount();

            return(cmd.RunAction(args));
        }
Esempio n. 10
0
        public string DownloadAndProcessImage(Uri uri, Rect regionPercentage)
        {
            var engine = new TesseractEngine(_tessdataPath, "hun");

            byte[] imageData;
            try
            {
                var client = new WebClient();
                imageData = client.DownloadData(uri);
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();

                _log.Debug("Image downloaded from `" + uri + "`. Size: " + imageData.Length + " Byte(s).");
            }
            catch (Exception e)
            {
                _log.Error("Failed to download image from `" + uri + "`. Error: e");
                return("");
            }

            var bitmap = new Bitmap(new MemoryStream(imageData));

            _log.Debug("Image size: " + bitmap.Size);

            // Calculate image region
            var region = new Tesseract.Rect(
                (int)(regionPercentage.Left * bitmap.Width),
                (int)(regionPercentage.Top * bitmap.Height),
                (int)(regionPercentage.Width * bitmap.Width),
                (int)(regionPercentage.Height * bitmap.Height));

            _log.Debug("OCR region: " + region);

            Page   page = engine.Process(bitmap, region, PageSegMode.Auto);
            string text = page.GetText();

            _log.Debug("Processed text length: " + text.Length);

            StatisticsCollector.GetInstance().IncrementOcredPageCount();

            return(text);
        }
Esempio n. 11
0
        public string RunAction(string[] args)
        {
            string xhtmlData;

            try
            {
                var webClient = new WebClient();
                xhtmlData = webClient.DownloadString("https://c.xkcd.com/random/comic/");
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
            }
            catch (Exception e)
            {
                _log.Error("Failed to download the web page. Error: " + e);
                return("Hiba: nem lehet letölteni az XKCD honlapját.");
            }

            // We must strip down the html code to avoid read errors
            int pos = xhtmlData.IndexOf("<div id=\"comic\">", StringComparison.OrdinalIgnoreCase);

            if (pos > -1)
            {
                xhtmlData = xhtmlData.Remove(0, pos);
                pos       = xhtmlData.IndexOf("<img", StringComparison.OrdinalIgnoreCase);
                if (pos > -1)
                {
                    xhtmlData = xhtmlData.Remove(0, pos);
                }
            }

            pos = xhtmlData.IndexOf("</div>", StringComparison.CurrentCultureIgnoreCase);
            if (pos > -1)
            {
                xhtmlData = xhtmlData.Remove(pos);
            }

            var       reader = new StringReader(xhtmlData /*match.Groups[1].ToString()*/);
            XmlReader xml    = XmlReader.Create(reader);

            try
            {
                while (xml.Read())
                {
                    if (xml.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    if (xml.Name != "img" || !xml.HasAttributes)
                    {
                        continue;
                    }

                    string src = xml.GetAttribute("src");

                    if (src == null)
                    {
                        _log.Error("Failed to find comic's src.");
                        return("Hiba: nem található a képregény forrása.");
                    }

                    string title = xml.GetAttribute("title");
                    string alt   = xml.GetAttribute("alt");

                    var sb = new StringBuilder();
                    if (alt != null)
                    {
                        sb.AppendFormat("*{0:G}*\n", alt);
                    }
                    if (title != null)
                    {
                        sb.AppendLine(title);
                    }
                    sb.AppendFormat("http:{0:G}", src);

                    return(sb.ToString());
                }
            }
            catch (XmlException e)
            {
                if (!e.Message.ToLower(CultureInfo.InvariantCulture).Contains("unexpected end tag"))
                {
                    _log.Error("Failed to parse XHTML. Error: " + e);
                    return("Hiba a feldolgozás során. Ellenőrizd a naplót.");
                }
            }

            _log.Error("Error.");
            return("Ez most nem fog menni.");
        }
Esempio n. 12
0
        public string RunAction(string[] args)
        {
            string feedUrl = "http://9gag-rss.com/api/rss/get?code=9GAGHot&format=1";

            if (args != null && args.Any())
            {
                if (args[0].ToLower() == "nsfw")
                {
                    feedUrl = "http://9gag-rss.com/api/rss/get?code=9GAGNSFW&format=1";
                }
                else if (args[0].ToLower() == "gif")
                {
                    feedUrl = "http://9gag-rss.com/api/rss/get?code=9GAGGIF&format=1";
                }
            }

            MemoryStream feedDataStream;

            try
            {
                var    webClient = new WebClient();
                byte[] buf       = webClient.DownloadData(feedUrl);
                webClient.Dispose();

                feedDataStream = new MemoryStream(buf);
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
            }
            catch (Exception e)
            {
                _log.Error("Failed to download 9Gag RSS. Error: " + e);
                return("It's dead, Jim. :( Check the log for details.");
            }


            XmlReader xml = XmlReader.Create(feedDataStream);

            SyndicationFeed feed;

            try
            {
                feed = SyndicationFeed.Load(xml);
            }
            catch (Exception e)
            {
                return("No gags for today. Failed to load syndication feed.");
            }

            feedDataStream.Dispose();

            if (feed == null || !feed.Items.Any())
            {
                return("No gags for today. (RSS parse error)");
            }

            IEnumerator <SyndicationItem> enumerator = feed.Items.GetEnumerator();

            int rnd = new Random().Next(feed.Items.Count()) + 1;

            while (rnd-- > 0)
            {
                enumerator.MoveNext();
            }

            SyndicationItem item    = enumerator.Current;
            var             content = (TextSyndicationContent)item.Content;

            return(item.Id);
        }
Esempio n. 13
0
        public string GetCurrentMenu()
        {
            // Download the home page and try to find the menu link
            string homePageContent = "";

            try
            {
                var webClient = new WebClient();
                homePageContent = webClient.DownloadString("http://cafevian.com/hu/");
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
            }
            catch (Exception e)
            {
                _log.Error("Failed to download home page of Vian. Error: " + e);
                return("Hiba: nem lehet letölteni az aktuális étlapot.");
            }

            var   regex = new Regex(@"(http:\/\/cafevian\.com\/wp\-content\/uploads\/.*\.pdf).*GOZSDU");
            Match match = regex.Match(homePageContent);

            if (!match.Success)
            {
                _log.Error("Failed to find Vian's menu PDF URL");
                return("Hiba: nem lehet letölteni az aktuális étlapot.");
            }

            // Download the menu page
            MemoryStream pdfContent = null;

            try
            {
                var    webClient = new WebClient();
                byte[] data      = webClient.DownloadData(new Uri(match.Groups[1].ToString()));
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
                pdfContent = new MemoryStream(data);
            }
            catch (Exception e)
            {
                _log.Error("Failed to download menu of Vian. Error: " + e);
                return("Hiba: nem lehet letölteni az aktuális étlapot.");
            }

            // Convert PDF to plain text
            var    pdf  = new PdfReader(pdfContent);
            string text = PdfTextExtractor.GetTextFromPage(pdf, 1);

            var dayOfWeek = (int)DateTime.Today.DayOfWeek;

            string[] dayNames = DateTimeFormatInfo.GetInstance(new CultureInfo("hu-HU")).DayNames;

            // Find the menu for today
            text = text.Replace("\r", " ");
            string[] lines = text.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("Napi menü a Vianban:");

            bool menuFoundForToday = false;

            for (int i = 0; i < lines.Count(); ++i)
            {
                string line = lines[i];
                line = line.Replace("\n", "");

                if (!line.ToLower().Contains(dayNames[dayOfWeek] + " "))
                {
                    continue;
                }

                menuFoundForToday = true;

                line = line.Trim();

                string nextDayName = dayNames[(dayOfWeek + 1) % 7];

                for (; i < lines.Count(); ++i)
                {
                    line = lines[i];
                    line = line.Replace("\n", "");
                    line = line.Trim();

                    if (line.ToLower().Contains(nextDayName))
                    {
                        break;
                    }
                    stringBuilder.AppendLine(line);
                }
            }

            if (!menuFoundForToday)
            {
                return("Erre a napra nincs ebéd menü a Vianban.");
            }

            return(stringBuilder.ToString());
        }
Esempio n. 14
0
        public string GetCurrentMenu()
        {
            string xhtmlData;

            try
            {
                var webClient = new WebClient();
                xhtmlData = webClient.DownloadString("http://pest.vakvarju.com/hu/napimenu");
                StatisticsCollector.GetInstance().IncrementOutgoingWebRequestCount();
            }
            catch (Exception e)
            {
                _log.Error("Failed to download the web page. Error: " + e);
                return("Hiba: nem lehet letölteni a VakVarjú honlapját.");
            }

            // We must strip down the html code to avoid read errors
            int pos = xhtmlData.IndexOf("<div id=\"etlapfelsorol\">", StringComparison.InvariantCultureIgnoreCase);

            if (pos > -1)
            {
                xhtmlData = xhtmlData.Remove(0, pos);
            }

            pos = xhtmlData.IndexOf("<div class=\"footerbox\">", StringComparison.CurrentCultureIgnoreCase);
            if (pos > -1)
            {
                xhtmlData = xhtmlData.Remove(pos);
            }

            // Poor man's sanitizer...
            xhtmlData = ToUtf8(xhtmlData);
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&iacute;", "í");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&aacute;", "á");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&eacute;", "é");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&uacute;", "ú");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&oacute;", "ó");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&ouml;", "ö");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&uuml;", "ü");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&bdquo;", "\"");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&rdquo;", "\"");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&nbsp;", " ");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "&ndash;", "-");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "<br />", "\n");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "<br/>", "\n");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "<h2>", "");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "</h2>", "");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "<p>", "");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "</p>", "");
            xhtmlData = ReplaceCaseInsensitive(xhtmlData, "\t", "");

            var reader = new StringReader(xhtmlData);

            var settings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Ignore
            };
            XmlReader xml = XmlReader.Create(reader, settings);

            string menuText = null;

            var dayOfWeek = (int)DateTime.Today.DayOfWeek;

            string[] dayNames = DateTimeFormatInfo.GetInstance(new CultureInfo("hu-HU")).DayNames;

            try
            {
                while (xml.Read())
                {
                    if (xml.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    if (xml.Name != "div" || !xml.HasAttributes || xml.GetAttribute("class") != "nev")
                    {
                        continue;
                    }

                    string headerContent = xml.ReadElementContentAsString();

                    // Read the menu contents if we have found one for today
                    if (!headerContent.ToLower().Contains(dayNames[dayOfWeek].ToLower()))
                    {
                        continue;
                    }

                    while (xml.Read())
                    {
                        if (xml.NodeType != XmlNodeType.Element)
                        {
                            continue;
                        }

                        if (xml.Name != "div" || !xml.HasAttributes || xml.GetAttribute("class") != "text")
                        {
                            continue;
                        }

                        string content = xml.ReadElementContentAsString();

                        var sb = new StringBuilder();
                        sb.AppendLine("A mai menü a Varjúban:");
                        sb.AppendLine(headerContent);
                        sb.AppendLine();
                        sb.AppendLine(content);

                        menuText = sb.ToString();

                        break;
                    }
                }
            }
            catch (XmlException e)
            {
                if (!e.Message.ToLower().Contains("unexpected end tag"))
                {
                    _log.Error("Failed to parse XHTML. Error: " + e);
                    menuText = "Hiba a feldolgozás során. Ellenőrizd a naplót.";
                }
            }

            if (menuText == null)
            {
                return("A mai napra nem található menü a Varjúban.");
            }

            return(menuText);
        }