Esempio n. 1
6
        static async void ProcessUpdate(TelegramBotClient bot, Update update, User me)
        {
            // Read Configuration
            var wundergroundKey = ConfigurationManager.AppSettings["WundergroundKey"];
            var bingKey = ConfigurationManager.AppSettings["BingKey"];
            var wolframAppId = ConfigurationManager.AppSettings["WolframAppID"];

            // Process Request
            try
            {
                var httpClient = new ProHttpClient();
                var text = update.Message.Text;
                var replyText = string.Empty;
                var replyTextMarkdown = string.Empty;
                var replyImage = string.Empty;
                var replyImageCaption = string.Empty;
                var replyDocument = string.Empty;

                if (text != null && (text.StartsWith("/", StringComparison.Ordinal) || text.StartsWith("!", StringComparison.Ordinal)))
                {
                    // Log to console
                    Console.WriteLine(update.Message.Chat.Id + " < " + update.Message.From.Username + " - " + text);

                    // Allow ! or /
                    if (text.StartsWith("!", StringComparison.Ordinal))
                    {
                        text = "/" + text.Substring(1);
                    }

                    // Strip @BotName
                    text = text.Replace("@" + me.Username, "");

                    // Parse
                    string command;
                    string body;
                    if (text.StartsWith("/s/", StringComparison.Ordinal))
                    {
                        command = "/s"; // special case for sed
                        body = text.Substring(2);
                    }
                    else
                    {
                        command = text.Split(' ')[0];
                        body = text.Replace(command, "").Trim();
                    }
                    var stringBuilder = new StringBuilder();

                    switch (command.ToLowerInvariant())
                    {
                        case "/beer":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /beer <Name of beer>";
                                break;
                            }

                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            var beerSearch = httpClient.DownloadString("http://www.beeradvocate.com/search/?q=" + HttpUtility.UrlEncode(body) + "&qt=beer").Result.Replace("\r", "").Replace("\n", "");

                            // Load First Result
                            var firstBeer = Regex.Match(beerSearch, @"<div id=""ba-content"">.*?<ul>.*?<li>.*?<a href=""(.*?)"">").Groups[1].Value.Trim();
                            if (firstBeer == string.Empty)
                            {
                                replyText = "The Great & Powerful Trixie was unable to find a beer name matching: " + body;
                                break;
                            }
                            var beer = httpClient.DownloadString("http://www.beeradvocate.com" + firstBeer).Result.Replace("\r", "").Replace("\n", "");
                            var beerName = Regex.Match(beer, @"<title>(.*?)</title>").Groups[1].Value.Replace(" | BeerAdvocate", string.Empty).Trim();
                            beer = Regex.Match(beer, @"<div id=""ba-content"">.*?<div>(.*?)<div style=""clear:both;"">").Groups[1].Value.Trim();
                            replyImage = Regex.Match(beer, @"img src=""(.*?)""").Groups[1].Value.Trim();
                            replyImageCaption = "http://www.beeradvocate.com" + firstBeer;
                            var beerScore = Regex.Match(beer, @"<span class=""BAscore_big ba-score"">(.*?)</span>").Groups[1].Value.Trim();
                            var beerScoreText = Regex.Match(beer, @"<span class=""ba-score_text"">(.*?)</span>").Groups[1].Value.Trim();
                            var beerbroScore = Regex.Match(beer, @"<span class=""BAscore_big ba-bro_score"">(.*?)</span>").Groups[1].Value.Trim();
                            var beerbroScoreText = Regex.Match(beer, @"<b class=""ba-bro_text"">(.*?)</b>").Groups[1].Value.Trim();
                            var beerHads = Regex.Match(beer, @"<span class=""ba-ratings"">(.*?)</span>").Groups[1].Value.Trim();
                            var beerAvg = Regex.Match(beer, @"<span class=""ba-ravg"">(.*?)</span>").Groups[1].Value.Trim();
                            var beerStyle = Regex.Match(beer, @"<b>Style:</b>.*?<b>(.*?)</b>").Groups[1].Value.Trim();
                            var beerAbv = beer.Substring(beer.IndexOf("(ABV):", StringComparison.Ordinal) + 10, 7).Trim();
                            var beerDescription = Regex.Match(beer, @"<b>Notes / Commercial Description:</b>(.*?)</div>").Groups[1].Value.Replace("|", "").Trim();
                            stringBuilder.Append(beerName.Replace("|", "- " + beerStyle + " by") + "\r\nScore: " + beerScore + " (" + beerScoreText + ") | Bros: " + beerbroScore + " (" + beerbroScoreText + ") | Avg: " + beerAvg + " (" + beerHads + " hads)\r\nABV: " + beerAbv + " | ");
                            stringBuilder.Append(HttpUtility.HtmlDecode(beerDescription).Replace("<br>"," ").Trim());
                            break;

                        case "/cat":
                            replyImage = "http://thecatapi.com/api/images/get?format=src&type=jpg,png";
                            break;

                        case "/doge":
                            replyImage = "http://dogr.io/wow/" + body.Replace(",", "/").Replace(" ", "") + ".png";
                            replyImageCaption = "wow";
                            break;

                        case "/echo":
                            replyText = body;
                            break;

                        case "/fat":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /fat <Name of food>";
                                break;
                            }

                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            var search = httpClient.DownloadString("http://www.calorieking.com/foods/search.php?keywords=" + body).Result.Replace("\r", "").Replace("\n", "");

                            // Load First Result
                            var firstUrl = Regex.Match(search, @"<a class=""food-search-result-name"" href=""([\w:\/\-\._]*)""").Groups[1].Value.Trim();
                            if (firstUrl == string.Empty)
                            {
                                replyText = "The Great & Powerful Trixie was unable to find a food name matching: " + body;
                                break;
                            }
                            var food = httpClient.DownloadString(firstUrl).Result.Replace("\r", "").Replace("\n", "");

                            // Scrape it
                            var label = string.Empty;
                            var protein = 0.0;
                            var carbs = 0.0;
                            var fat = 0.0;
                            var fiber = 0.0;
                            stringBuilder.Append(Regex.Match(food, @"<title>(.*)\ \|.*<\/title>").Groups[1].Value.Replace("Calories in ", "").Trim() + " per "); // Name of item
                            stringBuilder.Append(Regex.Match(food, @"<select name=""units"".*?<option.*?>(.*?)<\/option>", RegexOptions.IgnoreCase).Groups[1].Value.Trim() + "\r\n"); // Unit
                            foreach (Match fact in Regex.Matches(food, @"<td class=""(calories|label|amount)"">([a-zA-Z0-9\ &;<>=\/\""\.]*)<\/td>"))
                            {
                                switch (fact.Groups[1].Value.Trim().ToLowerInvariant())
                                {
                                    case "calories":
                                        stringBuilder.Append("Calories: " + fact.Groups[2].Value.Replace("Calories&nbsp;<span class=\"amount\">", "").Replace("</span>", "") + ", ");
                                        break;

                                    case "label":
                                        label = fact.Groups[2].Value.Trim();
                                        break;

                                    case "amount":
                                        stringBuilder.Append(label + ": " + fact.Groups[2].Value + ", ");
                                        switch (label.ToLowerInvariant())
                                        {
                                            case "protein":
                                                protein = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("&lt;", "").Replace("&gt;", ""));
                                                break;

                                            case "total carbs.":
                                                carbs = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("&lt;", "").Replace("&gt;", ""));
                                                break;

                                            case "total fat":
                                                fat = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("&lt;", "").Replace("&gt;", ""));
                                                break;

                                            case "dietary fiber":
                                                fiber = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("&lt;", "").Replace("&gt;", ""));
                                                break;
                                        }
                                        break;
                                }
                            }

                            // WW Points = (Protein/10.9375) + (Carbs/9.2105) + (Fat/3.8889) - (Fiber/12.5)
                            stringBuilder.Append("WW PointsPlus: " + Math.Round((protein / 10.9375) + (carbs / 9.2105) + (fat / 3.8889) - (fiber / 12.5), 1));
                            break;

                        case "/forecast":
                            if (body.Length < 2)
                            {
                                body = "Cincinnati, OH";
                            }

                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic dfor = JObject.Parse(httpClient.DownloadString("http://api.wunderground.com/api/" + wundergroundKey + "/forecast/q/" + body + ".json").Result);
                            if (dfor.forecast == null || dfor.forecast.txt_forecast == null)
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try \"City, ST\" or \"City, Country\" next time.";
                                break;
                            }
                            for (var ifor = 0; ifor < Enumerable.Count(dfor.forecast.txt_forecast.forecastday) - 1; ifor++)
                            {
                                stringBuilder.AppendLine(dfor.forecast.txt_forecast.forecastday[ifor].title.ToString() + ": " + dfor.forecast.txt_forecast.forecastday[ifor].fcttext.ToString());
                            }
                            break;

                        case "/help":
                            replyText = "The Great & powerful Trixie understands the following commands:\r\n" +
                                "/cat /doge /fat /forecast /help /image /imdb /google /joke /map /outside /overwatch /pony /radar /satellite /stock /stock7 /stockyear /translate /translateto /trixie /version /weather /wiki /ww";
                            /* Send this string of text to BotFather to register the bot's commands:
cat - Get a picture of a cat
doge - Dogeify a comma sep list of terms
fat - Nutrition information
forecast - Weather forecast
help - Displays help text
image - Search for an image
imdb - Search IMDB for a movie name
google - Search Google
map - Returns a location for the given search
joke - Returns a random joke from /r/jokes on Reddit
outside - Webcam image
overwatch - Overwatch Stats
pony - Ponies matching comma separated tags
radar - Weather radar
remind - Sets a reminder message after X minutes
satellite - Weather Satellite
stock - US Stock Chart (1 day)
stock7 - US Stock Chart (7 day)
stockyear - US Stock Chart (12 month)
translate - Translate to english
translateto - Translate to a given language
trixie - Wolfram Alpha logic search
version - Display version info
weather - Current weather conditions
wiki - Search Wikipedia
ww - WeightWatcher PointsPlus calc
                            */
                            break;

                        case "/image":
                        case "/img":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /image <Description of image to find>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            httpClient.AuthorizationHeader = "Basic " + bingKey;
                            dynamic dimg = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Market=%27en-US%27&Adult=%27Moderate%27&Query=%27" + HttpUtility.UrlEncode(body) + "%27&$format=json&$top=3").Result);
                            httpClient.AuthorizationHeader = string.Empty;
                            if (dimg.d == null || dimg.d.results == null || Enumerable.Count(dimg.d.results) < 1)
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                                break;
                            }
                            var rimg = new Random();
                            var iimgmax = Enumerable.Count(dimg.d.results);
                            if (iimgmax > 3)
                            {
                                iimgmax = 3;
                            }
                            var iimg = rimg.Next(0, iimgmax);
                            string imageUrl = dimg.d.results[iimg].MediaUrl.ToString();
                            if (imageUrl.Trim().EndsWith(".gif", StringComparison.Ordinal))
                            {
                                replyDocument = dimg.d.results[iimg].MediaUrl;
                            }
                            else
                            {
                                replyImage = dimg.d.results[iimg].MediaUrl;
                            }
                            break;

                        case "/imdb":
                        case "/rt":
                        case "/movie":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /imdb <Movie Title>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);

                            // Search Bing
                            httpClient.AuthorizationHeader = "Basic " + bingKey;
                            dynamic dimdb = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Market=%27en-US%27&Adult=%27Moderate%27&Query=%27site%3Aimdb.com%20" + HttpUtility.UrlEncode(body) + "%27&$format=json&$top=1").Result);
                            httpClient.AuthorizationHeader = string.Empty;
                            if (dimdb.d == null || dimdb.d.results == null ||
                                Enumerable.Count(dimdb.d.results) < 1)
                            {
                                replyText = "Trixie was unable to find a movie name matching:" + body;
                                break;
                            }

                            // Find correct /combined URL
                            string imdbUrl = dimdb.d.results[0].Url;
                            imdbUrl = (imdbUrl.Replace("/business", "").Replace("/combined", "").Replace("/faq", "").Replace("/goofs", "").Replace("/news", "").Replace("/parentalguide", "").Replace("/quotes", "").Replace("/ratings", "").Replace("/synopsis", "").Replace("/trivia", "") + "/combined").Replace("//combined","/combined");

                            // Scrape it
                            var imdb = httpClient.DownloadString(imdbUrl).Result.Replace("\r", "").Replace("\n", "");
                            var title = Regex.Match(imdb, @"<title>(IMDb \- )*(.*?) \(.*?</title>", RegexOptions.IgnoreCase).Groups[2].Value.Trim();
                            var year = Regex.Match(imdb, @"<title>.*?\(.*?(\d{4}).*?\).*?</title>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var rating = Regex.Match(imdb, @"<b>(\d.\d)/10</b>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var votes = Regex.Match(imdb, @">(\d+,?\d*) votes<", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var plot = Regex.Match(imdb, @"Plot:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var tagline = Regex.Match(imdb, @"Tagline:</h5>.*?<div class=""info-content"">(.*?)(<a|</div)", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var poster = Regex.Match(imdb, @"<div class=""photo"">.*?<a name=""poster"".*?><img.*?src=""(.*?)"".*?</div>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                            var posterFull = string.Empty;
                            if (!string.IsNullOrEmpty(poster) && poster.IndexOf("media-imdb.com", StringComparison.Ordinal) > 0)
                            {
                                poster = Regex.Replace(poster, @"_V1.*?.jpg", "_V1._SY200.jpg");
                                posterFull = Regex.Replace(poster, @"_V1.*?.jpg", "_V1._SX1280_SY1280.jpg");
                            }
                            if (title.Length < 2)
                            {
                                replyText = "Trixie was unable to find a movie name matching: " + body;
                            }
                            else
                            {
                                // Try for RT score scrape
                                httpClient.AuthorizationHeader = "Basic " + bingKey;
                                dynamic drt = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Market=%27en-US%27&Adult=%27Moderate%27&Query=%27site%3Arottentomatoes.com%20" + HttpUtility.UrlEncode(body) + "%27&$format=json&$top=1").Result);
                                httpClient.AuthorizationHeader = string.Empty;
                                if (drt.d != null && drt.d.results != null && Enumerable.Count(drt.d.results) > 0)
                                {
                                    string rtUrl = drt.d.results[0].Url;
                                    var rt = httpClient.DownloadString(rtUrl).Result;
                                    //var rtCritic = Regex.Match(rt, @"<span class=""meter-value .*?<span>(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    var rtCritic = Regex.Match(rt, @"<span class=""meter-value superPageFontColor""><span>(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    var rtAudience = Regex.Match(rt, @"<span class=""superPageFontColor"" style=""vertical-align:top"">(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    replyText = HttpUtility.HtmlDecode(title) + " (" + year + ") - " + HttpUtility.HtmlDecode(tagline) + "\r\nIMDb: " + rating + " (" + votes + " votes) | RT critic: " + rtCritic + "% | RT audience: " + rtAudience + "\r\n" + HttpUtility.HtmlDecode(plot);
                                }
                                else
                                {
                                    var rt = httpClient.DownloadString("http://www.rottentomatoes.com/search/?search=" + HttpUtility.UrlEncode(body)).Result;
                                    //var rtCritic = Regex.Match(rt, @"<span class=""meter-value .*?<span>(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    var rtCritic = Regex.Match(rt, @"<span class=""meter-value superPageFontColor""><span>(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    var rtAudience = Regex.Match(rt, @"<span class=""superPageFontColor"" style=""vertical-align:top"">(.*?)</span>", RegexOptions.IgnoreCase).Groups[1].Value.Trim();
                                    replyText = HttpUtility.HtmlDecode(title) + " (" + year + ") - " + HttpUtility.HtmlDecode(tagline) + "\r\nIMDb: " + rating + " (" + votes + " votes) | RT critic: " + rtCritic + "% | RT audience: " + rtAudience + "\r\n" + HttpUtility.HtmlDecode(plot);
                                }

                                // Remove trailing pipe that sometimes occurs
                                if (replyText.EndsWith("|"))
                                {
                                    replyText = replyText.Substring(0, replyText.Length - 2).Trim();
                                }

                                // Set referrer URI to grab IMDB poster
                                httpClient.ReferrerUri = imdbUrl;
                                replyImage = posterFull;
                                replyImageCaption = imdbUrl;
                            }
                            break;

                        case "/joke":
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic djoke = JObject.Parse(httpClient.DownloadString("https://api.reddit.com/r/jokes/top?t=day&limit=5").Result);
                            var rjoke = new Random();
                            var ijokemax = Enumerable.Count(djoke.data.children);
                            if (ijokemax > 4)
                            {
                                ijokemax = 4;
                            }
                            var ijoke = rjoke.Next(0, ijokemax);
                            replyText = djoke.data.children[ijoke].data.title.ToString() + " " + djoke.data.children[ijoke].data.selftext.ToString();
                            break;

                        case "/map":
                        case "/location":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /map <Search Text>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic dmap = JObject.Parse(httpClient.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address=" + HttpUtility.UrlEncode(body)).Result);
                            if (dmap == null || dmap.results == null || Enumerable.Count(dmap.results) < 1)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                            }
                            else
                            {
                                await bot.SendLocationAsync(update.Message.Chat.Id, (float)dmap.results[0].geometry.location.lat, (float)dmap.results[0].geometry.location.lng);
                            }
                            break;

                        case "/google":
                        case "/bing":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /google <Search Text>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            httpClient.AuthorizationHeader = "Basic " + bingKey;
                            dynamic dgoog = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Market=%27en-US%27&Adult=%27Moderate%27&Query=%27" + HttpUtility.UrlEncode(body) + "%27&$format=json&$top=1").Result);
                            httpClient.AuthorizationHeader = string.Empty;
                            if (dgoog.d == null || dgoog.d.results == null || Enumerable.Count(dgoog.d.results) < 1)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                            }
                            else
                            {
                                var rgoog = new Random();
                                var igoog = rgoog.Next(0, Enumerable.Count(dgoog.d.results));
                                replyText = HttpUtility.HtmlDecode(dgoog.d.results[igoog].Title.ToString()) + " | " + HttpUtility.HtmlDecode(dgoog.d.results[igoog].Description.ToString()) + "\r\n" + dgoog.d.results[igoog].Url;
                            }
                            break;

                        case "/outside":
                            if (body.Length < 2)
                            {
                                body = "Cincinnati, OH";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic dout = JObject.Parse(httpClient.DownloadString("http://api.wunderground.com/api/" + wundergroundKey + "/webcams/q/" + body + ".json").Result);
                            if (dout.webcams == null)
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try \"City, ST\" or \"City, Country\" next time.";
                                break;
                            }
                            var rout = new Random();
                            var iout = rout.Next(0, Enumerable.Count(dout.webcams));
                            replyImage = dout.webcams[iout].CURRENTIMAGEURL;
                            replyImageCaption = dout.webcams[iout].organization + " " + dout.webcams[iout].neighborhood + " " + dout.webcams[iout].city + ", " + dout.webcams[iout].state + "\r\n" + dout.webcams[iout].CAMURL;
                            break;

                        case "/overwatch":
                            if (body.Length < 2)
                            {
                                replyText = "Usage: /overwatch <Battletag with no spaces>  eg: /overwatch SniperFox#1513";
                                break;
                            }
                            var ow = new OverwatchPlayer(body, Platform.pc, Region.us);
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            ow.UpdateStats().GetAwaiter().GetResult();
                            if (ow.CompetitiveStats.AllHeroes != null)
                            { 
                                replyTextMarkdown = "*Competitive Play - Rank " + ow.CompetitiveRank + "*\r\n" + ow.CompetitiveStats.AllHeroes.Game.GamesWon + " wins, " + (ow.CompetitiveStats.AllHeroes.Game.GamesPlayed - ow.CompetitiveStats.AllHeroes.Game.GamesWon) + " losses " +
                                    "(" + Math.Round((ow.CompetitiveStats.AllHeroes.Game.GamesWon / ow.CompetitiveStats.AllHeroes.Game.GamesPlayed) * 100, 2) + "%) " +
                                    "over " + Math.Round(ow.CompetitiveStats.AllHeroes.Game.TimePlayed.TotalHours / 24, 2) + " days played.\r\n" +
                                    ow.CompetitiveStats.AllHeroes.Combat.Eliminations + " eliminations, " + ow.CompetitiveStats.AllHeroes.Deaths.Deaths + " deaths, " + Math.Round(ow.CompetitiveStats.AllHeroes.Combat.Eliminations / ow.CompetitiveStats.AllHeroes.Deaths.Deaths, 2) + " eliminations per death.\r\n" +
                                    ow.CompetitiveStats.AllHeroes.MatchAwards.Cards + " cards, " + ow.CompetitiveStats.AllHeroes.MatchAwards.MedalsGold + " gold, " + ow.CompetitiveStats.AllHeroes.MatchAwards.MedalsSilver + " silver, and " + ow.CompetitiveStats.AllHeroes.MatchAwards.MedalsGold + " bronze medals.\r\n";
                            }
                            replyTextMarkdown += "*Quick Filthy Casual Play - Level " + ow.PlayerLevel + "*\r\n" + ow.CasualStats.AllHeroes.Game.GamesWon + " wins, " + (ow.CasualStats.AllHeroes.Game.GamesPlayed - ow.CasualStats.AllHeroes.Game.GamesWon) + " losses " +
                                "(" + Math.Round((ow.CasualStats.AllHeroes.Game.GamesWon / ow.CasualStats.AllHeroes.Game.GamesPlayed) * 100, 2) + "%) " +
                                "over " + Math.Round(ow.CasualStats.AllHeroes.Game.TimePlayed.TotalHours / 24, 2) + " days played.\r\n" +
                                ow.CasualStats.AllHeroes.Combat.Eliminations + " eliminations, " + ow.CasualStats.AllHeroes.Deaths.Deaths + " deaths, " + Math.Round(ow.CasualStats.AllHeroes.Combat.Eliminations / ow.CasualStats.AllHeroes.Deaths.Deaths, 2) + " eliminations per death.\r\n" +
                                ow.CasualStats.AllHeroes.MatchAwards.Cards + " cards, " + ow.CasualStats.AllHeroes.MatchAwards.MedalsGold + " gold, " + ow.CasualStats.AllHeroes.MatchAwards.MedalsSilver + " silver, and " + ow.CasualStats.AllHeroes.MatchAwards.MedalsGold + " bronze medals.\r\n" +
                                ow.ProfileURL.Replace("/en-gb/", "/en-us/");
                            break;

                        case "/pony":
                        case "/pone":
                            if (body.Length < 2)
                            {
                                replyText = "I like ponies too.  What kind of pony would you like me to search for?";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic dpony = JObject.Parse(httpClient.DownloadString("https://derpibooru.org/search.json?q=safe," + HttpUtility.UrlEncode(body)).Result);
                            if (dpony.search == null)
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.";
                                break;
                            }
                            var rpony = new Random();
                            var iponymax = Enumerable.Count(dpony.search);
                            if (iponymax < 1)
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.";
                                break;
                            }
                            if (iponymax > 5)
                            {
                                iponymax = 5;
                            }
                            var ipony = rpony.Next(0, iponymax);
                            replyImage = "https:" + dpony.search[ipony].representations.large;
                            replyImageCaption = "https:" + dpony.search[ipony].image;
                            break;

                        case "/radar":
                            if (body.Length < 2)
                            { 
                                body = "Cincinnati, OH";
                            }
                            replyDocument = "http://api.wunderground.com/api/" + wundergroundKey + "/animatedradar/q/" + body + ".gif?newmaps=1&num=15&width=1024&height=1024";
                            break;

                        case "/remind":
                        case "/remindme":
                        case "/reminder":
                            if (body.Length < 2 || !body.Contains(" "))
                            { 
                                replyText = "Usage: /remind <minutes> <Reminder Text>";
                            }
                            else
                            {
                                var delayMinutesString = body.Substring(0, body.IndexOf(" ", StringComparison.Ordinal));
                                int delayMinutes;
                                if (int.TryParse(delayMinutesString, out delayMinutes))
                                {
                                    if (delayMinutes > 1440 || delayMinutes < 1)
                                    {
                                        replyText = "Reminders can not be set for longer than 1440 minutes (24 hours).";
                                    }
                                    else
                                    {
                                        DelayedMessage(bot, update.Message.Chat.Id, "@" + update.Message.From.Username + " Reminder: " + body.Substring(delayMinutesString.Length).Trim(), delayMinutes);
                                        replyText = "OK, I'll remind you at " + DateTime.Now.AddMinutes(delayMinutes).ToString("MM/dd/yyyy HH:mm") + " (US Eastern)";
                                    }
                                }
                                else
                                {
                                    replyText = "Usage: /remind <minutes as positive integer> <Reminder Text>";
                                }
                            }
                            break;

                        case "/s":
                            if (body.Length < 2 || update.Message.ReplyToMessage == null)
                            { 
                                replyText = "This must be done as a reply in the format /s/replace this/replace with/";
                            }
                            else
                            {
                                var sed = body.Split('/');
                                if (sed.Length != 4)
                                    replyText = "The only sed command parsed is /s/replace this/replace with/";
                                else
                                {
                                    replyTextMarkdown = "*" + update.Message.ReplyToMessage.From.FirstName + " " + update.Message.ReplyToMessage.From.LastName + "* \r\n" + update.Message.ReplyToMessage.Text.Replace(sed[1], sed[2]);
                                }
                            }
                            break;

                        case "/satellite":
                            if (body.Length < 2)
                            { 
                                body = "Cincinnati, OH";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic rsat = JObject.Parse(httpClient.DownloadString("http://api.wunderground.com/api/" + wundergroundKey + "/satellite/q/" + body + ".json").Result);
                            if (rsat.satellite == null || rsat.satellite.image_url == null)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try \"City, ST\" or \"City, Country\" next time.";
                            }
                            else
                            {
                                string saturl = rsat.satellite.image_url;
                                replyImage = saturl.Replace("height=300", "height=1280").Replace("width=300", "width=1280").Replace("radius=75", "radius=250");
                                replyImageCaption = body + " as of " + DateTime.Now.ToString("MM/dd/yyy HH:mm:ss");
                            }
                            break;

                        case "/stock":
                            if (body.Length < 1 || body.Length > 5)
                            { 
                                body = "^DJI";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            replyImage = "https://chart.yahoo.com/t?s=" + body + "&lang=en-US&region=US&width=1200&height=765";
                            replyImageCaption = "Chart for " + body + " as of " + DateTime.Now.ToString("MM/dd/yyy HH:mm:ss");
                            break;

                        case "/stock5":
                            if (body.Length < 1 || body.Length > 5)
                            { 
                                body = "^DJI";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            replyImage = "https://chart.yahoo.com/w?s=" + body + "&lang=en-US&region=US&width=1200&height=765";
                            replyImageCaption = "5 day chart for " + body + " as of " + DateTime.Now.ToString("MM/dd/yyy HH:mm:ss");
                            break;

                        case "/stockyear":
                            if (body.Length < 1 || body.Length > 5)
                            { 
                                body = "^DJI";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            replyImage = "https://chart.yahoo.com/c/1y/" + body;
                            replyImageCaption = "Year chart for " + body + " as of " + DateTime.Now.ToString("MM/dd/yyy HH:mm:ss");
                            break;

                        case "/translateto":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /translateto <Language Code> <English Text>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            var lang = body.Substring(0, body.IndexOf(" ", StringComparison.Ordinal));
                            var query = body.Substring(body.IndexOf(" ", StringComparison.Ordinal) + 1);
                            httpClient.AuthorizationHeader = "Basic " + bingKey;
                            dynamic dtto = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=%27" + HttpUtility.UrlEncode(query) + "%27&To=%27" + lang + "%27&$format=json").Result);
                            httpClient.AuthorizationHeader = string.Empty;
                            if (dtto.d == null || dtto.d.results == null || Enumerable.Count(dtto.d.results) < 1 || dtto.d.results[0].Text == null)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                            }
                            else
                            { 
                                replyText = dtto.d.results[0].Text;
                            }
                            break;

                        case "/translate":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /translate <Foreign Text>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            httpClient.AuthorizationHeader = "Basic " + bingKey;
                            dynamic dtrans = JObject.Parse(httpClient.DownloadString("https://api.datamarket.azure.com/Bing/MicrosoftTranslator/v1/Translate?Text=%27" + HttpUtility.UrlEncode(body) + "%27&To=%27en%27&$format=json").Result);
                            httpClient.AuthorizationHeader = string.Empty;
                            if (dtrans.d == null || dtrans.d.results == null || Enumerable.Count(dtrans.d.results) < 1 || dtrans.d.results[0].Text == null)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                            }
                            else
                            { 
                                replyText = dtrans.d.results[0].Text;
                            }
                            break;

                        case "/trixie":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /trixie <Query>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            var xmlDoc = new XmlDocument();
                            xmlDoc.LoadXml(httpClient.DownloadString("http://api.wolframalpha.com/v2/query?input=" + HttpUtility.UrlEncode(body) + "&appid=" + wolframAppId).Result);
                            var queryResult = xmlDoc.SelectSingleNode("/queryresult");
                            if (queryResult == null || queryResult?.Attributes == null || queryResult.Attributes?["success"] == null || queryResult.Attributes?["success"].Value != "true")
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try harder next time.";
                                break;
                            }
                            var pods = queryResult.SelectNodes("pod");
                            foreach (var pod in pods.Cast<XmlNode>().Where(pod => pod.Attributes != null && pod.Attributes["title"].Value != "Input interpretation"))
                            {
                                // Parse Image
                                if (replyImage == string.Empty)
                                {
                                    try
                                    {
                                        var subPodImage = pod.SelectSingleNode("subpod/img");
                                        if (subPodImage.Attributes != null)
                                        {
                                            replyImage = subPodImage.Attributes?["src"].Value.Trim();
                                        }
                                    }
                                    catch
                                    {
                                        // Don't care
                                    }
                                }

                                // Parse plain text
                                try
                                {
                                    var subPodPlainText = pod.SelectSingleNode("subpod/plaintext");
                                    if (subPodPlainText == null || subPodPlainText.InnerText.Trim().Length <= 0) continue;
                                    var podName = pod.Attributes?["title"].Value.Trim();
                                    if (podName == "Response" || podName == "Result")
                                    { 
                                        stringBuilder.AppendLine(subPodPlainText.InnerText);
                                    }
                                    else
                                    { 
                                        stringBuilder.AppendLine(podName + ": " + subPodPlainText.InnerText);
                                    }
                                }
                                catch
                                {
                                    // Don't care
                                }
                            }
                            break;

                        case "/version":
                        case "/about":
                            replyText = "Trixie Is Best Pony Bot\r\nRelease fourty-two\r\nBy http://scottrfrost.github.io";
                            break;

                        case "/weather":
                            if (body.Length < 2)
                            { 
                                body = "Cincinnati, OH";
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            dynamic dwthr = JObject.Parse(httpClient.DownloadString("http://api.wunderground.com/api/" + wundergroundKey + "/conditions/q/" + body + ".json").Result);
                            if (dwthr.current_observation == null)
                            { 
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.  Try \"City, ST\" or \"City, Country\" next time.";
                            }
                            else
                            { 
                                replyText =
                                    dwthr.current_observation.display_location.full + " Conditions: " +
                                    dwthr.current_observation.weather +
                                    " Wind: " + dwthr.current_observation.wind_string +
                                    " Temp: " + dwthr.current_observation.temperature_string + " Feels Like: " +
                                    dwthr.current_observation.feelslike_string;
                            }
                            break;

                        case "/wiki":
                            if (body == string.Empty)
                            {
                                replyText = "Usage: /wiki <Query>";
                                break;
                            }
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                            var dwiki = JObject.Parse(httpClient.DownloadString("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&redirects=true&titles=" + HttpUtility.UrlEncode(body)).Result);
                            if (dwiki["query"].HasValues && dwiki["query"]["pages"].HasValues)
                            {
                                var page = dwiki["query"]["pages"].First().First();
                                if (Convert.ToString(page["pageid"]).Length > 0)
                                    replyTextMarkdown = "*" + page["title"] + "*\r\n" + page["extract"] + "\r\n" + "https://en.wikipedia.org/?curid=" + page["pageid"];
                                else
                                {
                                    replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.";
                                }
                            }
                            else
                            {
                                replyText = "You have disappointed Trixie.  \"" + body + "\" is bullshit and you know it.";
                                
                            }
                            break;

                        case "/ww":
                            var split = body.Split(' ');
                            if (split.Length != 4)
                            {
                                replyText = "Usage: /ww <carbs> <fat> <fiber> <protein>";
                                break;
                            }
                            try
                            {
                                var wwcarbs = Convert.ToDouble(split[0]);
                                var wwfat = Convert.ToDouble(split[1]);
                                var wwfiber = Convert.ToDouble(split[2]);
                                var wwprotein = Convert.ToDouble(split[3]);
                                replyText = "WW PointsPlus value for " + wwcarbs + "g carbs, " + wwfat + "g fat, " + wwfiber + "g fiber, " + wwprotein + "g protein is: " + Math.Round((wwprotein / 10.9375) + (wwcarbs / 9.2105) + (wwfat / 3.8889) - (wwfiber / 12.5), 1);
                            }
                            catch
                            {
                                replyText = "Trixie is disappointed that you used /ww incorrectly. The correct usage is: /ww <carbs> <fat> <fiber> <protein>";
                            }
                            break;
                    }

                    // Output
                    replyText += stringBuilder.ToString();
                    if (!string.IsNullOrEmpty(replyText))
                    {
                        Console.WriteLine(update.Message.Chat.Id + " > " + replyText);
                        await bot.SendTextMessageAsync(update.Message.Chat.Id, replyText);
                    }
                    if (!string.IsNullOrEmpty(replyTextMarkdown))
                    {
                        Console.WriteLine(update.Message.Chat.Id + " > " + replyTextMarkdown);
                        await bot.SendTextMessageAsync(update.Message.Chat.Id, replyTextMarkdown, false, false, 0, null, ParseMode.Markdown);
                    }

                    if (!string.IsNullOrEmpty(replyImage) && replyImage.Length > 5)
                    {
                        Console.WriteLine(update.Message.Chat.Id + " > " + replyImage);
                        await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing);
                        try
                        {
                            var stream = httpClient.DownloadData(replyImage).Result;
                            var extension = ".jpg";
                            if (replyImage.Contains(".gif") || replyImage.Contains("image/gif"))
                            { 
                                extension = ".gif";
                            }
                            else if (replyImage.Contains(".png") || replyImage.Contains("image/png"))
                            { 
                                extension = ".png";
                            }
                            else if (replyImage.Contains(".tif"))
                            { 
                                extension = ".tif";
                            }
                            else if (replyImage.Contains(".bmp"))
                            { 
                                extension = ".bmp";
                            }
                            var photo = new FileToSend("Photo" + extension, stream);
                            await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.UploadPhoto);
                            if (extension == ".gif")
                            { 
                                await bot.SendDocumentAsync(update.Message.Chat.Id, photo);
                            }
                            else
                            { 
                                await bot.SendPhotoAsync(update.Message.Chat.Id, photo, replyImageCaption == string.Empty ? replyImage : replyImageCaption);
                            }
                        }
                        catch (System.Net.Http.HttpRequestException ex)
                        {
                            Console.WriteLine("Unable to download " + ex.HResult + " " + ex.Message);
                            await bot.SendTextMessageAsync(update.Message.Chat.Id, replyImage);
                        }
                        catch (System.Net.WebException ex)
                        {
                            Console.WriteLine("Unable to download " + ex.HResult + " " + ex.Message);
                            await bot.SendTextMessageAsync(update.Message.Chat.Id, replyImage);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(replyImage + " Threw: " + ex.Message);
                            await bot.SendTextMessageAsync(update.Message.Chat.Id, replyImage);
                        }
                    }

                    if (!string.IsNullOrEmpty(replyDocument) && replyDocument.Length > 5)
                    {
                        Console.WriteLine(update.Message.Chat.Id + " > " + replyDocument);
                        await bot.SendChatActionAsync(update.Message.Chat.Id, ChatAction.UploadDocument);
                        var stream = httpClient.DownloadData(replyDocument).Result;
                        var filename = replyDocument.Substring(replyDocument.LastIndexOf("/", StringComparison.Ordinal));
                        var document = new FileToSend(filename, stream);
                        await bot.SendDocumentAsync(update.Message.Chat.Id, document);
                    }
                }
            }
            catch (System.Net.WebException ex)
            {
                Console.WriteLine("Unable to download " + ex.HResult + " " + ex.Message);
                await bot.SendTextMessageAsync(update.Message.Chat.Id, "The Great & Powerful Trixie got bored while waiting for that to download.  Try later.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR - " + ex);
            }
        }
