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 <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("<", "").Replace(">", "")); break; case "total carbs.": carbs = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("<", "").Replace(">", "")); break; case "total fat": fat = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("<", "").Replace(">", "")); break; case "dietary fiber": fiber = Convert.ToDouble(fact.Groups[2].Value.Replace("mg", "").Replace("g", "").Replace("<", "").Replace(">", "")); 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®ion=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®ion=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); } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // Load JObject from stream var jObject = JObject.Load(reader); IConversation conversation; if (jObject["title"] != null) { conversation = new GroupChat(); } else if (jObject["first_name"] != null) { conversation = new User(); } else { throw new JsonReaderException("Required properties not found"); } // Populate the object properties serializer.Populate(jObject.CreateReader(), conversation); return conversation; }
private async Task TeamSelected(long chatId, Telegram.Bot.Types.User user, string teamId) { var data = new { chatId, user, teamId }.ToJson(); try { TimeoutTimer.Stop(); // var prevQuestion = await _telegramBotHistoryRepository.GetLatestAsync(x => x.ChatId == chatId && x.UserId == user.Id); var prevQuestion = _history.LastOrDefault(); if (prevQuestion == null || prevQuestion.Question == _chooseTeam) { await _bot.SendTextMessageAsync(chatId, $"@{user.Username} \n" + _questionEnterName, replyMarkup : new ForceReplyMarkup { Selective = true }); await CreateBotHistory(chatId, user.Id, user.Username, _questionEnterName, teamId); await SaveHistory(false); TimeoutTimer.Start(); } else { await SendTextToUser(chatId); } } catch (Exception ex) { await _log.WriteErrorAsync("TelegramBotService.TeamSelected", data, ex); throw; } }
public async Task ClearTeam(long chatId, Telegram.Bot.Types.User user) { var data = new { chatId, user }.ToJson(); try { var entities = await _telegramBotHistoryRepository.GetAllAsync(x => x.Question == _chooseTeam && x.ChatId == chatId && x.UserId == user.Id); if (entities != null) { foreach (var entity in entities) { await _telegramBotHistoryRepository.RemoveAsync(entity.RowKey); } } await SendTextToUser(chatId, $"@{user.Username} \n" + "Your team was reseted."); } catch (Exception ex) { await _log.WriteErrorAsync("TelegramBotActions.ClearTeam", data, ex); throw; } }
private async Task <bool> IsUserJoinedThisGroupBeforeAsync(Chat chat, Telegram.Bot.Types.User user, FilterDefinitionBuilder <Entities.User> filter, IMongoCollection <Entities.User> usersCollection) { var existenceFilter = filter.ElemMatch(c => c.Groups, d => d.ChatId == chat.Id); var userGroup = await usersCollection.FindAsync(existenceFilter); return(userGroup.SingleOrDefault() != null); }
public async void getme() { Telegram.Bot.Types.User me = await tgbotClient.GetMeAsync(); Global.ME.ID = me.Id; Global.ME.Username = me.Username; Global.ME.FirstName = me.FirstName; }
private static void SendMemo(ChatId chat, Telegram.Bot.Types.User user) { const string textToSend = "21.12 12:21 - закрытие регистрации\n" + "22-е - получение анкет\n" + "26-о вечером - отправка подарков\n" + "27-о вечером (ориентировочно) - получение подарков"; Logger.Log($"{user} Sending memo"); SendMessage(chat, textToSend); }
private void AddUser(Telegram.Bot.Types.User user) { if (!trustedUsersForApprove.Any(u => u.ID == user.Id)) { trustedUsersForApprove.Add(new TrustedUserDTO() { ID = user.Id, Username = user.Username, FirstName = user.FirstName }); } }
public static User ToUser(TgUser user) { return(new User( user.Id, TgConstants.Name, !user.IsBot) { FirstName = user.FirstName, LastName = user.LastName, Username = user.Username }); }
//public static string GetUserName(Message message) //{ // string userName = String.IsNullOrEmpty(message.From.LastName) ? message.From.FirstName + " " : // message.From.FirstName + " " + message.From.LastName; // return userName; //} public static User CreateNewUserFrom(Telegram.Bot.Types.User userTg) { User u = new User { firstName = userTg.FirstName, lastName = userTg.LastName, userName = userTg.Username, telegramId = userTg.Id }; return(u); }
private System.Boolean IsUserAdmin(Telegram.Bot.Types.User user, Chat chat = null) { if (Singleton.GetInstance().Context._users.Any(c => c.ID == user.Id && c.IsAdmin != 0)) { return(true); } if (chat != null) { List <ChatMember> Ads = BotClient.GetChatAdministratorsAsync(chat).Result.ToList(); if (Ads.Any(c => c.User.Id == user.Id)) { return(true); } } return(false); }
/********************************************************************************************************* * // This function will check the user is already known or it will be added * // It will also do any check to be sure the user is ready, for example test the Qlik Sense connection *********************************************************************************************************/ private static QSUser CheckTheUser(string UserId, Telegram.Bot.Types.User TelegramUser, string UserName = "") { // Add the user if not exists // All new users are allowed by default except if running in Demo Mode, they can be banned in the users file QSUser Usr = QlikUsers.AddUser(UserId, UserName); Usr.QS = (Usr.QS == null) ? QSTemplateApp : Usr.QS; if (Usr.QS == null) { // This user has no connection Usr.QS = new QSApp(); // This is the default Qlik Sense app for new users // Fill it with the default values from the template Usr.QS.qsAppName = QSTemplateApp.qsAppName; Usr.QS.qsAppId = QSTemplateApp.qsAppId; Usr.QS.qsServer = QSTemplateApp.qsServer; Usr.QS.qsSingleServer = QSTemplateApp.qsSingleServer; Usr.QS.qsSingleApp = QSTemplateApp.qsSingleApp; Usr.QS.qsAlternativeStreams = QSTemplateApp.qsAlternativeStreams; try { // Create or use the Telegram UserID as the Qlik Sense UserID to open the connection Connect(Usr.QS, UserId, QSTemplateApp.VirtualProxy(), QSTemplateApp.IsUsingSSL()); // And open the app if (!Usr.QS.AppIsOpen) { Usr.QS.QSOpenApp(); } Console.WriteLine(string.Format("Opened the Qlik Sense app: {0} for user {1} ({2})", Usr.QS.qsAppName, Usr.UserId, Usr.UserName)); } catch (Exception e) { Console.WriteLine(string.Format("Error opening the Qlik Sense app{0} for user {1}: {2}", Usr.QS.qsAppName, Usr.UserId, e)); } } else { // The connection was previously created, so check the connection is alive Usr.QS.CheckConnection(); } return(Usr); }
private async Task <Models.User> GetUser(Update update) { Telegram.Bot.Types.User telegramUser = update.Type switch { UpdateType.Message => update.Message.From, UpdateType.CallbackQuery => update.CallbackQuery.From, _ => null }; if (telegramUser == null) { return(null); } return(await userRepo.GetByIdAsync(telegramUser.Id)); } }
private static void OnBotWokeUp(Update update) { Telegram.Bot.Types.Chat chat = null; Telegram.Bot.Types.User user = null; try { if (update?.Message != null) { chat = update.Message.Chat; user = update.Message.From; } else if (update?.CallbackQuery != null) { chat = update.CallbackQuery.Message.Chat; user = update.CallbackQuery.From; } else { return; } if (Chats.TryGetValue(chat.Id, out _)) { return; } var chatRoom = CreateChatRoom(chat); if (chatRoom == null) { return; } chatRoom.ChatIo.SendMessageAsync(new EnglishTexts().DidYouWriteSomething).Wait(); chatRoom.ChatIo.OnUpdate( new Update { Message = new Message { Text = "/start", From = user } }); RunChatRoom(chat, chatRoom); } catch (Exception e) { Botlog.WriteError(chat?.Id, "WokeUpfailed" + e, true); } }
public static void DeleteStatusByUserAndChat(Telegram.Bot.Types.User user, Telegram.Bot.Types.Chat chat) { using (var db = new ApplicationContext()) { try { var status = db.UserStatuses .Where(s => s.Chat.ChatId == chat.Id) .FirstOrDefault(s => s.User.UserId == user.Id); db.UserStatuses.Remove(status); db.SaveChanges(); } catch { Console.WriteLine("Error with deleting statys"); } } }
static void Main() { Processing.ReadCsv(); botClient = new TelegramBotClient(Configuration.BotToken); me = botClient.GetMeAsync().Result; Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}."); //botClient.OnMessage += Bot_FirstOnMessage; botClient.OnMessage += Bot_OnMessage; botClient.StartReceiving(); Console.WriteLine("Press any key to exit"); Console.ReadKey(); botClient.StopReceiving(); Console.ReadKey(); }
/// <summary> /// Поиск юзера и его последнего действия /// Если юзер новый, то создает в бд /// </summary> /// <param name="msg"></param>сообщение /// <returns></returns> private static async Task <States> getState(Telegram.Bot.Types.User msg) { using (MyDB db = new MyDB()) { try { var res = db.Users.First(x => x.UserId == msg.Id); return((States)res.state); } catch (Exception) { db.Users.Add(new DB_model.User { UserId = msg.Id }); await db.SaveChangesAsync(); } } return(0); }
private static void SendUserProfile(ChatId chat, User localUser, Telegram.Bot.Types.User user) { string textToSend = ""; textToSend += "Статус анкеты: "; switch (localUser.State) { case States.RegistrationCompleted: textToSend += "Регистрация завершена\n"; break; case States.NewUser: textToSend += "Регистрация не начата\n"; break; case States.TargetChosen: textToSend += "Регистрация завершена\n"; break; case States.TargetSent: textToSend += "Регистрация завершена, цель получена\n"; break; case States.RegistrationStarted: textToSend += "Регистрация в процессе\n"; break; } textToSend += "ФИО: "; textToSend += localUser.OfficialName + "\n"; textToSend += "Номер телефона: "; textToSend += localUser.Phone + "\n"; textToSend += "Город и номер отделения НП: "; textToSend += localUser.Post + "\n"; textToSend += "Я фанат: "; textToSend += localUser.FanOf + "\n"; textToSend += "Мне не стоит дарить: "; textToSend += localUser.Ban + "\n"; Logger.Log($"{user} Sending profile"); SendMessage(chat, textToSend); }
public static void Start(Update u, string[] args) { if (u.Message.Chat.Type != ChatType.Private) { return; } TgUser user = u.Message.From; var dbUser = DB.Users.Find(user.Id); if (dbUser == null) { dbUser = DB.Users.Add(user.CreateDbUser(Bot.GetLanguage(user.LanguageCode))); } dbUser.FirstName = user.FirstName; dbUser.LastName = user.LastName; dbUser.LanguageCode = user.LanguageCode; dbUser.Username = user.Username; DB.SaveChanges(); Bot.SendLocale(user.Id, "Start"); }
public static bool Start() { try { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; me = Bot.GetMeAsync().Result; Bot.OnMessage += BotOnMessageReceived; Bot.OnMessageEdited += BotOnMessageReceived; Bot.OnCallbackQuery += BotOnCallbackQueryReceived; Bot.OnInlineQuery += BotOnInlineQueryReceived; Bot.OnInlineResultChosen += BotOnChosenInlineResultReceived; Bot.OnReceiveError += BotOnReceiveError; Bot.StartReceiving(new List <UpdateType>().ToArray()); return(true); } catch { return(false); } }
public static void CheckAndAddUserToDb(Telegram.Bot.Types.User user) { try { using (ApplicationContext db = new ApplicationContext()) { if (db.Users.FirstOrDefault(u => u.UserId == user.Id) == null) { db.Users.Add(new Database.User() { UserId = user.Id, UserName = user.Username, FirstName = user.FirstName, IsBot = user.IsBot, LanguageCode = user.LanguageCode, LastName = user.LastName }); db.SaveChanges(); } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } }
private async Task <bool> IsCanAnswer(Telegram.Bot.Types.User from, Message message) { int userID = from.Id; string userName = from.Username; if (!trustedUsers.Any(u => u.ID == userID)) { UntrustedUserDTO user = untrustedUsers.FirstOrDefault(u => u.ID == userID); if (user != null) { TimeSpan timeSpan = DateTime.Now - user.TimeLastRequest; if (timeSpan.TotalMinutes < telegramBotSettings.ReqTimeoutForUntrustedUsers) { if (!user.IsNotified) { long chatID = message.Chat.Id; await botClient.SendTextMessageAsync(chatID, $"You make requests too often. Try after {user.TimeLastRequest.AddMinutes(telegramBotSettings.ReqTimeoutForUntrustedUsers)}").ConfigureAwait(false); user.IsNotified = true; } return(false); } else { untrustedUsers.Remove(user); } } else { untrustedUsers.Add(new UntrustedUserDTO() { ID = userID, IsNotified = false, TimeLastRequest = DateTime.Now }); } } return(true); }
/// <summary> /// Connect and start receiving messages. Returns false if failed to connect. /// </summary> public static bool Connect() { if (string.IsNullOrEmpty(Config.Params.TelegamToken)) { Log.Error("Telegram token is null or empty!"); return(false); } Log.Information("Connecting..."); api = new TelegramBotClient(Config.Params.TelegamToken); if (!api.TestApiAsync().Result) { Log.Error("API Test failed, shutting down!"); return(false); } BotUser = api.GetMeAsync().Result; Log.Information("API Test successful, starting receiving..."); api.StartReceiving(new DefaultUpdateHandler(HandleUpdates, HandleError)); Log.Information("Connected!"); return(true); }
async public Task Initialize () { me = await bot.GetMe (); Console.WriteLine ("Telegram Frontend Initialized"); }
public static User ToImgUser(this tg.User user) { return(new User { TgId = user.Id, IsAdmin = false, UserName = user.Username }); }
private void Client_OnConnected(object sender, User me) { tabControl1.SelectTab(2); Console.Text += Environment.NewLine + "Connected to Telegram Web API ! " + Environment.NewLine + "Bot_ID: " + me.Id + " Bot_FirstName: " + me.FirstName + "Bot_LastName: " + me.LastName + " Bot_UserName: " + me.Username; }
private static async void SendIntroMessages(ChatId chat, Telegram.Bot.Types.User user) { const double sendOffsetInSecs = 0.3; Logger.Log($"{user} Sending intro messages"); var textToSend = "Приветствуем Вас в боте Секретного Санты ЖППП!"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "С помощью этого бота вы можете зарегистрироваться для участия, а также узнать всю подробную инфу" + " касательно Секретного Санты 2020 by Zhopki Popki©! <i>главный админ убьет меня за такое название ну не" + " важно давайте начинать уже там целая простынь текста дальше...</i>"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "Поскольку этот год оч прикольный такой и интересный в некоторых моментах, мы в редакции Желтой" + " Прессы решили, что разумнее всего будет провести данный ивент с некоторыми поправками, касающимися" + " доставки подарков. И ДА - подарки будут отправляться по почте :("; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "И тут есть два момента: во-первых - Вы не сможете ехидно пронаблюдать за тем как кто-то" + " распаковывает, тщательно Вами запакованную в матрешку из коробок и туалетной бумаги флешку," + " но на этот счет мы попробуем кое-что предпринять; а во-вторых это то, что человек," + " принимающий подарок, сможет узнать от кого получил подарок (из-за накладной)."; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "<i>(Кто-то по секрету сказал что можно попробовать на почте при отправке указать не Ваши" + " а абсолютно рандомные данные и таким образом остаться анонимным, однако этот вариант" + " стоит рассматривать только для энтузиастов и вообще обязательным не является)</i>"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "Ладно, давайте перейдем к делу. Для начала Вам нужно будет заполнить небольшую анкету," + " в которой указать такую информацию:\n" + "ФИО\n" + "Номер телефона\n" + "Инфа о почтовом отделении\n" + "А также некоторая информация для человека который будет дарить, дабы ни у кого " + "не было проблем с выбором подарка"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "Форма для регистрации будет открыта до 21.12 12:21 (поторопитесь, попингуйте-потэгайте" + " всех ППшничков которые должны в этом участвовать чтобы никто не пропустил), и 22-о" + " днем Вам придет анкета того кому Вы будете дарить подарок. Далее Вы готовите подарок " + "и отправляете его 26-о числа (по-возможности так чтоб посылка пришла получателю 27-о числа)."; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "Ориентировочно 27-о числа вечером Вам приходит посылочка и Вы идете ее забираете. " + "Радостные открываете свои носки с оленями и такие же радостные делаете фоточки-видосики и " + "кидаете их сюда в бот, в чатик Прикладного питания или делитесь ими со всеми каким либо " + "другим образом. Так каждый сможет понаблюдать за получателем подарка и все разделят " + "радость праздника с другими."; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "Касательно подарка - это может быть что угодно, главное чтоб было весело и " + "приятно <i>и <b>от души</b></i>. Наши рекомендации (чтобы никому не было обидно) по " + "поводу стоимости подарка это 150-250грн, а также не забывайте что около 50грн пойдет на " + "отправку посылки. К тому же это стоит учитывать при упаковке подарка, например всякие " + "банты на коробках по любому помнут на почте если не предпринять какие-то меры 😭. <i>Банты топ.</i>"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "И на этом наконец все! Совсем скоро Вы уже начнете заполнять анкету, но перед этим " + "хотелось бы сказать про еще один очень важный момент. Этот бот написан каким-то криворуким " + "ППшником на коленке и будет очень неудивительно если бот ляжет или не сможет исполнять " + "свои функции в каком-то другом плане. В таком случае пишите на аккаунт нашей поддержки" + " - @bIudger, и мы постараемся помочь Вам в ближайшее время. " + "Иии да, можете уже заполнять анкету, удачи Вам с подготовкой подарка и счастливых праздников 🥳!"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(sendOffsetInSecs)); textToSend = "С любовью, редакция @ppidory <i>(ахвахвхахв у нас внатуре тэг канала - ПИПИДОРЫ)</i>"; SendMessage(chat, textToSend); }
// TODO send memo on deleting confirmation private static async void AskProfileQuestion(Chat chat, Telegram.Bot.Types.User user, User localUser) { string textToSend; Logger.Log($"{user} Asking next question"); switch (localUser.Stage) { case Stages.None: Logger.Log($"{user} is on None stage, asking Name question"); textToSend = "ФИО (полное, на рідній или русском)"; SendMessage(chat, textToSend); break; case Stages.StageOffName: Logger.Log($"{user} is on Name stage, asking Phone question"); textToSend = "Номер телефона (необходим для отправки посылки)"; SendMessage(chat, textToSend); break; case Stages.StagePhone: Logger.Log($"{user} is on Phone stage, asking Post question"); textToSend = "Город и номер отделения НП (или подробно описать другой метод доставки)"; SendMessage(chat, textToSend); break; case Stages.StagePost: Logger.Log($"{user} is on Post stage, asking Fan question"); textToSend = "Теперь пара вопросов для того чтобы можно было получше выбрать Вам подарок"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(0.2)); textToSend = "Опишите фанатом чего вы являетесь (например Гарри Поттер, Initial D, " + "Гречка (ну та которая музыку поет), Райан Гослинг)"; SendMessage(chat, textToSend); break; case Stages.StageFan: Logger.Log($"{user} is on Fan stage, asking Ban question"); textToSend = "А теперь укажите что Вам лучше не дарить " + "<i>(конечно можете пропустить этот пункт (тогда напишите что-то типа " + "\"Все равно...\"), но любой Ваш отзыв обязательно обработают и учтут наши " + "сотрудники отдела качества)</i>"; SendMessage(chat, textToSend); break; case Stages.StageBan: Logger.Log($"{user} is on Ban stage, asking registration confirmation"); textToSend = "Отлично, это были все вопросы на которые необходимо было ответить! " + "Теперь проверьте Вашу анкету еще раз потому, что после подтверждения " + "изменить ответы через бот невозможно:"; SendMessage(chat, textToSend); await Task.Delay(TimeSpan.FromSeconds(0.2)); SendUserProfile(chat, localUser, user); await Task.Delay(TimeSpan.FromSeconds(0.2)); textToSend = "Если все хорошо, то нажмите команду /confirm_registration " + "если же хотите что-то изменить, то нажмите команду /abort_registration " + "и заполните заново 👹"; SendMessage(chat, textToSend); break; } }
public static bool IsUserOwner(User user) { if (user.Id == OwnerId && user.Username.Equals(OwnerUsername)) return true; return false; }
public string GetUserTargetName(Telegram.Bot.Types.User user) { return(GetUserTargetName(user.Username, user.FirstName, user.LastName)); }
public static void changeBalance(Telegram.Bot.Types.User user, long changeValue) { BotMain.users.FirstOrDefault(m => m.id == user.Id).balance += changeValue; }
private void runBot() { Bot = new Telegram.Bot.TelegramBotClient(Token); this.Invoke(new Action(() => { lblStatus.Text = "Online"; lblStatus.ForeColor = Color.Green; })); int offset = 0; while (true) { try { Telegram.Bot.Types.Update[] Update = Bot.GetUpdatesAsync(offset).Result; foreach (Telegram.Bot.Types.Update Up in Update) { offset = Up.Id + 1; while (Up.CallbackQuery != null) { //Contatct To Me Inline if (Up.CallbackQuery.Data.Contains("gmail")) { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Gmail address is : [email protected]"); Up.CallbackQuery = null; break; } else if (Up.CallbackQuery.Data.Contains("outlook")) { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "My Outlook address is : [email protected]"); Up.CallbackQuery = null; break; } //Poll Inline var user = db.PollManager.SingleOrDefault(u => u.UserID == Up.CallbackQuery.From.Id); if (user == null) { user = new PollManager() { UserID = Up.CallbackQuery.From.Id, VotedByUser = "" }; db.PollManager.Add(user); db.SaveChanges(); } var UserID = Up.CallbackQuery.From.Id; var pUserID = db.PollManager.Select(p => p.UserID).ToList(); var pVotedByUSer = db.PollManager.Select(p => p.VotedByUser).ToList(); var query = Up.CallbackQuery.Data; string VotedNow = Up.CallbackQuery.Data; if (db.PollManager.Any(p => (p.UserID == Up.CallbackQuery.From.Id) && (p.VotedByUser != VotedNow))) { Poll(Up, db.PollManager.SingleOrDefault(a => a.UserID == UserID).VotedByUser, VotedNow); InlineKeyboardMarkup PollButons = PollInline(); Bot.EditMessageReplyMarkupAsync(Up.CallbackQuery.Message.Chat.Id, Up.CallbackQuery.Message.MessageId, replyMarkup: PollButons); Up.CallbackQuery = null; } else { Bot.SendTextMessageAsync(Up.CallbackQuery.Message.Chat.Id, "You have rated before"); } Up.CallbackQuery = null; } if (Up.Message == null) { continue; } string MessageFromUser = Up.Message.Text.ToLower(); Telegram.Bot.Types.User Upfrom = Up.Message.From; Telegram.Bot.Types.ChatId ChatID = Up.Message.Chat.Id; StringBuilder SB = new StringBuilder(); if (MessageFromUser.Contains("start")) { ReplyKeyboardMarkup MainKeyboardMarkup = StartKeyboards(); SB.AppendLine("Welcome To My Bot"); SB.AppendLine("Contact To Me : /ContactToMe"); SB.AppendLine("About Me : /AboutMe"); Bot.SendTextMessageAsync(ChatID, SB.ToString(), parseMode: default, false, true, 0, MainKeyboardMarkup);
public static string ToString(this Telegram.Bot.Types.User user) { return((user.FirstName + " " + user.LastName).Trim()); }
public async Task RunBot() { Bot = new Telegram.Bot.Api(Token); me = await Bot.GetMe(); Translator.Translator T = null; Console.WriteLine("System>{0} is on!", me.Username); int offset = 0; while (true) { Update[] updates = await Bot.GetUpdates(offset); foreach (Update update in updates) { this.update = update; if (update.Message.From.Id.ToString() == user)//Auth OK { if (update.Message.Type == MessageType.TextMessage) { Console.WriteLine(update.Message.Text); if (update.Message.Text == "/start") { SendMessage("일본어 번역기 봇 ver" + Version + " by 조호연@KMOU"); SendMessage("일본어, 한국어, Romaji 지원"); offset = update.Id + 1; break; } try { T = new Translator.Translator(update.Message.Text); T.Translate(); switch (T.L.SoruceType) { case "ko": SendMessage("번역된 말 : " + T.L.Japanese + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); SendMessage(T.L.Japanese); break; case "ja": SendMessage("번역된 말 : " + T.L.Korean + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); break; case "rmj": SendMessage(T.L.Japanese + "으로 변경되었음.\n" + "번역된 말 : " + T.L.Korean + "\n\n재번역된 말 : " + T.L.Retranslated + "\n\n일본어 발음 : " + T.L.Furigana); break; default: SendMessage("해석 불가!"); break; } T = null; } catch (Exception e) { SendMessage("Error!"); offset = update.Id + 1; continue; } } offset = update.Id + 1; } } await Task.Delay(500); } }
public User GetUserFromTg(Telegram.Bot.Types.User tgUser) { return(new User(tgUser.Id, tgUser.IsBot, tgUser.FirstName, tgUser.LastName, tgUser.Username, tgUser.LanguageCode)); }