Esempio n. 1
0
        public void Answer(Message msg)
        {
            string city1 = "Rome";

            try
            {
                substr1 = msg.text.Substring(51);
                city1   = substr1;
                string         url1            = ($"https://api.openweathermap.org/data/2.5/weather?q={city1}&units=metric&appid=01919e822c17cd48130238904353d786");
                HttpWebRequest httpWebRequest1 = (HttpWebRequest)WebRequest.Create(url1);

                HttpWebResponse httpWebResponse1 = (HttpWebResponse)httpWebRequest1.GetResponse();

                string response1;

                using (StreamReader streamReader1 = new StreamReader(httpWebResponse1.GetResponseStream()))
                {
                    response1 = streamReader1.ReadToEnd();
                }


                WeatherResponse weatherResponse1 = JsonConvert.DeserializeObject <WeatherResponse>(response1);
                float           lon             = weatherResponse1.Coord.Lon;
                float           lat             = weatherResponse1.Coord.Lat;
                string          url2            = ($"http://api.openweathermap.org/data/2.5/air_pollution?lat={lat}&lon={lon}&appid=01919e822c17cd48130238904353d786");
                HttpWebRequest  httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url2);

                HttpWebResponse httpWebResponse2 = (HttpWebResponse)httpWebRequest2.GetResponse();

                string response2;

                using (StreamReader streamReader2 = new StreamReader(httpWebResponse2.GetResponseStream()))
                {
                    response2 = streamReader2.ReadToEnd();
                }


                PollutionResponse1 weatherResponse2 = JsonConvert.DeserializeObject <PollutionResponse1>(response2);
                int    quality  = weatherResponse2.List[0].Main.Aqi;
                float  cofloat  = weatherResponse2.List[0].Components.Co;
                string costr    = cofloat.ToString();
                float  nofloat  = weatherResponse2.List[0].Components.No;
                string nostr    = nofloat.ToString();
                float  no2float = weatherResponse2.List[0].Components.No2;
                string no2str   = no2float.ToString();
                float  o3float  = weatherResponse2.List[0].Components.O3;
                string o3str    = o3float.ToString();

                string qualitystr = quality.ToString();



                publish.SendMessage($"Здравствуйте!\nСостояние атмосферы {qualitystr} по пятибальной шкале\n(5-отлично, 4-хороший и чистый воздух, 3-средний, 2-плохой, 1-очень плохой воздух).\nСодержание CO {costr} мкг/м3.\nСодержание NO {nostr} мкг/м3.\nСодержание NO2 {no2str} мкг/м3.\nСодержание O3 {o3str} мкг/м3.", msg.chat.id);
            }
            catch
            {
                publish.SendMessage("Неверный формат запроса о погоде в данном городе или ошибка в названии города", msg.chat.id);
            }
        }
Esempio n. 2
0
        public void Answer(Message msg)
        {
            try
            {
                List <Items> items = new List <Items>();
                xDoc.Load("https://www.sports.ru/rss/conference/338597.xml");
                XmlElement xRoot = xDoc.DocumentElement;

                foreach (XmlNode xnode in xRoot)
                {
                    foreach (XmlNode childnode in xnode.ChildNodes)
                    {
                        Items item = new Items();
                        if (childnode.Name == "title")
                        {
                            item.Title = childnode.InnerText;
                        }

                        if (childnode.Name == "description")
                        {
                            item.Description = childnode.InnerText;
                        }

                        if (childnode.Name == "item")
                        {
                            foreach (XmlNode childnode2 in childnode)
                            {
                                if (childnode2.Name == "title")
                                {
                                    item.Title = childnode2.InnerText;
                                }

                                if (childnode2.Name == "description")
                                {
                                    item.Description = childnode2.InnerText;
                                }

                                if (childnode2.Name == "link")
                                {
                                    item.Link = childnode2.InnerText;
                                }
                            }
                            items.Add(item);
                        }
                    }
                }
                foreach (Items i in items)
                {
                    publish.SendMessage($"\nНазвание:  {i.Title}\nСсылка на статью: {i.Link}", msg.chat.id);
                }
            }
            catch
            {
                publish.SendMessage("Ошибка во вводе", msg.chat.id);
            }
        }