Esempio n. 2
0
        private void Bot_OnMessage(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            var count = Bot.GetChatMembersCountAsync("CyberneticCodeCom");

            if (message == null || message.Type != MessageType.Text)
            {
                return;
            }

            if (message.Text.Contains("/start"))
            {
                string Str = "Start Recived...";
                Bot.SendTextMessageAsync(message.Chat.Id, Str);
            }
            else if (message.Text.Contains("/Stop"))
            {
                string Str = "Stop Recived...";
                Bot.SendTextMessageAsync(message.Chat.Id, Str);
            }
            else
            {
                Bot.SendTextMessageAsync(message.Chat.Id, message.Chat.Id.ToString());
            }
        }
Esempio n. 3
0
        public static async void ReceiveMessage()
        {
            int checkname     = 0;
            var lastMessageId = 0;

            while (true)
            {
                var messages = await Bot.GetUpdatesAsync();

                if (messages.Length > 0)
                {
                    var last = messages[messages.Length - 1];
                    if (lastMessageId != last.Id)
                    {
                        lastMessageId = last.Id;
                        Console.WriteLine(last.Message.Text);
                        switch (last.Message.Text.ToLower().Trim())
                        {
                        case "/start":
                        case "hi":
                        case "hello":
                        {
                            Console.WriteLine("Получено сообщение!");
                            await Bot.SendTextMessageAsync(last.Message.From.Id, BotAnswers.SendFirstMessage());

                            break;
                        }

                        case "/info":
                        {
                            await Bot.SendTextMessageAsync(last.Message.From.Id, BotAnswers.CommandsInfo());

                            break;
                        }

                        case "/createnote":
                        {
                            await Bot.SendTextMessageAsync(last.Message.From.Id, BotAnswers.InsertNoteName());

                            break;
                        }
                        }

                        /*if (checkname == 0 && last.Message.Text.Contains("/start"))
                         * {
                         * await Bot.SendTextMessageAsync(last.Message.From.Id, "Hello! How can I call you?");
                         * checkname = 1;
                         * }
                         * if (checkname == 1)
                         * {
                         *  await Bot.SendTextMessageAsync(last.Message.From.Id, "Nice to meet you, {0}! My name is RemindBookBot.",);
                         * }*/
                    }
                }
                if (checkname == 0)
                {
                    Thread.Sleep(200);
                }
            }
        }
Esempio n. 4
0
        private void SendResponse(HashSet <long> receivers, KidsNoteNotification notification)
        {
            bool imagesAsAttachment = SendImagesAsAttachment();

            foreach (var eachContent in notification.Contents)
            {
                // 본문 발송.
                string text = eachContent.FormatContent();

                List <Task <Message> > taskList = new List <Task <Message> >();
                foreach (var user in receivers)
                {
                    if (user != 0)
                    {
                        taskList.Add(TheClient.SendTextMessageAsync(user, text));
                    }
                }

                // 메시지 순서가 섞이지 않도록 모두 보내질 때까지 대기.
                foreach (var task in taskList)
                {
                    try
                    {
                        task.Wait();
                    }
                    catch (Exception)
                    {
                    }
                }

                //Dictionary<long, LinkedList<InputMediaPhoto>> photoAlbumPerUser = new Dictionary<long, LinkedList<InputMediaPhoto>>();

                bool hasAttachment = eachContent.Attachments != null && eachContent.Attachments.Count > 0;

                if (hasAttachment)
                {
                    if (imagesAsAttachment)
                    {
                        SendImageAttachments(receivers, eachContent);
                    }
                    else
                    {
                        SendImageLinks(receivers, eachContent);
                    }

                    SendVideoLinks(receivers, eachContent);
                }
            }

            AllNotificationsSent(notification);
        }
Esempio n. 5
0
        private static async void BotOnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            Bot.Types.Message msg = e.Message;

            if (msg == null)
            {
                return;
            }

            if (msg.Type == Bot.Types.Enums.MessageType.TextMessage)
            {
                AIMLbot.Bot AI = new AIMLbot.Bot();

                AI.loadSettings(); // This loads the settings from the config folder

                AI.loadAIMLFromFiles();

                AIMLbot.User me_aiml = new AIMLbot.User("dd", AI);

                Request r   = new Request(msg.Text, me_aiml, AI);
                Result  res = AI.Chat(r);
                string  s   = res.ToString();
                await bot.SendTextMessageAsync(msg.Chat.Id, s);
            }

            //if (msg.Type == Bot.Types.Enums.MessageType.TextMessage)
            //{
            //    //await bot.SendTextMessageAsync(msg.Chat.Id, "Здарова " + msg.From.FirstName
            //}
        }
Esempio n. 6
0
        async Task sendTelegramUpdateBets(Telegram.Bot.TelegramBotClient Bot, ApplicationUser user)
        {
            if (user.TelegramChatId > 0)
            {
                //var Bot = new Telegram.Bot.TelegramBotClient(key);
                //await Bot.SetWebhookAsync("");
                //string telegramUserName = user.TelegramUserName;
                string   text         = "Нужно сделать ставки: ";
                DateTime now          = DateTime.UtcNow + utcMoscowShift;
                DateTime later        = now + TimeSpan.FromMinutes(120);
                bool     timeToRemind = false;
                //List<string> bets2send = new List<string>();
                //List<Bet> burningBets = db.Bets.Where(b => b.ApplicationUser == user & b.BetSTIplus == 0 & !b.IsLocked).ToList();
                List <Bet> bets2send = new List <Bet>();
                foreach (Bet b in allbets)
                {
                    if (b.ApplicationUser.TelegramUserName == user.TelegramUserName & b.Program.TimeStart >= now & b.Program.TvDate == now.Date)
                    {
                        //string betDescription = b.Program.ProgTitle + "(" + b.Program.TimeStart.ToString("HH:mm") + ") " + b.Program.ChannelCode;
                        //bets2send.Add(betDescription);
                        bets2send.Add(b);
                        if (b.Program.TimeStart < later)
                        {
                            timeToRemind = true;
                        }
                    }
                }

                InlineKeyboardMarkup kb = createKeabordFromBets(bets2send, true);
                if (timeToRemind)
                {
                    await Bot.SendTextMessageAsync(chatId : user.TelegramChatId, text : text, replyMarkup : kb);
                }
            }
        }
Esempio n. 7
0
        public override async void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as string;

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                await Bot.SetWebhookAsync("");

                int offset = 0;

                while (true)
                {
                    var updates = await Bot.GetUpdatesAsync(offset);

                    foreach (var v in updates)
                    {
                        var message = v.Message;
                        if (message == null)
                        {
                            return;
                        }

                        int idCurrentUser = dataBase.IdCurrentUser(message.From.Id);

                        if (idCurrentUser == 0)                                                                              //если ID не найден, то создаем и добавляем нового клиента и присваиваем ему индек последнего объекта
                        {
                            dataBase.AddUser(message.From.Id.ToString(), message.Chat.Id.ToString(), OperatingMode.AddGoal); //add new user
                            await Bot.SendTextMessageAsync(message.Chat.Id, "Приветствуем Вас.\nВведите от 3 до 15 целей, которые необходимо достичь.", replyMarkup : KeyBoard());
                        }
                        else
                        {
                            IUser user = new User(dataBase, idCurrentUser, message, dataBase.GetUserMod(idCurrentUser));
                            await Bot.SendTextMessageAsync(message.Chat.Id, (user.Message = message).Text, replyMarkup : KeyBoard());
                        }

                        offset = v.Id + 1;
                    }
                }
            }

            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 8
0
 public async Task SendNotificationsForCarsAsync(IList <Car> cars, IList <Url> urls)
 {
     foreach (var car in cars)
     {
         var text = FormatMessage(car, urls.FirstOrDefault(x => x.Id == car.UrlId).Address);
         var t    = await _bot.SendTextMessageAsync(new Telegram.Bot.Types.ChatId(_chatId), text, ParseMode.Html);
     }
 }
Esempio n. 9
0
 public async Task SendTextMessageAsync(BotChat chat, string message, MessageParseMode parseMode = MessageParseMode.Default)
 {
     if (!_active)
     {
         return;
     }
     await _bot.SendTextMessageAsync(chat.Id.ParseTo <long>(-1), message,
                                     disableWebPagePreview : DisableWebPagePreview,
                                     parseMode : (TBot.Types.Enums.ParseMode)parseMode).ConfigureAwait(false);
 }