Esempio n. 3
0
        public void Answer(Message msg)
        {
            try
            {
                List <Items> items = new List <Items>();
                xDoc.Load("https://news.ru/rss/category/post/economics/");
                XmlElement xRoot = xDoc.DocumentElement;

                foreach (XmlNode xnode in xRoot)
                {
                    foreach (XmlNode childnode in xnode.ChildNodes)
                    {
                        Items item = new Items();
                        if (childnode.Name == "title")
                        {
                            item.Title = childnode.InnerText;
                        }

                        if (childnode.Name == "description")
                        {
                            item.Description = childnode.InnerText;
                        }

                        if (childnode.Name == "item")
                        {
                            foreach (XmlNode childnode2 in childnode)
                            {
                                if (childnode2.Name == "title")
                                {
                                    item.Title = childnode2.InnerText;
                                }

                                if (childnode2.Name == "description")
                                {
                                    item.Description = childnode2.InnerText;
                                }

                                if (childnode2.Name == "link")
                                {
                                    item.Link = childnode2.InnerText;
                                }
                            }
                            items.Add(item);
                        }
                    }
                }
                for (int i = 0; i < 8; ++i)
                {
                    publish.SendMessage($"\nОписание:  {items[i].Title}\nСсылка на статью: {items[i].Link}", msg.chat.id);
                }
            }
            catch
            {
                publish.SendMessage("Ошибка во вводе", msg.chat.id);
            }
        }
Esempio n. 4
0
        public void Answer(Message message)
        {
            string city = "Rome";

            try
            {
                substr = message.text.Substring(14);
                city   = substr;
                string         url            = ($"https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid=01919e822c17cd48130238904353d786");
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                string response;

                using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                {
                    response = streamReader.ReadToEnd();
                }


                WeatherResponse weatherResponse         = JsonConvert.DeserializeObject <WeatherResponse>(response);
                float           curweatherweatherfloat  = weatherResponse.Main.Temp;
                string          curweatherstr           = curweatherweatherfloat.ToString();
                float           curweatherweather1float = weatherResponse.Main.Feels_like;
                string          curweatherstr1          = curweatherweather1float.ToString();
                int             humidity      = weatherResponse.Main.Humidity;
                string          humiditystr   = humidity.ToString();
                float           curwindfloat  = weatherResponse.Wind.Speed;
                string          curwindstr    = curwindfloat.ToString();
                int             pressure      = weatherResponse.Main.Pressure;
                int             pressure1     = (int)(pressure / 1.333);
                string          pressurestr   = pressure1.ToString();
                int             clouds        = weatherResponse.Clouds.All;
                string          cloudsstr     = clouds.ToString();
                int             visibility    = weatherResponse.Visibility;
                string          visibilitystr = visibility.ToString();



                publish.SendMessage($"Здравствуйте!\nТемпература в городе {curweatherstr} °C.\nТемпература ощущается как {curweatherstr1} °C.\nВлажность {humiditystr} %.\nДавление {pressurestr} мм рт. ст.\nСкорость ветра {curwindstr} м/c.\nОблачность {cloudsstr} %.\nВидимость {visibilitystr} метров.", message.chat.id);
            }
            catch
            {
                publish.SendMessage("Неверный формат запроса о погоде в данном городе или ошибка в названии города", message.chat.id);
            }
        }
Esempio n. 5
0
        public void Answer()
        {
            DateTime time     = DateTime.UtcNow;
            string   asString = time.ToString();


            publish.SendMessage(asString, this.message.chat.id);
        }
Esempio n. 6
0
        public void Answer(Message message)
        {
            string city3 = "Rome";

            try
            {
                substr3 = message.text.Substring(26);
                city3   = substr3;
                string         url1            = ($"https://api.openweathermap.org/data/2.5/weather?q={city3}&units=metric&appid=01919e822c17cd48130238904353d786");
                HttpWebRequest httpWebRequest3 = (HttpWebRequest)WebRequest.Create(url1);

                HttpWebResponse httpWebResponse3 = (HttpWebResponse)httpWebRequest3.GetResponse();

                string response3;

                using (StreamReader streamReader3 = new StreamReader(httpWebResponse3.GetResponseStream()))
                {
                    response3 = streamReader3.ReadToEnd();
                }


                WeatherResponse weatherResponse3 = JsonConvert.DeserializeObject <WeatherResponse>(response3);
                float           timezone         = weatherResponse3.Timezone;
                float           timezone1        = timezone / 3600;
                var             timezone2        = (double)timezone1;
                string          timezone1str     = timezone1.ToString();


                DateTime time      = DateTime.UtcNow;
                var      time2     = time.AddHours(timezone2);
                string   asString  = time2.ToString();
                string   asString2 = time2.ToString("dd.MM.yyyy, hh:mm:ss tt", CultureInfo.InvariantCulture);



                publish.SendMessage(asString, message.chat.id);
                publish.SendMessage(asString2, message.chat.id);
            }
            catch
            {
                publish.SendMessage("Неверный формат запроса о погоде в данном городе или ошибка в названии города", message.chat.id);
            }
        }