Esempio n. 10
0
        static void Main(string[] args)
        {
            // 透過SendTextMessageAsync來傳送訊息,傳入chanelid及要傳送的訊息
            //chanelId test
            Bot.SendTextMessageAsync(chanelId, "每5秒傳送一個訊息");
            Bot.SendTextMessageAsync(chanelId, "Mickey Mouse");

            var me = Bot.GetMeAsync().Result;

            Console.Title        = me.Username;
            Bot.OnMessage       += BotOnMessageEcho;
            Bot.OnMessageEdited += BotOnMessageEcho;

            /* Bot.OnCallbackQuery += BotOnCallbackQueryReceived;
             * Bot.OnReceiveError += BotOnReceiveError;*/
            Bot.StartReceiving(Array.Empty <UpdateType>());
            Console.WriteLine($"Start listening for @cutebaby0630_Bot");
            Console.ReadLine();
            Bot.StopReceiving();
        }
Esempio n. 11
0
 public async Task sendMessage(string destID, string text)
 {
     try
     {
         var bot = new Telegram.Bot.TelegramBotClient("--TOKEN--");
         await bot.SendTextMessageAsync(destID, text);
     }
     catch (Exception e)
     {
         Console.WriteLine("err");
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Bot's work process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void backgroundWorkerProcess_DoWorkAsync(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as string; // получаем ключ из аргументов

            try
            {
                var webProxy = new WebProxy("198.199.91.20:3128", true);
                var Bot      = new Telegram.Bot.TelegramBotClient(key, webProxy);
                await Bot.SetWebhookAsync(""); //USE VPN

                int offset = 0;                // отступ по сообщениям
                while (true)
                {
                    var updates = await Bot.GetUpdatesAsync(offset);

                    foreach (var update in updates)
                    {
                        var message = update.Message;

                        /*
                         * Test message
                         * if (message.Text == "/saysomething")
                         * {
                         *   // в ответ на команду /saysomething выводим сообщение
                         *   await Bot.SendTextMessageAsync(message.Chat.Id, "тест",
                         *          replyToMessageId: message.MessageId);
                         * }
                         */

                        if (message.Text == "/random")
                        {
                            string   pageText = AnekdotParsing.LoadPage(randomAnekdotPage);
                            string[] data     = AnekdotParsing.ParseData(pageText);

                            string reply = string.Empty;
                            foreach (string str in data)
                            {
                                reply += str + "\n";
                            }

                            await Bot.SendTextMessageAsync(message.Chat.Id, reply);
                        }

                        offset = update.Id + 1;
                    }
                }
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Esempio n. 13
0
 //destID: destination ID
 //text: text to send
 public async Task sendMessage(string destID, string text)
 {
     // destID = chatId;
     // string apiToken = "775672851:AAEUjIvm-Vc4ZWIWmvfUffK5Rh4fLIP2jDE";
     try
     {
         var bot = new Telegram.Bot.TelegramBotClient(apiToken);
         await bot.SendTextMessageAsync(destID, text);
     }
     catch (Exception e)
     {
         Console.WriteLine("err");
     }
 }
Esempio n. 14
0
        public static async void MainMenu(Models.ObjectsModels.User user, TelegramContext db, Message message, Telegram.Bot.TelegramBotClient botClient)
        {
            var keyboard = new InlineKeyboardMarkup(
                new InlineKeyboardButton[]
            {
                new InlineKeyboardButton {
                    Text = "Нова будівля", CallbackData = "AddBuilding"
                }
            }
                );

            var mess = await botClient.SendTextMessageAsync(message.Chat.Id, "Привіт, " + message.Chat.FirstName +
                                                            "! \n\nЦей бот створений для для того, щоб ми якомога швидше могли шукати будівлі. яким потрібна наша допомога. " +
                                                            "\n\nШвидше тисни кнопку, та рятуй прекрасне місто!🦄", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);
        }
Esempio n. 15
0
        private void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.TextMessage && message.Chat.Id != ChatId)
            {
                return;
            }

            if (message.Text.StartsWith("/cookie"))
            {
                _stream.Publish(new NewAuthCookie()
                {
                    Value = message.Text.Replace("/cookie ", string.Empty)
                });
            }
            else
            {
                var usage = @"Usage:
                    ///cookie <cookie value>   - send cookie";

                _bot.SendTextMessageAsync(message.Chat.Id, usage);
            }
        }
Esempio n. 16
0
        public static async void MainMenu(Message message, Telegram.Bot.TelegramBotClient botClient)
        {
            var keyboard = new InlineKeyboardMarkup(
                new InlineKeyboardButton[]
            {
                new InlineKeyboardButton {
                    Text = "Условия", CallbackData = "ShowPrice"
                }
            }
                );

            var mess = await botClient.SendTextMessageAsync(message.Chat.Id, $"Здравствуйте, {message.Chat.FirstName} !\n\nЕсли вы хотите выставить вакансию, " +
                                                            $"будет необходимо следовать инструкциям бота и отвечать на них.  Старайтесь писать кратко и по делу, донося основную суть задачи или проекта.\n\n" +
                                                            $"<b>❌ Не ставьте собственные пунктиры «-, –, • и т.д.»</b>",
                                                            Telegram.Bot.Types.Enums.ParseMode.Html, false, false, 0, keyboard);

            StateManager.SetLastMessage(botClient, (int)message.Chat.Id, mess.MessageId);
        }
Esempio n. 17
0
        private async void BotOnMessageReceived(object sender, MessageEventArgs e)
        {
            String Answer = "";

            if (e.Message == null)
            {
                return;
            }
            switch (e.Message.Text)
            {
            case "/start": Answer = "/stone - твой камень\r\n/scissors - твои ножницы\r\n/paper - твоя бумага\r\n/baba - показать смачную бабу"; break;

            case "/help": Answer = "А у меня бумага - ты проиграл"; break;

            case "/scissors": Answer = "А у меня камень - ты проиграл"; break;

            case "/paper": Answer = "А у меня ножницы - ты проиграл"; break;

            case "/baba": Answer = "Вот тебе баба - "; break;

            default: Answer = "Не знаю такой команды"; break;
            }
            //e.Message.Text = Answer;
            //listBox1.Items.Add($"Received a text message in chat {e.Message.Chat.Id}.");

            Action action = () => listBox1.Items.Add("Received message");

            Invoke(action);
            await BOT.SendTextMessageAsync(chatId : e.Message.Chat, text : "" + Answer);

            //listadd(Convert.ToInt32(e.Message.Chat.Id),Answer);

            new ListBox();
            //var sync = WindowsFormsSynchronizationContext.Current;
            //sync.Post(
            //    delegate
            //    {
            //        listBox1.Items.Add("Received message");
            //    },
            //    null);

            // Telegram.Bot.Types.Message msg = new Telegram.Bot.Types.Message();
        }
Esempio n. 18
0
        public async Task SendMessageToChannel(Media item, string channelName)
        {
            try
            {
                var Bot = new TB.TelegramBotClient(BOT_API);
                var hashtag = !string.IsNullOrEmpty(item.User.Name) ? "🖼 " + item.User.Name.ToHashtag() : "";
                var name = $"{item.User.Name} ({item.User.Username})</b>";
                //var ad = "⚽️🎼🎭\r\n<i>جدیدترین عکس‌ها و اخبار از محبوب‌ترین چهره‌های ایرانی در کانال اینستاچهره  </i> 👇\r\n  https://telegram.me/joinchat/BFGINT2hHdPVzqGfj43k1Q";
                var ad = "⚽️🎼🎭<i>داغ‌ترین عکس‌ها از هنرمندان و ورزشکاران ایرانی  </i> 👇\r\n https://telegram.me/joinchat/BFGINT2hHdPVzqGfj43k1Q   @InstaHonar    @InstaVarzesh1";
                var link = $"<a href='{item.InstaStandardResolution}'>{item.InstaCreatedTime.ToShamsi()}</a>";
                var instaLink = $"<a href='{item.InstaLink}'>اینستاگرام</a>";

                await Bot.SendTextMessageAsync(channelName, $"{hashtag} [{link}]\r\n{item.Caption}\r\n\r\n{ad}", false, true, 0, null, TB.Types.Enums.ParseMode.Html);
                MarkAsSent(item);
            }
            catch (Exception ex)
            {
                //TODO
            }
        }
Esempio n. 19
0
 public async Task Execute(TGTypes.Message message, TGBot.TelegramBotClient botClient)
 {
     var chatId = message.Chat.Id;
     await botClient.SendTextMessageAsync(chatId, "Hallo I'm Pubg Stats Bot", parseMode : TGTypes.Enums.ParseMode.Markdown);
 }
Esempio n. 20
0
        private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String;

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                Bot.SetWebhookAsync("").Wait();

                int offset = 0;
                int stageM = 0;
                while (true)
                {
                    var updates = await Bot.GetUpdatesAsync(offset);

                    foreach (var update in updates)
                    {
                        var message = update.Message;
                        stageM = 0;
                        int index = -1;
                        for (int i = 0; i < persons.Count; i++)
                        {
                            if (persons[i].userid == message.From.Id)
                            {
                                index = i;
                                break;
                            }
                        }
                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                        {
                            if (message.Text == "/reset" && index >= 0)
                            {
                                persons.RemoveAt(index);
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Ваш профиль очищен.");
                            }
                            else if (message.Text == "/reset")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Профиль чист.");
                            }
                            else
                            {
                                if (index >= 0)
                                {
                                    stageM = persons[index].stage;
                                }
                                else
                                {
                                    persons.Add(new Person
                                    {
                                        FirstName   = message.From.FirstName,
                                        SecondName  = message.From.LastName,
                                        gender      = 0,
                                        temperament = "",
                                        bd          = 0,
                                        bm          = 0,
                                        by          = 0,
                                        userid      = message.From.Id,
                                        stage       = 0
                                    });
                                    index  = persons.Count - 1;
                                    stageM = 0;
                                }
                                switch (stageM)
                                {
                                case 0:
                                    Telegram.Bot.Types.FileToSend file = new Telegram.Bot.Types.FileToSend();
                                    file.Content  = File.Open("hello.jpg", FileMode.Open);
                                    file.Filename = "hello.jpg";
                                    await Bot.SendPhotoAsync(message.Chat.Id, file);

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Привет, " + message.From.FirstName + "!\nЯ Миша.\nЯ постараюсь быть тебе другом.\nРасскажи немного о себе😊");

                                    var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                                    {
                                        Keyboard = new[] {
                                            new[]     // row 1
                                            {
                                                new Telegram.Bot.Types.KeyboardButton("👨Мужской"),
                                                new Telegram.Bot.Types.KeyboardButton("👱‍♀Женский")
                                            },
                                        },
                                        ResizeKeyboard  = true,
                                        OneTimeKeyboard = true
                                    };

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Укажи свой пол", ParseMode.Default, false, false, 0, keyboard);

                                    stageM++;
                                    break;

                                case 1:
                                    if (message.Text == "👨Мужской")
                                    {
                                        persons[index].gender = 1;
                                    }
                                    else if (message.Text == "👱‍♀Женский")
                                    {
                                        persons[index].gender = 2;
                                    }
                                    else
                                    {
                                        stageM--;
                                        break;
                                    }
                                    var keyboard1 = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                                    {
                                        Keyboard = new[] {
                                            new[]     // row 1
                                            {
                                                new Telegram.Bot.Types.KeyboardButton("👍Хорошо"),
                                                new Telegram.Bot.Types.KeyboardButton("😞Плохо"),
                                                new Telegram.Bot.Types.KeyboardButton("😐Не очень")
                                            },
                                        },
                                        ResizeKeyboard  = true,
                                        OneTimeKeyboard = true
                                    };

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Как прошел твой день?", ParseMode.Default, false, false, 0, keyboard1);

                                    stageM++;
                                    break;

                                case 2:
                                    bool   inGame        = false;
                                    int    indexgame     = -1;
                                    int    indexGamer    = 0;
                                    string pathGamePhoto = "";
                                    for (int i = 0; i < gamesphoto.Count; i++)
                                    {
                                        if (gamesphoto[i].user1 == message.From.Id ||
                                            gamesphoto[i].user2 == message.From.Id ||
                                            gamesphoto[i].user3 == message.From.Id ||
                                            gamesphoto[i].user4 == message.From.Id)
                                        {
                                            inGame    = true;
                                            indexgame = i;
                                        }
                                    }
                                    if (!inGame)
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Я понял. Давай сыграем в игру, где надо будет собрать части картинки в одну. Я отправлю картинки всем в твоей команде и ты должен найти недостающие части.");
                                    }
                                    else if (gamesphoto[indexgame].count == 4)
                                    {
                                        if (message.Text.ToLower() == "кот" || message.Text.ToLower() == "котик" || message.Text.ToLower() == "кошка")
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Правильно!");

                                            var keyboard6 = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                                            {
                                                Keyboard = new[] {
                                                    new[] // row 1
                                                    {
                                                        new Telegram.Bot.Types.KeyboardButton("Учился в школе"),
                                                        new Telegram.Bot.Types.KeyboardButton("Гуляли с друзьями"),
                                                        new Telegram.Bot.Types.KeyboardButton("Справляли день рождения"),
                                                        new Telegram.Bot.Types.KeyboardButton("Ничего")
                                                    },
                                                },
                                                ResizeKeyboard  = true,
                                                OneTimeKeyboard = true
                                            };

                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Что запомнилось тебе за этот день?", ParseMode.Default, false, false, 0, keyboard6);

                                            stageM++;
                                            break;
                                        }
                                        else
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Подумай еще!😊");

                                            break;
                                        }
                                    }
                                    if (!inGame)
                                    {
                                        for (int i = 0; i < gamesphoto.Count; i++)
                                        {
                                            if (gamesphoto[i].count != 4)
                                            {
                                                if (gamesphoto[i].user1 == -1)
                                                {
                                                    gamesphoto[i].chatID1 = message.Chat.Id;
                                                    gamesphoto[i].user1   = message.From.Id;
                                                    pathGamePhoto         = gamesphoto[i].firstPath;
                                                }

                                                else if (gamesphoto[i].user2 == -1)
                                                {
                                                    indexGamer            = 1;
                                                    gamesphoto[i].chatID2 = message.Chat.Id;
                                                    gamesphoto[i].user2   = message.From.Id;
                                                    pathGamePhoto         = gamesphoto[i].secondPath;
                                                }
                                                else if (gamesphoto[i].user3 == -1)
                                                {
                                                    indexGamer            = 2;
                                                    gamesphoto[i].chatID3 = message.Chat.Id;
                                                    gamesphoto[i].user3   = message.From.Id;
                                                    pathGamePhoto         = gamesphoto[i].thirdPath;
                                                }
                                                else if (gamesphoto[i].user4 == -1)
                                                {
                                                    indexGamer            = 3;
                                                    gamesphoto[i].chatID4 = message.Chat.Id;
                                                    gamesphoto[i].user4   = message.From.Id;
                                                    pathGamePhoto         = gamesphoto[i].fourPath;
                                                }
                                                inGame    = true;
                                                indexgame = i;
                                                gamesphoto[indexgame].count++;
                                                if (gamesphoto[indexgame].count == 4)
                                                {
                                                    Telegram.Bot.Types.FileToSend file1 = new Telegram.Bot.Types.FileToSend();
                                                    file1.Content  = File.Open(gamesphoto[indexgame].firstPath, FileMode.Open);
                                                    file1.Filename = gamesphoto[indexgame].firstPath;
                                                    await Bot.SendPhotoAsync(gamesphoto[indexgame].chatID1, file1);

                                                    await Bot.SendTextMessageAsync(gamesphoto[indexgame].chatID1, "Найди другие части картинки и скажи что на картинке. Удачи!😊");

                                                    file1.Content  = File.Open(gamesphoto[indexgame].secondPath, FileMode.Open);
                                                    file1.Filename = gamesphoto[indexgame].secondPath;
                                                    await Bot.SendPhotoAsync(gamesphoto[indexgame].chatID2, file1);

                                                    await Bot.SendTextMessageAsync(gamesphoto[indexgame].chatID2, "Найди другие части картинки и скажи что на картинке. Удачи!😊");

                                                    file1.Content  = File.Open(gamesphoto[indexgame].thirdPath, FileMode.Open);
                                                    file1.Filename = gamesphoto[indexgame].thirdPath;
                                                    await Bot.SendPhotoAsync(gamesphoto[indexgame].chatID3, file1);

                                                    await Bot.SendTextMessageAsync(gamesphoto[indexgame].chatID3, "Найди другие части картинки и скажи что на картинке. Удачи!😊");

                                                    file1.Content  = File.Open(gamesphoto[indexgame].fourPath, FileMode.Open);
                                                    file1.Filename = gamesphoto[indexgame].fourPath;
                                                    await Bot.SendPhotoAsync(gamesphoto[indexgame].chatID4, file1);

                                                    await Bot.SendTextMessageAsync(gamesphoto[indexgame].chatID4, "Найди другие части картинки и скажи что на картинке. Удачи!😊");


                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!inGame)
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Игр пока нет😊");
                                    }
                                    else
                                    {
                                        if (gamesphoto[indexgame].count != 4)
                                        {
                                            await Bot.SendTextMessageAsync(message.Chat.Id, "Подожди немного, я поищу тебе команду😊");
                                        }
                                    }
                                    break;

                                case 3:
                                    persons[index].answer2 = message.Text;
                                    var keyboard3 = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                                    {
                                        Keyboard = new[] {
                                            new[]     // row 1
                                            {
                                                new Telegram.Bot.Types.KeyboardButton("Да"),
                                                new Telegram.Bot.Types.KeyboardButton("Нет"),
                                            },
                                        },
                                        ResizeKeyboard  = true,
                                        OneTimeKeyboard = true
                                    };

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Понравилось ли тебе сегодняшнее задание?", ParseMode.Default, false, false, 0, keyboard3);

                                    stageM++;
                                    break;

                                case 4:
                                    persons[index].answer3 = message.Text;

                                    await Bot.SendTextMessageAsync(message.Chat.Id, "Какое задание ты сегодня выполнял?");

                                    stageM++;
                                    break;

                                case 5:
                                    persons[index].answer4 = message.Text;
                                    var keyboard5 = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                                    {
                                        Keyboard = new[] {
                                            new[]     // row 1
                                            {
                                                new Telegram.Bot.Types.KeyboardButton("Да"),
                                                new Telegram.Bot.Types.KeyboardButton("Нет"),
                                            },
                                        },
                                        ResizeKeyboard  = true,
                                        OneTimeKeyboard = true
                                    };
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "У тебя есть чем поделиться со мной?", ParseMode.Default, false, false, 0, keyboard5);

                                    stageM++;
                                    break;

                                case 6:
                                    if (message.Text.ToLower() == "нет")
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "До завтра!");
                                    }
                                    else if (message.Text.ToLower() == "да")
                                    {
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Излагай свои мысли");
                                    }
                                    stageM++;
                                    break;

                                case 7:
                                    persons[index].answer5 += message.Text + Environment.NewLine;
                                    break;
                                }
                                ;
                                persons[index].stage = stageM;
                            }
                            offset = update.Id + 1;
                        }
                    }
                }
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 21
0
        private void ClientThreadHandle(object clientNo)
        {
            while (true)
            {
                try
                {
                    var      conString             = "mongodb://localhost:27017";
                    var      Client                = new MongoClient(conString);
                    var      DB                    = Client.GetDatabase("SatelliteDB");
                    var      collectionControlTime = DB.GetCollection <getDataControlTime>("ControlTime");
                    var      data                  = collectionControlTime.AsQueryable <getDataControlTime>().ToList();
                    var      controlAZEL           = (data[0].control).AsQueryable <control>().ToArray();
                    var      startdate             = data[0].timestart;
                    var      enddate               = data[0].timestop;
                    DateTime startdate2            = DateTime.ParseExact(startdate, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                    Console.WriteLine("startdate2 = " + startdate2);
                    var      Datetemp  = DateTime.Now.ToString("M/d/yyyy h:mm:ss tt", new CultureInfo("en-US"));
                    DateTime localDate = DateTime.ParseExact(Datetemp, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

                    long checkStart     = ((DateTimeOffset)startdate2).ToUnixTimeSeconds();
                    long checkLocalDate = ((DateTimeOffset)localDate).ToUnixTimeSeconds();
                    Console.WriteLine("checkStart = " + checkStart);
                    Console.WriteLine("checkLocalDate = " + checkLocalDate);
                    Console.WriteLine("operater = " + (checkStart - checkLocalDate)); // ได้ผลลัพท์เป็นวิ
                    if ((checkStart - checkLocalDate) < 0)
                    {
                        int           myID         = (int)clientNo;
                        byte[]        message      = new byte[4096];
                        String        txtmsg       = "";
                        String        txtresult    = "";
                        TcpClient     tcpClient    = Global.getTcpClient(myID);
                        NetworkStream clientStream = tcpClient.GetStream();
                        conString = "mongodb://localhost:27017";
                        Client    = new MongoClient(conString);
                        DB        = Client.GetDatabase("SatelliteDB");
                        var    collectionconfigAZEL = DB.GetCollection <getAzEl>("configAZEL");
                        var    dataAZEL             = collectionconfigAZEL.AsQueryable <getAzEl>().ToArray();
                        String AZ        = dataAZEL[0].azimuth;
                        String El        = dataAZEL[0].elevation;
                        int    bytesRead = 0;

                        try
                        {
                            //blocks until a client sends a message
                            bytesRead = clientStream.Read(message, 0, 4096);
                            //bytesRead = ssock.Receive(message, message.Length, 0);
                        }
                        catch
                        {
                            //a socket error has occured
                            break;
                        }

                        if (bytesRead == 0)
                        {
                            //the client has disconnected from the server
                            break;
                        }
                        String hello = "AZ=" + AZ + "," + "EL=" + El + "\r\n";
                        SetText(hello);
                        byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                        clientStream.Write(helloByte, 0, hello.Length);
                        //message has successfully been received
                        ASCIIEncoding encoder = new ASCIIEncoding();
                        String        txtdata = encoder.GetString(message, 0, bytesRead);
                        SetText("String :" + txtdata);

                        /*             if (txtdata.Contains('\r') || txtdata.Contains('\n'))
                         *             {
                         *                 int pos, pos2;
                         *                 if (txtdata.Contains('\r'))
                         *                 {
                         *                     //end with \r, windows style
                         *                     pos = txtdata.IndexOf('\r');
                         *                 }
                         *                 else
                         *                 {
                         *                     //end with \n, unix style
                         *                     pos = txtdata.IndexOf('\n');
                         *                 }
                         *                 txtmsg += txtdata.Substring(0, pos); */
                        txtmsg    = txtdata;
                        txtresult = txtmsg;

                        /*                   pos = txtdata.IndexOf("\r\n");
                         *                 pos2 = txtdata.IndexOf("\n\n");
                         *                 if (pos >= 0 || pos2 > 0) pos = pos + 1;
                         *                 txtmsg = txtdata.Substring(pos + 1);*/
                        SetText("Result String :" + txtresult);
                        //if (txtresult == "#exit") finished = true;

                        //forward to all
                        SendAllClient(myID + ":" + txtresult);
                    }
                    else if ((checkStart - checkLocalDate) < 60 * 3) //เช็คว่าเกิน 3 นาทีไหม
                    {
                        var text = "เหลือเวลาอีก 3 นาทีจะถึงเวลารับสัญญาณดาวเทียม " + (data[0].namesatellite);
                        var bot  = new Telegram.Bot.TelegramBotClient("572794128:AAGve89M6IRZc3-H5fBWgU66lMTFuPxg49c");
                        bot.SendTextMessageAsync(-272664117, text);
                        var requestLine  = (HttpWebRequest)WebRequest.Create("https://notify-api.line.me/api/notify");
                        var postDataLine = string.Format("message={0}", text);
                        var dataLine     = Encoding.UTF8.GetBytes(postDataLine);

                        requestLine.Method        = "POST";
                        requestLine.ContentType   = "application/x-www-form-urlencoded";
                        requestLine.ContentLength = dataLine.Length;
                        requestLine.Headers.Add("Authorization", "Bearer 7NobgAnQVINIPDXBDpfKqs8JOP4nO07vu6VJ3OfSuyh");

                        using (var stream = requestLine.GetRequestStream())
                        {
                            stream.Write(dataLine, 0, dataLine.Length);
                        }

                        var responseline       = (HttpWebResponse)requestLine.GetResponse();
                        var responseStringline = new StreamReader(responseline.GetResponseStream()).ReadToEnd();

                        int           myID         = (int)clientNo;
                        TcpClient     tcpClient    = Global.getTcpClient(myID);
                        NetworkStream clientStream = tcpClient.GetStream();
                        conString             = "mongodb://localhost:27017";
                        Client                = new MongoClient(conString);
                        DB                    = Client.GetDatabase("SatelliteDB");
                        collectionControlTime = DB.GetCollection <getDataControlTime>("ControlTime");

                        data        = collectionControlTime.AsQueryable <getDataControlTime>().ToList();
                        controlAZEL = (data[0].control).AsQueryable <control>().ToArray();

                        //send hello first

                        /*            String hello = "AZ=" + AZ + "EL=" + El +"\r\n";
                         *          byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                         *          clientStream.Write(helloByte, 0, hello.Length);*/
                        //ssock.Send(helloByte, hello.Length, SocketFlags.None);

                        byte[] message   = new byte[4096];
                        String txtmsg    = "";
                        String txtresult = "";
                        int    bytesRead;
                        //bool finished = false;
                        startdate = data[0].timestart;
                        enddate   = data[0].timestop;
                        Console.WriteLine("startdate = " + startdate);
                        Console.WriteLine("enddate = " + enddate);
                        // DateTime localDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sszzz");
                        startdate2 = DateTime.ParseExact(startdate, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                        DateTime enddate2 = DateTime.ParseExact(enddate, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                        // DateTime localDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:sszzz");
                        Datetemp = DateTime.Now.ToString("M/d/yyyy h:mm:ss tt", new CultureInfo("en-US"));

                        //Console.WriteLine("typeof : " + startdate2.GetType());
                        localDate = DateTime.ParseExact(Datetemp, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

                        /* Console.WriteLine("typeof : " + startdate2.GetType());
                         * Console.WriteLine("typeof : " + localDate.GetType());
                         */
                        var i = 0;
                        while (localDate <= enddate2)
                        {
                            int total = 0;
                            if (startdate2.Minute > localDate.Minute && startdate2.Second > localDate.Second)
                            {
                                total = 60 * (60 - startdate2.Minute + localDate.Minute) + (localDate.Second + (60 - startdate2.Second));
                            }
                            else if (startdate2.Minute > localDate.Minute)
                            {
                                total = 60 * (60 - startdate2.Minute + localDate.Minute) + (localDate.Second - startdate2.Second);
                            }

                            /*else if (startdate2.Second > localDate.Second)
                             * {
                             *  total = 60 * (localDate.Minute - startdate2.Minute) + (localDate.Second + (60 - startdate2.Second));
                             * }*/
                            else
                            {
                                total = 60 * (localDate.Minute - startdate2.Minute) + (localDate.Second - startdate2.Second);
                            }
                            SetText(total.ToString());
                            if (localDate >= startdate2)
                            {
                                bytesRead = 0;

                                try
                                {
                                    //blocks until a client sends a message
                                    bytesRead = clientStream.Read(message, 0, 4096);
                                    //bytesRead = ssock.Receive(message, message.Length, 0);
                                }
                                catch
                                {
                                    //a socket error has occured
                                    break;
                                }

                                if (bytesRead == 0)
                                {
                                    //the client has disconnected from the server
                                    break;
                                }
                                String AZ        = controlAZEL[total].azimuth;
                                String El        = controlAZEL[total].elevation;
                                String hello     = Datetemp + "AZ=" + AZ + "," + "EL=" + El + "\r\n";
                                byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                                clientStream.Write(helloByte, 0, hello.Length);
                                //message has successfully been received
                                ASCIIEncoding encoder = new ASCIIEncoding();
                                String        txtdata = encoder.GetString(message, 0, bytesRead);
                                SetText("String :" + txtdata);

                                /*             if (txtdata.Contains('\r') || txtdata.Contains('\n'))
                                 *             {
                                 *                 int pos, pos2;
                                 *                 if (txtdata.Contains('\r'))
                                 *                 {
                                 *                     //end with \r, windows style
                                 *                     pos = txtdata.IndexOf('\r');
                                 *                 }
                                 *                 else
                                 *                 {
                                 *                     //end with \n, unix style
                                 *                     pos = txtdata.IndexOf('\n');
                                 *                 }
                                 *                 txtmsg += txtdata.Substring(0, pos); */
                                txtmsg    = txtdata;
                                txtresult = txtmsg;

                                /*                   pos = txtdata.IndexOf("\r\n");
                                 *                 pos2 = txtdata.IndexOf("\n\n");
                                 *                 if (pos >= 0 || pos2 > 0) pos = pos + 1;
                                 *                 txtmsg = txtdata.Substring(pos + 1);*/
                                SetText("Result String :" + txtresult);

                                //if (txtresult == "#exit") finished = true;

                                //forward to all
                                SendAllClient(myID + ":" + txtresult);
                                //SetText("Total:" + txtresult);
                                //SetText("Total:" + txtresult.Length);
                                int    j      = 0;
                                int    jj     = 1;
                                int    jjj    = 2;
                                String az_str = "";
                                String el_str = "";
                                SetText("Total:" + txtresult);
                                //SetText("Total:" + txtresult.Length);
                                while (j < txtresult.Length)
                                {
                                    char c1 = txtresult[j];
                                    char c2 = txtresult[jj];
                                    char c3 = txtresult[jjj];
                                    if (c1 == 'A')
                                    {
                                        if (c2 == 'Z')
                                        {
                                            if (c3 == '=')
                                            {
                                                int ii = j + 2;
                                                while (true)
                                                {
                                                    if (txtresult[ii + 1] == ',')
                                                    {
                                                        j = ii;
                                                        SetText("AZZ=" + az_str);
                                                        //SetText("ELL=" + el_str);
                                                        break;
                                                    }
                                                    ii     = ii + 1;
                                                    az_str = az_str + txtresult[ii];
                                                }
                                            }
                                        }
                                    }
                                    if (c1 == 'E')
                                    {
                                        jj  = j + 1;
                                        jjj = j + 2;
                                        c2  = txtresult[jj];
                                        c3  = txtresult[jjj];
                                        if (c2 == 'L')
                                        {
                                            if (c3 == '=')
                                            {
                                                int ii = j + 3;
                                                while (ii < txtresult.Length)
                                                {
                                                    j      = ii;
                                                    el_str = el_str + txtresult[ii];
                                                    ii     = ii + 1;
                                                }
                                            }
                                        }
                                    }
                                    SetText("ELL=" + el_str);
                                    j = j + 1;
                                }

                                var collectionconfigAZEL = DB.GetCollection <getAzEl>("configAZEL");
                                var data1    = collectionconfigAZEL.AsQueryable <getAzEl>().ToArray();
                                var builder2 = Builders <getAzEl> .Filter;
                                var filter2  = builder2.Eq("_id", data1[0].Id);
                                var updateAZ = Builders <getAzEl> .Update
                                               .Set("azimuth", az_str);

                                collectionconfigAZEL.UpdateOne(filter2, updateAZ, new UpdateOptions()
                                {
                                    IsUpsert = true
                                });

                                var updateEL = Builders <getAzEl> .Update
                                               .Set("elevation", el_str);

                                collectionconfigAZEL.UpdateOne(filter2, updateEL, new UpdateOptions()
                                {
                                    IsUpsert = true
                                });
                                //System.Threading.Thread.Sleep(1000);*
                                i = i + 1;
                            }
                            else
                            {
                                bytesRead = 0;

                                try
                                {
                                    //blocks until a client sends a message
                                    bytesRead = clientStream.Read(message, 0, 4096);
                                    //bytesRead = ssock.Receive(message, message.Length, 0);
                                }
                                catch
                                {
                                    //a socket error has occured
                                    break;
                                }

                                if (bytesRead == 0)
                                {
                                    //the client has disconnected from the server
                                    break;
                                }
                                String AZ        = controlAZEL[0].azimuth;
                                String El        = controlAZEL[0].elevation;
                                String hello     = Datetemp + "AZ=" + AZ + "," + "EL=" + El + "\r\n";
                                byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                                clientStream.Write(helloByte, 0, hello.Length);
                                //message has successfully been received
                                ASCIIEncoding encoder = new ASCIIEncoding();
                                String        txtdata = encoder.GetString(message, 0, bytesRead);
                                SetText("String :" + txtdata);

                                /*             if (txtdata.Contains('\r') || txtdata.Contains('\n'))
                                 *             {
                                 *                 int pos, pos2;
                                 *                 if (txtdata.Contains('\r'))
                                 *                 {
                                 *                     //end with \r, windows style
                                 *                     pos = txtdata.IndexOf('\r');
                                 *                 }
                                 *                 else
                                 *                 {
                                 *                     //end with \n, unix style
                                 *                     pos = txtdata.IndexOf('\n');
                                 *                 }
                                 *                 txtmsg += txtdata.Substring(0, pos); */
                                txtmsg    = txtdata;
                                txtresult = txtmsg;

                                /*                   pos = txtdata.IndexOf("\r\n");
                                 *                 pos2 = txtdata.IndexOf("\n\n");
                                 *                 if (pos >= 0 || pos2 > 0) pos = pos + 1;
                                 *                 txtmsg = txtdata.Substring(pos + 1);*/
                                SetText("Result String :" + txtresult);
                                //if (txtresult == "#exit") finished = true;

                                //forward to all
                                SendAllClient(myID + ":" + txtresult);

                                /*                }
                                 *              else
                                 *              {
                                 *                  txtmsg += txtdata;
                                 *              }*/
                                //System.Threading.Thread.Sleep(1000);
                            }
                            Datetemp  = DateTime.Now.ToString("M/d/yyyy h:mm:ss tt", new CultureInfo("en-US"));
                            localDate = DateTime.ParseExact(Datetemp, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
                        }
                        var collectioncontrol = DB.GetCollection <getDatacontrol>("control");

                        var tempProperty = "Y";
                        var builder      = Builders <getDatacontrol> .Filter;
                        var filter       = builder.Eq("_id", ObjectId.Parse(data[0].idControl));
                        //Console.WriteLine("AZ = " + filter);
                        var update = Builders <getDatacontrol> .Update
                                     .Set("status", tempProperty);

                        collectioncontrol.UpdateOne(filter, update, new UpdateOptions()
                        {
                            IsUpsert = true
                        });

                        collectionControlTime.DeleteOne(a => a.Id == data[0].Id);
                        //Console.WriteLine("Helllo");
                        //Console.ReadKey();
                        //form reply answer

                        /*try
                         * {
                         *  String myAnswerStr = "bye\r\n";
                         *  byte[] myAnswer = Encoding.ASCII.GetBytes(myAnswerStr);
                         *  clientStream.Write(myAnswer, 0, myAnswerStr.Length);
                         *  //ssock.Send(myAnswer, myAnswer.Length, SocketFlags.None);
                         * }
                         * catch (Exception e)
                         * {
                         *  MessageBox.Show(e.ToString());
                         * }*/

                        //tcpClient.Close();
                        //ssock.Close();
                        //SetText("Client " + myID + " closed!!");
                    }
                    else
                    {
                        int           myID         = (int)clientNo;
                        byte[]        message      = new byte[4096];
                        String        txtmsg       = "";
                        String        txtresult    = "";
                        TcpClient     tcpClient    = Global.getTcpClient(myID);
                        NetworkStream clientStream = tcpClient.GetStream();
                        conString = "mongodb://localhost:27017";
                        Client    = new MongoClient(conString);
                        DB        = Client.GetDatabase("SatelliteDB");
                        var    collectionconfigAZEL = DB.GetCollection <getAzEl>("configAZEL");
                        var    dataAZEL             = collectionconfigAZEL.AsQueryable <getAzEl>().ToArray();
                        String AZ        = dataAZEL[0].azimuth;
                        String El        = dataAZEL[0].elevation;
                        int    bytesRead = 0;

                        try
                        {
                            //blocks until a client sends a message
                            bytesRead = clientStream.Read(message, 0, 4096);
                            //bytesRead = ssock.Receive(message, message.Length, 0);
                        }
                        catch
                        {
                            //a socket error has occured
                            break;
                        }

                        if (bytesRead == 0)
                        {
                            //the client has disconnected from the server
                            break;
                        }
                        String hello     = "AZ=" + AZ + "," + "EL=" + El + "\r\n";
                        byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                        clientStream.Write(helloByte, 0, hello.Length);
                        //message has successfully been received
                        ASCIIEncoding encoder = new ASCIIEncoding();
                        String        txtdata = encoder.GetString(message, 0, bytesRead);
                        SetText("String :" + txtdata);

                        /*             if (txtdata.Contains('\r') || txtdata.Contains('\n'))
                         *             {
                         *                 int pos, pos2;
                         *                 if (txtdata.Contains('\r'))
                         *                 {
                         *                     //end with \r, windows style
                         *                     pos = txtdata.IndexOf('\r');
                         *                 }
                         *                 else
                         *                 {
                         *                     //end with \n, unix style
                         *                     pos = txtdata.IndexOf('\n');
                         *                 }
                         *                 txtmsg += txtdata.Substring(0, pos); */
                        txtmsg    = txtdata;
                        txtresult = txtmsg;

                        /*                   pos = txtdata.IndexOf("\r\n");
                         *                 pos2 = txtdata.IndexOf("\n\n");
                         *                 if (pos >= 0 || pos2 > 0) pos = pos + 1;
                         *                 txtmsg = txtdata.Substring(pos + 1);*/
                        SetText("Result String :" + txtresult);
                        //if (txtresult == "#exit") finished = true;

                        //forward to all
                        SendAllClient(myID + ":" + txtresult);
                    }
                }
                catch (Exception)
                {
                    int           myID                 = (int)clientNo;
                    byte[]        message              = new byte[4096];
                    String        txtmsg               = "";
                    String        txtresult            = "";
                    TcpClient     tcpClient            = Global.getTcpClient(myID);
                    NetworkStream clientStream1        = tcpClient.GetStream();
                    var           conString            = "mongodb://localhost:27017";
                    var           Client               = new MongoClient(conString);
                    var           DB                   = Client.GetDatabase("SatelliteDB");
                    var           collectionconfigAZEL = DB.GetCollection <getAzEl>("configAZEL");
                    var           dataAZEL             = collectionconfigAZEL.AsQueryable <getAzEl> .ToArray();

                    String AZ        = dataAZEL[0].azimuth;
                    String El        = dataAZEL[0].elevation;
                    int    bytesRead = 0;

                    try
                    {
                        //blocks until a client sends a message
                        bytesRead = clientStream1.Read(message, 0, 4096);
                        //bytesRead = ssock.Receive(message, message.Length, 0);
                    }
                    catch
                    {
                        //a socket error has occured
                        break;
                    }

                    if (bytesRead == 0)
                    {
                        //the client has disconnected from the server
                        break;
                    }
                    String hello = "AZ=" + AZ + "," + "EL=" + El + "\r\n";
                    SetText(hello);
                    byte[] helloByte = Encoding.ASCII.GetBytes(hello);
                    clientStream1.Write(helloByte, 0, hello.Length);
                    //message has successfully been received
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    String        txtdata = encoder.GetString(message, 0, bytesRead);
                    SetText("String :" + txtdata);

                    txtmsg    = txtdata;
                    txtresult = txtmsg;

                    SetText("Result String :" + txtresult);
                    //if (txtresult == "#exit") finished = true;

                    //forward to all
                    SendAllClient(myID + ":" + txtresult);
                }
            }
        }
Esempio n. 22
0
 public override bool SendMessage(Chat chat, string message)
 {
     TClient.SendTextMessageAsync((long)chat.TelegramId(), message);
     return(true);
 }
Esempio n. 23
0
        private async void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            secondsElapsed += 1;
            DateTime now = DateTime.UtcNow + utcMoscowShift;

            if (secondsElapsed == 60 * 60)
            {
                foreach (ApplicationUser user in users)
                {
                    if (user.TelegramChatId > 0)
                    {
                        await sendTelegramUpdateBets(Bot, user);
                    }
                }
                allbets        = db.Bets.Where(b => b.BetSTIplus == 0 & !b.IsLocked).ToList();
                secondsElapsed = 0;
            }

            if ((secondsElapsed == 15 * 60) | (secondsElapsed == 30 * 60) | (secondsElapsed == 30 * 60))
            {
                allbets = db.Bets.Where(b => b.BetSTIplus == 0 & !b.IsLocked).ToList();
            }

            var updates = await Bot.GetUpdatesAsync(offset);

            if (updates != null)
            {
                if (updates.Count() > 0)
                {
                    foreach (var update in updates) // Перебираем все обновления
                    {
                        ApplicationUser curUser;
                        var             message = update.Message;
                        if (message != null)
                        {
                            string curUserName = message.Chat.Username;
                            curUser = db.Users.Where(u => u.TelegramUserName == curUserName).FirstOrDefault();

                            /*
                             * //Добавляем ChatId
                             * if (curUser != null)
                             * {
                             *  if (curUser.TelegramChatId == 0)
                             *  {
                             *      curUser.TelegramChatId = message.Chat.Id;
                             *      db.Entry(curUser).State = EntityState.Modified;
                             *      db.SaveChanges();
                             *  }
                             * }
                             */


                            if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                            {
                                if (message.Text == "/register")
                                {
                                    //Добавляем ChatId
                                    if (curUser != null)
                                    {
                                        curUser.TelegramChatId  = message.Chat.Id;
                                        db.Entry(curUser).State = EntityState.Modified;
                                        db.SaveChanges();
                                        await Bot.SendTextMessageAsync(message.Chat.Id, "Регистрация прошла успешно!", replyToMessageId : message.MessageId);
                                    }
                                }
                                else if (message.Text == "/saysomething")
                                {
                                    // в ответ на команду /saysomething выводим сообщение
                                    //ReplyKeyboardHide rkh = new ReplyKeyboardHide();

                                    //await Bot.SendTextMessageAsync(message.Chat.Id, "тест",
                                    //       replyToMessageId: message.MessageId, replyMarkup: rkh);
                                    await Bot.SendTextMessageAsync(message.Chat.Id, "something!", replyToMessageId : message.MessageId);
                                }
                                else if (message.Text == "/mybets")
                                {
                                    string   senderUserName = message.From.Username;
                                    DateTime dt             = DateTime.UtcNow.Date;
                                    Debug.Print("Sender: " + senderUserName);
                                    string reply = "";
                                    reply = "А вот твоя панама, " + senderUserName + "!";
                                    List <Bet>           bets = getBetsByTelegramUserNameAndDate(senderUserName, dt);
                                    InlineKeyboardMarkup kb   = createKeabordFromBets(bets);
                                    await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : reply, replyMarkup : kb);
                                }
                                else if (Regex.IsMatch(message.Text, "^(?=.*\\d)\\d*[\\.\\,]?\\d*$"))
                                {
                                    string betStr = message.Text.Replace(',', '.');
                                    if (curUser.TelegramBetId > 0)
                                    {
                                        Bet curBet = db.Bets.Find(curUser.TelegramBetId);
                                        if (!curBet.IsLocked)
                                        {
                                            float telegramBet = Convert.ToSingle(betStr, CultureInfo.InvariantCulture.NumberFormat);
                                            curBet.BetSTIplus      = telegramBet;
                                            db.Entry(curBet).State = EntityState.Modified;
                                            db.SaveChanges();
                                            if (curBet.BetSTIplus == telegramBet)
                                            {
                                                string reply = "Принято: \n\"" + curBet.Program.ProgTitle + "\" - " + curBet.BetSTIplus.ToString();

                                                await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : reply);
                                            }
                                            else
                                            {
                                                await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : "Что-то пошло не так. Ставка не принята.");
                                            }
                                            curUser.TelegramBetId   = 0;
                                            db.Entry(curUser).State = EntityState.Modified;
                                            db.SaveChanges();
                                        }
                                        else
                                        {
                                            string reply = "Ставка \"" + curBet.Program.ProgTitle + "\" заблокирована. Поставить не удалось.";
                                            await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : reply);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (update.CallbackQuery.Data != null)
                            {
                                string curUserName = update.CallbackQuery.Message.Chat.Username;
                                curUser = db.Users.Where(u => u.TelegramUserName == curUserName).FirstOrDefault();

                                if (update.CallbackQuery.Data.Length > 5)
                                {
                                    if (update.CallbackQuery.Data.Substring(0, 5) == "betId")
                                    {
                                        string betId = update.CallbackQuery.Data.Substring(6);
                                        Bet    b     = db.Bets.Find(Convert.ToInt32(betId));
                                        if (b.ApplicationUser == curUser)
                                        {
                                            curUser.TelegramBetId   = Convert.ToInt32(betId);
                                            db.Entry(curUser).State = EntityState.Modified;
                                            db.SaveChanges();
                                            string reply = "Сколько ставим на \"" + b.Program.ProgTitle + "\"?";
                                            //await Bot.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, reply, false, false, update.CallbackQuery.Message.MessageId, kb);
                                            //await Bot.SendTextMessageAsync(update.CallbackQuery.Message.Chat.Id, reply, false, false, update.CallbackQuery.Message.MessageId, rkh);
                                            await Bot.SendTextMessageAsync(chatId : update.CallbackQuery.Message.Chat.Id, text : reply);
                                        }
                                    }
                                }
                                else
                                {
                                    await Bot.SendTextMessageAsync(chatId : message.Chat.Id, text : "Что-то пошло не так...");
                                }
                            }
                        }
                        offset = update.Id + 1;
                    }
                }
            }
        }
Esempio n. 24
0
        private void SendResponse(List <ChatId> receivers, KidsNoteNotifyMessage kidsNoteMessage)
        {
            foreach (var each in kidsNoteMessage.NewContents)
            {
                foreach (var eachContent in each.Value)
                {
                    string text = FormatContent(each.Key, eachContent);
                    //TheClient.SendTextMessageAsync(text).Wait();

                    List <Task <Message> > taskList = new List <Task <Message> >();
                    foreach (var user in receivers)
                    {
                        taskList.Add(TheClient.SendTextMessageAsync(user, text));
                    }

                    // 메시지 순서가 섞이지 않도록 모두 보내질 때까지 대기.
                    foreach (var task in taskList)
                    {
                        task.Wait();
                    }

                    LinkedList <InputMediaPhoto> photoAlbum = new LinkedList <InputMediaPhoto>();
                    //LinkedList<InputMediaDocument> otherAttachments = new LinkedList<InputMediaDocument>();
                    if (eachContent.Attachments != null && eachContent.Attachments.Count > 0)
                    {
                        taskList.Clear();

                        System.Diagnostics.Trace.WriteLine(String.Format("Title : {0}", eachContent.Title));

                        int no = 0;
                        foreach (var attach in eachContent.Attachments)
                        {
                            if (attach.Data == null)
                            {
                                // TODO: 관리 사용자에게 통지.
                            }
                            InputMedia media = new InputMedia(attach.Data, String.Format("{0}_{1}", ++no, attach.Name));
                            if (attach.Type == AttachmentType.IMAGE)
                            {
                                photoAlbum.AddLast(new InputMediaPhoto(media));
                                System.Diagnostics.Trace.WriteLine(String.Format("Attachment {0} : {1}", no, attach.Name));
                            }
                            else
                            {
                                // Telegram 으로는 Image 만 보낸다.
                                // otherAttachments.AddLast(new InputMediaDocument(media));
                            }
                        }
                    }

                    if (photoAlbum.Count > 0)
                    {
                        List <Task <Message[]> > mediaTaskList = new List <Task <Message[]> >();
                        foreach (var user in receivers)
                        {
                            mediaTaskList.Add(TheClient.SendMediaGroupAsync(photoAlbum, user));
                        }

                        // 메시지 순서가 섞이지 않도록 모두 보내질 때까지 대기.
                        foreach (var task in mediaTaskList)
                        {
                            task.Wait();
                        }
                    }
                }
            }
        }
Esempio n. 25
0
 /// <summary>
 /// Пррослушшиватель сообщений бота
 /// </summary>
 /// <param name="sendedr"></param>
 /// <param name="Args"></param>
 private static void BotLstner(object sendedr, tlg.Args.MessageEventArgs Args)
 {
     if (Args.Message.Type != tlg.Types.Enums.MessageType.Text)
     {
         FileHelper.SaveToFile(Args.Message, botWorker);
     }
     else
     {
         try
         {
             SelectedCommand = Args.Message.Text; //Записываем какую команду выбрали
             botCommand[Args.Message.Text](Args);
         }
         catch
         {
             botWorker.SendTextMessageAsync(Args.Message.Chat.Id, "Команда не разрешена.");
             commandStart(Args);
         }
     }
 }
Esempio n. 26
0
        private void processUpdate(Telegram.Bot.Types.Update update)
        {
            switch (update.Type)
            {
            case Telegram.Bot.Types.Enums.UpdateType.Message:
                var text        = update.Message.Text;
                var msgid       = update.Message.Chat.Username;
                var tlgusername = update.Message.Chat.Username;

                if (tlgusername != inst.TlgUserName)
                {
                    inst.TlgUserName = tlgusername;
                    _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons());
                }
                else
                {
                    // TODO: need to code refactoring in the feature and build this app in Asp.Net
                    if (text == CANCEL)
                    {
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons());
                        inst.Clear();
                        break;
                    }

                    if (inst.TicketType == MAIN_3 & string.IsNullOrEmpty(inst.TicketCategory) & string.IsNullOrEmpty(inst.UserName) & string.IsNullOrEmpty(inst.TicketDescription))
                    {
                        inst.TicketDescription = text;
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите ваше имя", replyMarkup: CancelButton());
                        break;
                    }

                    if (inst.TicketType == MAIN_3 & string.IsNullOrEmpty(inst.TicketCategory) & !string.IsNullOrEmpty(inst.TicketDescription) & string.IsNullOrEmpty(inst.PhoneNumber) & string.IsNullOrEmpty(inst.UserName) | !string.IsNullOrEmpty(inst.TicketType) & !string.IsNullOrEmpty(inst.TicketCategory) & string.IsNullOrEmpty(inst.UserName))
                    {
                        inst.UserName = text;
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите номер телефона \nПример: 89281234567", replyMarkup: CancelButton());
                        break;
                    }

                    if (!string.IsNullOrEmpty(inst.TicketType) & !string.IsNullOrEmpty(inst.UserName))
                    {
                        //if (text.All(char.IsDigit) & text.Substring(0, 1) == "8" || text.Substring(0, 1) == "7" & text.Length == 11)
                        if (text.All(char.IsDigit) & text.Substring(0, 1) == "8" & text.Length == 11)
                        {
                            inst.PhoneNumber = text;
                            // create random no of ticket
                            inst.TicketNumber = RandomNo();
                            // just for cw
                            Console.WriteLine("ticket: " + inst.TicketNumber);
                            Console.WriteLine("type: " + inst.TicketType);
                            Console.WriteLine("category: " + inst.TicketCategory);
                            Console.WriteLine("description: " + inst.TicketDescription);
                            Console.WriteLine("username" + inst.UserName);
                            Console.WriteLine("phone: " + inst.PhoneNumber);
                            Console.WriteLine("tlg: " + inst.TlgUserName);
                            Console.WriteLine("------------");
                            _client.SendTextMessageAsync(update.Message.Chat.Id, $"Спасибо, {inst.UserName}! Ваша заявка №{inst.TicketNumber} принята.");
                            _client.SendTextMessageAsync(update.Message.Chat.Id, "Перенаправляю вас в Главное меню!", replyMarkup: GetButtons());
                            // run method for sendind tlgChannel
                            SendTlgChannel(inst.TicketType, inst.TicketCategory, inst.TicketNumber, inst.TicketDescription, inst.UserName, inst.PhoneNumber, inst.TlgUserName);
                            // run method for sendind Email
                            //SendEmail(inst.TicketType, inst.TicketCategory, inst.TicketNumber, inst.UserName, inst.PhoneNumber);
                            inst.Clear();
                        }
                        else
                        {
                            _client.SendTextMessageAsync(update.Message.Chat.Id, "Некорректный номер, пожалуйста, введите правильный номер телефона \nПример: 89281234567", replyMarkup: CancelButton());
                        }
                        break;
                    }

                    switch (text)
                    {
                    case MAIN_1:
                    case MAIN_2:
                    case MAIN_4:
                        inst.TicketType = text;
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите категорию в меню", replyMarkup: GetCategory());
                        break;

                    case MAIN_3:
                        inst.TicketType = text;
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите описание проблемы", replyMarkup: CancelButton());
                        break;


                    case CAT_1:
                    case CAT_2:
                    case CAT_3:
                    case CAT_4:
                        inst.TicketCategory = text;
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Введите имя", replyMarkup: CancelButton());
                        break;

                    default:
                        _client.SendTextMessageAsync(update.Message.Chat.Id, "Выберите пункт в меню", replyMarkup: GetButtons());
                        break;
                    }
                }
                break;
            }
        }
        private static async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            String Answer = "";

            string[] arrayChar =
            {
                "https://www.meme-arsenal.com/memes/382906c071b1656c03104e98775b99b7.jpg",
                "https://www.meme-arsenal.com/memes/c27ee50cd596b0bd73ce01b543246de6.jpg",
                "https://pbs.twimg.com/media/EVqEsClXsAQ7Mio.jpg",
                "https://cs.pikabu.ru/post_img/2013/09/01/8/1378039082_293717672.jpg",
                "https://i.pinimg.com/originals/5f/67/a6/5f67a64f65f27821a81a9193c97f9573.jpg"
            };

            Telegram.Bot.Types.Message msg = messageEventArgs.Message;
            //if (msg == null || msg.Type != MessageType.Document) return;
            //{
            //    Console.WriteLine(msg.Document.FileId);
            //    var file = await BOT.GetFileAsync(msg.Document.FileId);
            //    FileStream fs = new FileStream("C:\\Users\\anton\\OneDrive\\Рабочий стол\\DangerousSausages\\file.pdf", FileMode.Create);
            //    await BOT.DownloadFileAsync(file.FilePath, fs);
            //    fs.Close();
            //    fs.Dispose();
            //}

            if (msg == null || msg.Type != MessageType.Text)
            {
                return;
            }
            switch (msg.Text)
            {
            case "/start":
                Answer = "Чтобы узнать, что я умею напишите /help\n";
                break;

            case "/help":
                Answer = "Бот не может работать по следующему сценарию:\n\n" +
                         "1.отправляется файл frx на экспорт\n" +
                         "2.экспортируется в некий формат, например pdf\n" +
                         "3.возвращается\n\n" +
                         "Но зато, есть секретик на команду /memes\n";
                break;

            case "/status":
                Answer = "Пока не работает остальное, мы не можем добавить данную функцию\n";
                break;

            case "/memes":
                Answer = "Поздравляю, вы нашли ржумбу и открыли панель с клавишей)\n";
                break;

            case "Скрыть панель":
                Answer = "напишите команду заново";
                await BOT.SendTextMessageAsync(msg.Chat.Id, "Для повторного вызова панели", replyMarkup : new ReplyKeyboardRemove());

                break;

            case "Мемесы:)":
                Answer = "Ржумба";
                await BOT.SendPhotoAsync(msg.Chat.Id, arrayChar[new Random().Next(0, arrayChar.Length)], " ");

                break;

            default:
                Answer = "В разработке";
                break;
            }
            await BOT.SendTextMessageAsync(msg.Chat.Id, Answer);


            if (msg.Text == "/memes")
            {
                var keyboard = new Telegram.Bot.Types.ReplyMarkups.ReplyKeyboardMarkup
                {
                    Keyboard = new[] {
                        new[]                         // row 5
                        {
                            new KeyboardButton("Мемесы:)"),
                        },
                        new[]                         // row 6
                        {
                            new KeyboardButton("Скрыть панель"),
                        },
                    },
                    ResizeKeyboard = true
                };
                await BOT.SendTextMessageAsync(msg.Chat.Id, "Нажмите на клавишу, чтобы получить мемчик", replyMarkup : keyboard);
            }
        }
Esempio n. 28
0
 public void sendMessageToUser(User user, Animal animal)
 {
     botClient.SendTextMessageAsync(
         user.ChatId != 0 ? user.ChatId : chatId,
         user.ChatId == 0 ? user.Name + " must to feed the " + animal.Name : "You must feed the: " + animal.Name);
 }
Esempio n. 29
0
        public async static void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = "573711040:AAFTiBmtBskcWKhD9Qw03dyXS6jw4WGjwSA"; // <<< PUT REAL KEY

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);
                //Bot.SetWebhook("");
                //await Bot.SetWebhookAsync("");

                int offset = 0;
                while (true)
                {
                    var updates = await Bot.GetUpdatesAsync(offset);

                    foreach (var update in updates)
                    {
                        var message = update.Message;
                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                        {
                            if (message.Text == "/start")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Hi! Welcome to Rechatter Bot!. With me you can send incognito messages to any user. To use me, you should have app ReChatter Bot App on your Windows Device (XBox/WindowsPhone/WindowsPC etc.). Right now you cant find any release for this app. So to get this app contact to developer @AlexBesida. Using me without special app is working in progress.", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Alex Besida", "https://t.me/AlexBesida")));
                            }

                            if (message.Text == "/developer")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "My developer is Alex Besida.", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Alex Besida", "https://t.me/AlexBesida")));
                            }

                            if (message.Text == "/sendmessage")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            if (message.Text == "/feedback")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            if (message.Text == "/help")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            if (message.Text == "/settings")
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }
                        }

                        offset = update.Id + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Esempio n. 30