Esempio n. 7
0
        static void Main(string[] args)
        {
            var builder = new ConfigurationBuilder()
                          .AddJsonFile($"appsettings.json", true, true);


            var configuration = builder.Build();

            var webClient = new WebClient();

            var fileProvider        = new FileSystemProvider();
            var telegramBotSettings = configuration.GetSection("TelegramBotSettings").Get <TelegramBotSettings>();

            var webRequestor       = new WebRequestor(webClient);
            var chatUpdateReader   = new TelegramUpdatesReader(telegramBotSettings, webRequestor);
            var publishBotReaction = new TelegramChatMessagePublisher(telegramBotSettings, webRequestor);
            var chatBotState       = new ChatBotState(fileProvider);

            chatBotState.LoadState();

            var pollingWatcher = new TelegramChatUpdatesPollingWatcher(chatUpdateReader, chatBotState);

            var cancellationTokenSource = new CancellationTokenSource();


            var hellow     = new HellowAnswer(publishBotReaction);
            var Say        = new SayUserInformation(publishBotReaction);
            var weather    = new WeatherAnswer(publishBotReaction);
            var vedomosti  = new Vedomosti(publishBotReaction);
            var dw         = new EconomicsDw(publishBotReaction);
            var cbr        = new Cbr(publishBotReaction);
            var news       = new NewsRu(publishBotReaction);
            var prime      = new PrimeRu(publishBotReaction);
            var sport      = new Sport(publishBotReaction);
            var utkin      = new Utkin(publishBotReaction);
            var nike       = new Nike(publishBotReaction);
            var legislat   = new Legislation(publishBotReaction);
            var reebok     = new Reebok(publishBotReaction);
            var newbalance = new Newbalance(publishBotReaction);
            var answers    = new List <IBotAnswer>()
            {
                hellow, Say, weather, vedomosti, dw, cbr, news, prime, sport, utkin, nike, legislat, reebok, newbalance
            };
            var asker = new Asker(answers);



            pollingWatcher.OnMessageArrived += (msg) =>
            {
                Console.WriteLine($"{msg.text} from {msg.from.username} with id { msg.chat.id} {msg.from.id} ");

                if (msg.text == "/start")
                {
                    publishBotReaction.SendMessage("Приветствую вас! Я  готов к работе. Команды бота:\n1) Скажи погоду: [место].\n2)Скажи информацию про состояние атмосферы в городе: [название города].\n3)Сколько времени в городе: [название города].\nСобытия в мире экономики по версии:\n4)Газета ведомости -\n/EconomicsVedomosti.\n5)Cайт dw.com\n/EconomicsDw\n6)Сайт ЦБ РФ-\n/EconomicsCbr.\n7)Сайт news.ru-\n/EconomicsNewsRu.\n8)Сайт 1prime.ru-\n/EconomicsPrimeRu.\nНОВОСТИ СПОРТА:\n9)Cайт sports.ru-\n/SportsNews\n10)Блог Уткина-\n/UtkinSportsNews\nНОВЫЕ ЗАКОНЫ:\n11)Сайт с обновлениями законодательства РФ-\n/LegislationChanges.\nНОВОСТИ БРЕНДОВ ОДЕЖДЫ:\n12)Nike-\n/NikenewsFeed\n13)Reebok-\n/ReebokNewsGlobal\n14)NewBalance-\n/NewBalanceNewsMarket.", msg.chat.id);
                }



                TimeAnswer response = new TimeAnswer(publishBotReaction, msg);
                response.CanWork(msg.text);
                if (response.CanWork(msg.text) == true)
                {
                    response.Answer();
                }
                asker.Ask(msg.text, msg);
            };

            pollingWatcher.StartWatch(cancellationTokenSource.Token);

            var stop = Console.ReadLine();

            if (stop == "stop bot")
            {
                Console.WriteLine("Работа Бота остановлена. Сохранение.");
                cancellationTokenSource.Cancel();

                chatBotState.SaveState();
            }
        }