0
        public HttpResponseMessage Post()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            string TelegramAPIKey = ConfigurationManager.AppSettings.Get("TelegramAPIToken");
            var    bot            = new Telegram.Bot.TelegramBotClient(TelegramAPIKey); //System.Environment.CurrentDirectory

            try
            {
                var body = Request.Content.ReadAsStringAsync().Result;
                var obj  = JsonConvert.DeserializeObject <ReleaseEvent>(body);
                if (obj?.subscriptionId != null)
                {
                    var releaseKey = ConfigurationManager.AppSettings.Get("VSTSReleaseId");
                    var buildKey   = ConfigurationManager.AppSettings.Get("VSTSBuildId");
                    if (obj.subscriptionId == releaseKey) //can't have random people triggering this!
                    {
                        //what was released
                        var beta    = obj.resource.environment.name.Contains("Beta");
                        var node    = obj.resource.environment.name.Contains("Node");
                        var control = obj.resource.environment.name.Contains("Control");
                        var website = obj.resource.environment.name.Contains("Website");


                        var msg = obj.detailedMessage.markdown;
                        InlineKeyboardMarkup menu = null;
                        if (obj.resource.environment.status == "succeeded")
                        {
                            if (website)
                            {
                                msg += "The website will now be deployed.\r\n";
                            }

                            if (node || control)
                            {
                                msg += "\nDo you want me to copy the files and update?";
                                menu = new InlineKeyboardMarkup(new[]
                                {
                                    InlineKeyboardButton.WithCallbackData("Yes",
                                                                          $"update|{(beta ? "beta" : "release")}{(node ? "node" : "control")}"),
                                    InlineKeyboardButton.WithCallbackData("No", "update|no")
                                });
                            }
                        }


                        bot.SendTextMessageAsync(GroupId, msg, replyMarkup: menu, parseMode: ParseMode.Markdown);
                    }

                    if (obj.subscriptionId == buildKey)
                    {
                        var build =
                            JsonConvert.DeserializeObject <BuildEvent>(Request.Content.ReadAsStringAsync().Result);

                        var detail = obj.detailedMessage.markdown;
                        if (detail.Contains("\r\n+ Process 'msbuild.exe'"))
                        {
                            detail = detail.Substring(0, detail.IndexOf("\r\n+ Process 'msbuild.exe'"));
                        }
                        detail = detail.Replace("\r\n+ ", "\r\n");
                        var msg    = detail + "\n";
                        var urlPre = "https://github.com/GreyWolfDev/Werewolf/commit/";
                        var ver    = build.resource.sourceGetVersion;
                        var commit = ver.Substring(ver.Length - 40, 40);
                        msg +=
                            $"Built with commit [{commit}]({urlPre + commit}) as latest";
                        if (build.resource.status == "succeeded")
                        {
                            msg += "\nRelease is now being created, you will be notified when it is completed.";
                        }

                        bot.SendTextMessageAsync(GroupId, msg, parseMode: ParseMode.Markdown);
                    }
                }
                else
                {
                    //github
                    var push = JsonConvert.DeserializeObject <PushEvent>(body);
                    var msg  =
                        $"🔨 <a href='{push.compare}'>{push.commits.Length} new commit{(push.commits.Length > 1 ? "s" : "")} to {push.repository.name}:{push._ref}</a>\n\n";
                    msg = push.commits.Aggregate(msg,
                                                 (current, a) => current +
                                                 $"<a href='{a.url}'>{a.id.Substring(0, 7)}</a>: {a.message} ({a.author.username})\n");



                    //string path = HttpContext.Current.Server.MapPath("~/App_Data/github.json");
                    //using (var sw = new StreamWriter(path))
                    //{
                    //    foreach (var c in push.commits)
                    //        sw.WriteLine($"Commit by: {c.committer.username}\nMessage: {c.message}\n");
                    //    sw.WriteLine(body);
                    //}

                    //check what was built
                    var beta   = push._ref.Contains("beta"); //beta or master - refs/head/<branch>
                    var master = push._ref.Contains("master");
                    //now check if control was changed
                    var control =
                        push.commits.Any(
                            x => x.modified.Union(x.added).Union(x.removed).Any(c => c.Contains("Werewolf Control")));
                    var node =
                        push.commits.Any(
                            x => x.modified.Union(x.added).Union(x.removed).Any(c => c.Contains("Werewolf Node")));
                    var website =
                        push.commits.Any(
                            x => x.modified.Union(x.added).Union(x.removed).Any(c => c.Contains("Werewolf Website")));

                    if ((!beta && !master) || (!control && !node && !website)) //nothing to build
                    {
                        bot.SendTextMessageAsync(GroupId, msg, parseMode: ParseMode.Html,
                                                 disableWebPagePreview: true);
                        return(Request.CreateResponse(HttpStatusCode.OK));
                    }



                    var none        = InlineKeyboardButton.WithCallbackData("No", "build|no");
                    var yes         = "Yes";
                    var betaControl = InlineKeyboardButton.WithCallbackData(yes, "build|betacontrol");
                    var betaNode    = InlineKeyboardButton.WithCallbackData(yes, "build|betanode");
                    var betaBoth    = InlineKeyboardButton.WithCallbackData(yes, "build|betaboth");

                    var releaseControl = InlineKeyboardButton.WithCallbackData(yes, "build|releasecontrol");
                    var releaseNode    = InlineKeyboardButton.WithCallbackData(yes, "build|releasenode");
                    //var releaseBoth = InlineKeyboardButton.WithCallbackData(yes, "build|releaseboth");
                    var releaseWebSite = InlineKeyboardButton.WithCallbackData(yes, "build|releasewebsite");
                    //var releaseWN = InlineKeyboardButton.WithCallbackData(yes, "build|releasenodewebsite");
                    //var releaseWC = InlineKeyboardButton.WithCallbackData(yes, "build|releasecontrolwebsite");
                    //var releaseAll = InlineKeyboardButton.WithCallbackData(yes, "build|releasewebsitebot");
                    Menu menu;

                    msg += "\nThis commit contains changes to ";
                    if (beta)
                    {
                        if (control && node && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("All of it!", "build|betacontrolwebsitenode"),
                                InlineKeyboardButton.WithCallbackData("Control & Node", "build|betacontrolnode"),
                                InlineKeyboardButton.WithCallbackData("Website & Control", "build|betacontrolwebsite"),
                                InlineKeyboardButton.WithCallbackData("Website & Node", "build|betanodewebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|betawebsite"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|betacontrol"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|betanode"),
                                none
                            });
                            msg += "Control, Node, and Website";
                        }
                        else if (control && node)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Control & Node", "build|betacontrolnode"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|betacontrol"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|betanode"),
                                none
                            });
                            msg += "Control and Node";
                        }
                        else if (control && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Website & Control", "build|betacontrolwebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|betawebsite"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|betacontrol"),
                                none
                            });
                            msg += "Control and Website";
                        }
                        else if (node && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Website & Node", "build|betanodewebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|betawebsite"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|betanode"),
                                none
                            });
                            msg += "Node and Website";
                        }
                        else if (control)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                betaControl,
                                none
                            });
                            msg += "Control only";
                        }
                        else if (node)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                betaNode,
                                none
                            });
                            msg += "Node only";
                        }
                        else //if (website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                releaseWebSite,
                                none
                            });
                            msg += "Website Only";
                        }
                    }
                    else
                    {
                        if (control && node && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("All of it!", "build|releasecontrolwebsitenode"),
                                InlineKeyboardButton.WithCallbackData("Control & Node", "build|releasecontrolnode"),
                                InlineKeyboardButton.WithCallbackData("Website & Control", "build|releasecontrolwebsite"),
                                InlineKeyboardButton.WithCallbackData("Website & Node", "build|releasenodewebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|releasewebsite"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|releasecontrol"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|releasenode"),
                                none
                            });
                            msg += "Control, Node, and Website";
                        }
                        else if (control && node)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Control & Node", "build|releasecontrolnode"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|releasecontrol"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|releasenode"),
                                none
                            });
                            msg += "Control and Node";
                        }
                        else if (control && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Website & Control", "build|releasecontrolwebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|releasewebsite"),
                                InlineKeyboardButton.WithCallbackData("Control Only", "build|releasecontrol"),
                                none
                            });
                            msg += "Control and Website";
                        }
                        else if (node && website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                InlineKeyboardButton.WithCallbackData("Website & Node", "build|releasenodewebsite"),
                                InlineKeyboardButton.WithCallbackData("Website Only", "build|releasewebsite"),
                                InlineKeyboardButton.WithCallbackData("Node Only", "build|releasenode"),
                                none
                            });
                            msg += "Node and Website";
                        }
                        else if (control)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                releaseControl,
                                none
                            });
                            msg += "Control only";
                        }
                        else if (node)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                releaseNode,
                                none
                            });
                            msg += "Node only";
                        }
                        else //if (website)
                        {
                            menu = new Menu(1, new List <InlineKeyboardButton>
                            {
                                releaseWebSite,
                                none
                            });
                            msg += "Website Only";
                        }
                    }
                    msg += $", on {(beta ? "Beta" : "Release")}\n";
                    msg += "Do you want to build?";

                    var r = bot.SendTextMessageAsync(GroupId, msg, replyMarkup: menu.CreateMarkup(), parseMode: ParseMode.Html,
                                                     disableWebPagePreview: true).Result;

                    //if (beta)
                    //{
                    //    var m = "Changes on beta branch. Do you want to build the website too?";
                    //    var websiteYes = InlineKeyboardButton.WithCallbackData("Yes", "build|website");
                    //    menu = new InlineKeyboardMarkup(new[] { websiteYes, none });
                    //    bot.SendTextMessageAsync(GroupId, m, replyMarkup: menu, parseMode: ParseMode.Html, disableWebPagePreview: true);
                    //}
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (AggregateException e)
            {
                var x = e.InnerExceptions[0];
                while (x.InnerException != null)
                {
                    x = x.InnerException;
                }
                bot.SendTextMessageAsync(GroupId, x.Message + "\n" + x.StackTrace);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, x));
            }
            catch (ApiRequestException e)
            {
                var code = e.ErrorCode;
                var x    = e.InnerException;
                while (x?.InnerException != null)
                {
                    x = x.InnerException;
                }
                bot.SendTextMessageAsync(GroupId, x?.Message + "\n" + x?.StackTrace);
                return(Request.CreateErrorResponse((HttpStatusCode)code, x));
            }
            catch (Exception e)
            {
                //string path = HttpContext.Current.Server.MapPath("~/App_Data/error");
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                bot.SendTextMessageAsync(GroupId, e.Message + "\n" + e.StackTrace);
                //using (var sw = new StreamWriter(path))
                //{
                //    sw.WriteLine(e.Message);
                //    sw.Flush();
                //}
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
            }
        }
Esempio n. 31
0
        private void Botik_OnMessageAsync(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            //  Тут очень простое дело - банально отправляем назад сообщения
            var message = e.Message;

            formUpdater("Тип сообщения : " + message.Type.ToString());

            //  Получение файла (картинки)
            if (message.Type == Telegram.Bot.Types.Enums.MessageType.Photo)
            {
                formUpdater("Picture loadining started");
                var  photoId = message.Photo.Last().FileId;
                File fl      = botik.GetFileAsync(photoId).Result;

                var img = System.Drawing.Image.FromStream(botik.DownloadFileAsync(fl.FilePath).Result);

                System.Drawing.Bitmap bm = new System.Drawing.Bitmap(img);
                System.Drawing.Bitmap uProcessed;
                //  Масштабируем aforge
                try
                {
                    uProcessed = MagicEye.ProcessDataSetImage(bm);
                }
                catch
                {
                    botik.SendTextMessageAsync(message.Chat.Id, "Глаз замылился");
                    return;
                }
                uProcessed.Save(@"..\..\1.jpg");

                Sample sample = SamplerConverter.Convert(uProcessed);

                var x = perseptron.Predict(sample);
                switch (x)
                {
                case FigureType.zero: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на нолик"); break;

                case FigureType.one: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на единичку"); break;

                case FigureType.two: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на двойку"); break;

                case FigureType.three: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на тройку"); break;

                case FigureType.four: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на четверку"); break;

                case FigureType.five: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на пятерку"); break;

                case FigureType.six: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на шестерку"); break;

                case FigureType.seven: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на семерку"); break;

                case FigureType.eight: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на восьмерку"); break;

                case FigureType.nine: botik.SendTextMessageAsync(message.Chat.Id, "Похоже на девятку"); break;

                default: botik.SendTextMessageAsync(message.Chat.Id, "Глаз замылился"); break;
                }
                string textresults = "";
                var    outputs     = perseptron.getOutput();
                textresults  = "Распознанная цифра: " + x.ToString() + "\r\n";
                textresults += " 0: " + outputs[0].ToString() + "\r\n";
                textresults += " 1: " + outputs[1].ToString() + "\r\n";
                textresults += " 2: " + outputs[2].ToString() + "\r\n";
                textresults += " 3: " + outputs[3].ToString() + "\r\n";
                textresults += " 4: " + outputs[4].ToString() + "\r\n";
                textresults += " 5: " + outputs[5].ToString() + "\r\n";
                textresults += " 6: " + outputs[6].ToString() + "\r\n";
                textresults += " 7: " + outputs[7].ToString() + "\r\n";
                textresults += " 8: " + outputs[8].ToString() + "\r\n";
                textresults += " 9: " + outputs[9].ToString() + "\r\n";
                formUpdater(textresults);
                //botik.SendPhotoAsync(message.Chat.Id, @"..\..\1.jpg");
                formUpdater("Picture recognized!");
                return;
            }
            else
            {
                if (message == null || message.Type != Telegram.Bot.Types.Enums.MessageType.Text)
                {
                    return;
                }
                if (message.Text == "Authors")
                {
                    string authors = "Гаянэ Аршакян, Луспарон Тызыхян, Дамир Казеев, Роман Хыдыров, Владимир Садовский, Анастасия Аскерова, Константин Бервинов, и Борис Трикоз (но он уже спать ушел) и молчаливый Даниил Ярошенко";
                    botik.SendTextMessageAsync(message.Chat.Id, "Авторы проекта : " + authors);
                }
                botik.SendTextMessageAsync(message.Chat.Id, mybot.Talk(message.Text));
                formUpdater(message.Text);
            }
            return;
        }
Esempio n. 32
0
 static async void DelayedMessage(TelegramBotClient bot, long chatId, string message, int minutesToWait)
 {
     await Task.Delay(minutesToWait * 60000);
     await bot.SendTextMessageAsync(chatId, message);
 }
Esempio n. 33
0
        public async static void Bw_DoWork(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = "627466136:AAFo8004Q5Z_UvZSjMsyiDstRcizoBE6xEQ"; // <<< PUT REAL KEY

            try
            {
                var Bot = new Telegram.Bot.TelegramBotClient(key);

                int offset = 0;
                while (true)
                {
                    var updates = await Bot.GetUpdatesAsync(offset);

                    foreach (var update in updates)
                    {
                        var message = update.Message;
                        if (message.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                        {
                            if (message.Text == "/start" || message.Text == "/start@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Good day! I'm Flux Assistant. I am always ready to help you. Right now, I am in Alpha Version. My developer is @AlexBesida", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Alex Besida", "https://t.me/AlexBesida")));
                            }

                            else if (message.Text == "/developer" || message.Text == "/developer@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "My developer is Alex Besida.", replyMarkup : new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("Alex Besida", "https://t.me/AlexBesida")));
                            }

                            else if (message.Text == "/feedback" || message.Text == "/@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            else if (message.Text == "/help" || message.Text == "/help@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            else if (message.Text == "/settings" || message.Text == "/settings@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, comingsoon);
                            }

                            else if (message.Text == "/myid" || message.Text == "/myid@" + AppSettings.FAName)
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Your ID is: " + message.From.Id + ".");
                            }

                            else if (message.Text.Contains("Hello") || message.Text.Contains("Hey") || message.Text.Contains("Hi") || message.Text.Contains("Hola") || message.Text.Contains("Hoy") || message.Text.Contains("Good day"))
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Hello!");
                            }

                            else if (message.Text.Contains("XD") || message.Text.Contains("xd") || message.Text.Contains("Xd") || message.Text.Contains("xD"))
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "A little laugh will not prevent you", replyToMessageId : message.MessageId);
                            }

                            else if (message.Text.Contains("Okey") || message.Text.Contains("Ok") || message.Text.Contains("OK"))
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "👌 🤙", replyToMessageId : message.MessageId);
                            }
                            else if (message.Text.Contains("How are you") || message.Text.Contains("Whats up") || message.Text.Contains("What's up"))
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "All fine, thanks. And you?", replyToMessageId : message.MessageId);
                            }

                            else if (message.Text.Contains("good") || message.Text.Contains("Good") || message.Text.Contains("Nice") || message.Text.Contains("Fine"))
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Okey 👌");
                            }



                            else
                            {
                                await Bot.SendTextMessageAsync(message.Chat.Id, "Sorry, but I did not understand.");
                            }
                        }

                        offset = update.Id + 1;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }