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 TelegramService(string apiKey, ISession session) { this.bot = new TelegramBotClient(apiKey); this.session = session; var me = bot.GetMeAsync().Result; bot.OnMessage += OnTelegramMessageReceived; bot.StartReceiving(); this.session.EventDispatcher.Send(new NoticeEvent {Message = "Using TelegramAPI with " + me.Username}); }
public TelegramService(string apiKey, ISession session) { try { _bot = new TelegramBotClient(apiKey); _session = session; var me = _bot.GetMeAsync().Result; _bot.OnMessage += OnTelegramMessageReceived; _bot.StartReceiving(); _session.EventDispatcher.Send(new NoticeEvent {Message = "Using TelegramAPI with " + me.Username}); } catch (Exception) { _session.EventDispatcher.Send(new ErrorEvent { Message = "Unkown Telegram Error occured. "}); } }
internal void GetUpdates() { _client = new Telegram.Bot.TelegramBotClient(_token); var me = _client.GetMeAsync().Result; if (me != null && !string.IsNullOrEmpty(me.Username)) { int offset = 0; while (true) { try { var updates = _client.GetUpdatesAsync(offset).Result; if (updates != null && updates.Count() > 0) { foreach (var update in updates) { processUpdate(update); offset = update.Id + 1; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } //Thread.Sleep(1000); Task.Delay(1000); } } }
private void button1_Click(object sender, EventArgs e) { BOT = new Telegram.Bot.TelegramBotClient("744578703:AAFel2eXEWWYrsiplEPhxgxNCd2BSLumYmQ"); BOT.OnMessage += BotOnMessageReceived; BOT.StartReceiving(); button1.Enabled = false; }
static void Main(string[] args) { Console.WriteLine("Json is loading..."); try { JsonData.InitJson(); } catch (Exception e) { Console.WriteLine(e.Message + "I GOT YOU"); } try { var botClient = new Telegram.Bot.TelegramBotClient("365015286:AAED8kb8oncNHdruQcDpTk_WaRNFjeHm8Lo"); bot = botClient; } catch (Exception e) { Console.WriteLine(e.Message + "I GOT YOU!"); } try { bot.StartReceiving(); bot.OnMessage += Bot_OnMessage; bot.OnCallbackQuery += Bot_OnCallbackQuery; } catch (Exception e) { Console.WriteLine(e.Message + "I GOT YOU"); } Console.ReadLine(); }
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); } } }
private void frmConfig_FormClosing(object sender, FormClosingEventArgs e) { if (TelegramBotClient != null) { __cancellationTokenSource.Cancel(); TelegramBotClient = null; } }
private async void telegramAPIAsync() { var Bot = new Telegram.Bot.TelegramBotClient("Token key"); var me = await Bot.GetMeAsync(); //Debug.WriteLine("Hello my name is {0}", me.FirstName); }
private TelegramBotClient BuildBot() { var bot = new Telegram.Bot.TelegramBotClient("340012648:AAF1bURuuTS7Dce5iDfkQrINRDHNMftSSeo"); bot.OnMessage += BotOnMessageReceived; bot.StartReceiving(); return(bot); }
public TelegramClient(Matbot.Bot bot, ClientToken token) : base(bot, token) { Token = token.Token; TClient = new TelegramBotClient(token.Token); TClient.OnUpdate += TClient_OnUpdate; CustomCmdManger.RegisterNewCommand(new StickersOnlyCommand()); }
public TelegramBot() { if (SettingsStore.Default.TelegramBotBroadcastId != 0) { BroadcastId = new ChatId(SettingsStore.Default.TelegramBotBroadcastId); } InnerClient = new Telegram.Bot.TelegramBotClient("410447550:AAGz1QRPgdoh5tuddcMleFYI9Ttw-Ytn9Fs"); IsActive = SettingsStore.Default.TelegramBotActive; Update(); }
public TelegramBotTransport(string token) { Token = token; _bot = new TBotApi(token); _bot.OnMessage += Bot_OnMessage; _bot.OnMessageEdited += Bot_OnMessage; _bot.OnReceiveError += Bot_OnReceiveError; _bot.OnInlineQuery += Bot_OnInlineQuery; _bot.OnInlineResultChosen += Bot_OnInlineResultChosen; }
private void StartBot(object sender, RoutedEventArgs e) { if (TokenLabel.Content.Equals("Token received")) { TokenLabel.Content = "Bot alive"; } BOT = new Telegram.Bot.TelegramBotClient(Token); BOT.OnMessage += BotOnMessageReceived; BOT.StartReceiving(new UpdateType[] { UpdateType.Message }); }
public TLGBotik(BaseNetwork net, UpdateTLGMessages updater) { var botKey = System.IO.File.ReadAllText("botkey.txt"); mybot = new AIMLBotik(); botik = new Telegram.Bot.TelegramBotClient(botKey); botik.OnMessage += Botik_OnMessageAsync; //botik.OnMessage += MyBotik_OnMessageAsync; formUpdater = updater; perseptron = net; }
private void tmSearch_Tick(object sender, EventArgs e) { tmSearch.Enabled = false; bnSearch.Enabled = true; if (TelegramBotClient != null) { __cancellationTokenSource.Cancel(); TelegramBotClient = null; } }
public TelegramBot() { var proxy = new HttpToSocks5Proxy("142.93.108.135", 1080, "sockuser", "boogieperets"); WebClient cl = new WebClient(); cl.Proxy = proxy; proxy.ResolveHostnamesLocally = true; InnerClient = new Telegram.Bot.TelegramBotClient("410447550:AAGz1QRPgdoh5tuddcMleFYI9Ttw-Ytn9Fs", proxy); }
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"); } }
/// <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); } }
private static bool isInternetConnected() { try { Telegram.Bot.TelegramBotClient teleBot = new Telegram.Bot.TelegramBotClient(botToken); var me = teleBot.GetMeAsync().Result; return(true); } catch { return(false); } }
//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"); } }
public TelegramConnector() { botClient = new Telegram.Bot.TelegramBotClient("524727579:AAHZaFNr3S1vUfuPy-wZEIGO3-WxQWodL5s"); var me = botClient.GetMeAsync(); Console.WriteLine("Api for bot: " + me.Result.FirstName + " - was connected"); Console.WriteLine("Connected to: " + botClient.GetChatAsync(chatId).Result.Title + "chat"); botClient.OnMessage += onMessage; botClient.StartReceiving(Array.Empty <UpdateType>()); Thread.Sleep(2000); }
public NotifierBot(string apiKey) { TheClient = new TelegramBotClient(apiKey); RequestQueue = new RequestMessageQueue(this); ResponseQueue = new ResponseMessageQueue(this); TheClient.OnMessage += this.OnMessageReceived; TheClient.OnCallbackQuery += this.OnCallbackQueryReceived; TheClient.OnInlineResultChosen += this.OnChosenInlineResultReceived; TheClient.OnInlineQuery += this.OnInlineQueryReceived; TheClient.OnReceiveError += this.OnReceiveError; TheClient.OnReceiveGeneralError += this.OnReceiveGeneralError; TheClient.OnUpdate += this.OnUpdateReceived; }
public async void testApi() //метод проверки связи данного бота по нашему токену { try { Bot = new Telegram.Bot.TelegramBotClient(token); var me = await Bot.GetMeAsync(); ApiCheck = 0; //Thread newThread = new Thread(RemindBookBotClient.ReceiveMessage); //newThread.Start(); } catch (Exception ex) { ApiCheck = 1; } }
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); } }
public static async void ShowPrice(Telegram.Bot.TelegramBotClient botClient, Message message) { var keyboard = new InlineKeyboardMarkup( new InlineKeyboardButton[] { new InlineKeyboardButton { Text = "Я согласен! Хочу добавить вакансию✅", CallbackData = "AddVacancy" } } ); var messageText = $"Стоимость размещения вакансий:\n\n <b>990р</b> - один пост, то есть одна вакансия\n" + $"<b>2690р</b> - ОПТ, 3 поста в месяц(по одной вакансии на пост)\n\n" + $"Вы получите: \n1. До 16 000 просмотров за первые сутки, а это до 200 откликов.\n" + $"2. Ваша вакансия никогда не будет удаляться из канала наберёт 24 000 - 30 000 просмотров исполнителями.\n" + $"3. Вакансия не улетит быстро вниз. Мы публикуем до 4-х вакансий в сутки."; await SendMessage(botClient, message, messageText, keyboard); }
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); }
public ReactionCommand(TelegramBotClient bot, List<string> folderNames, string cacheFilePath):base(bot) { _rng = new Random(); _files = new List<FileInfo>(); foreach (var folderName in folderNames) { var dir = new DirectoryInfo(folderName); if (dir.Exists) { _files.AddRange(dir.EnumerateFiles().ToList()); } } _cacheFilePath = cacheFilePath; // Since Telegram allows you to "send" files by using their id (if they are on the server already), // I use this to create a simple cache by sending id of a file if it was already sent once. _sentFiles = new Dictionary<string, string>(); }
public AskStasonCommand(TelegramBotClient bot, string responsesFilePath):base(bot) { _rng = new Random(); _responses = new List<string>(); _weights = new List<int>(); using (var sr = new StreamReader(new FileStream(responsesFilePath, FileMode.Open))) { var str = sr.ReadToEnd(); if (str.Length > 0) { Dictionary<string, int> config = null; try { config = JsonConvert.DeserializeObject<Dictionary<string, int>>(str); } catch (Exception ex) { Log.Logger.Error("An error as occured during parsing of {0} file. Error message: {1}", responsesFilePath, ex.Message); } if (config != null) { // { a:5, b:5, c:3, d:1 } => { 5:a, 10:b, 13:c, 14:d } int accumulator = 0; foreach (var item in config) { // Skip incorrect values if (item.Value < 0) continue; accumulator += item.Value; _responses.Add(item.Key); _weights.Add(accumulator); } _maxRadnomValue = accumulator; } } else { Log.Logger.Warning("The file {0} was expected to be populated with data, but was empty.", responsesFilePath); } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); // Setup telegram client var accessToken = Configuration["Settings:accessToken"]; var bot = new Telegram.Bot.TelegramBotClient(accessToken); // Set up webhook string webhookUrl = Configuration["Settings:webhookUrl"]; int maxConnections = int.Parse(Configuration["Settings:maxConnections"]); bot.SetWebhookAsync(webhookUrl, maxConnections: maxConnections, allowedUpdates: new [] { Telegram.Bot.Types.Enums.UpdateType.Message, Telegram.Bot.Types.Enums.UpdateType.CallbackQuery }); services.AddScoped <ITelegramBotClient>(client => bot); var storageConnectionString = Configuration["Settings:storageConnectionString"]; var storage = new StorageAzure(storageConnectionString); services.AddScoped <IStorageAzure>(client => storage); services.AddScoped <IStorage, StorageAzureAdapter>(); services.AddScoped <ISubscribesDataAccess, SubscribesDataAccess>(); services.AddScoped <ISubscribesDataAccess, SubscribesDataAccess>(); services.AddScoped <ISettingsDataAccess, SettingsDataAccess>(); services.AddScoped <IDataAccess, DataAccess>(); services.AddScoped <ISettings, Settings>(); //services.AddHostedService<ScheduleTask>(); services.AddSingleton <IHostedService, ScheduleTask>(); }
public async void testApiAsync() { Bot = new Telegram.Bot.TelegramBotClient("349066899:AAFiqkKRiwbO8Rgc1bLdANgLqWpbiJvfK3U"); var me = await Bot.GetMeAsync(); System.Console.WriteLine("Hello my name is " + me.FirstName); while (true) { try { var updates = await GetUpdatesAsync(); foreach (var update in updates) { if (updateDictionary.ContainsKey(update.Message.Chat.Id)) { updateDictionary[update.Message.Chat.Id] = update; } else { updateDictionary.Add(update.Message.Chat.Id, update); } _offset = update.Id + 1; } foreach (var key in updateDictionary) { if (key.Value.Message.Text != null && key.Value.Message.Text != String.Empty) { Console.WriteLine(updates.Length); } OnMessageReceived?.Invoke(key.Value.Message); } updateDictionary = new Dictionary <long, Update>(); } catch (Exception) { Thread.Sleep(10000); } } }
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 } }
public TelegramManager(AppDbContext dbContext, ITaskRepository taskRepository, IExecutorRepository executorRepository) { TelegramSettings telegramSettings = new TelegramSettings { APIKey = "1013744878:AAF5qFktlgyBpXeVp-KXpWyb4dnTqUbSPN4" }; _botClient = new Telegram.Bot.TelegramBotClient(telegramSettings.APIKey); NLog.LogManager.GetCurrentClassLogger().Info($"Telegram bot created:{telegramSettings.APIKey}"); _taskRepository = taskRepository; _executorRepository = executorRepository; _dbContext = dbContext; _botClient.OnCallbackQuery += _botClient_OnCallbackQuery; _botClient.OnReceiveError += _botClient_OnReceiveError; _botClient.OnReceiveGeneralError += _botClient_OnReceiveGeneralError; _botClient.OnMessage += _botClient_OnMessage; _botClient.OnInlineResultChosen += _botClient_OnInlineResultChosen; _botClient.StartReceiving(Array.Empty <UpdateType>()); }
public DwellerBot(Settings settings) { // move to container CommandService = new CommandService(BotName); _rng = new Random(); // Get bot api token _bot = new TelegramBotClient(settings.keys.First(x => x.name == "dwellerBotKey").value); Offset = 0; CommandsProcessed = 0; ErrorCount = 0; LaunchTime = DateTime.Now.AddHours(3); CommandService.RegisterCommands(new Dictionary<string, ICommand> { {@"/debug", new DebugCommand(_bot, this)}, {@"/rate", new RateNbrbCommand(_bot)}, {@"/askstason", new AskStasonCommand(_bot, settings.paths.paths.First(x => x.name == "askStasonResponsesPath").value)}, {@"/weather", new WeatherCommand(_bot, settings.keys.First(x => x.name == "openWeatherKey").value)}, { @"/reaction", new ReactionCommand( _bot, settings.paths.pathGroups.First(x => x.name == "reactionImagePaths").paths.Select(x => x.value).ToList(), settings.paths.paths.First(x => x.name == "reactionImageCachePath").value ) }, {@"/rtd", new RtdCommand(_bot)}, {@"/featurerequest", new FeatureRequestCommand(_bot, settings.paths.paths.First(x => x.name == "featureRequestsPath").value)}, {@"/bash", new BashimCommand(_bot)}, {@"/savestate", new SaveStateCommand(_bot, this)}, {@"/shutdown", new ShutdownCommand(_bot, this)}, {@"/changelog", new ChangelogCommand(_bot)} }); CommandService.LoadCommandStates(); }
private void bnSearch_Click(object sender, EventArgs e) { if (txtAPIKey.Text == "") { return; } MessageBox.Show("This will start the Bot for 10 seconds and saves the chat id from the first message arrived.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); tmSearch.Enabled = true; bnSearch.Enabled = false; TelegramBotClient = new TelegramBotClient(txtAPIKey.Text); __cancellationTokenSource = new CancellationTokenSource(); var receiverOptions = new ReceiverOptions { AllowedUpdates = { } // receive all update types }; TelegramBotClient.StartReceiving(HandleUpdateAsync, HandleErrorAsync, receiverOptions, __cancellationTokenSource.Token); }
public CommandBase(TelegramBotClient bot) { Bot = bot; }
public BashimCommand(TelegramBotClient bot):base(bot) { }
public RateCommand(TelegramBotClient bot):base(bot) { ; }
public ShutdownCommand(TelegramBotClient bot, DwellerBot dwellerBot):base(bot) { _dwellerBot = dwellerBot; }
public RtdCommand(TelegramBotClient bot):base(bot) { _rng = new Random(); }
public WeatherCommand(TelegramBotClient bot, string apiKey):base(bot) { _apiKey = apiKey; }
public TelegramActor() { _stream = Context.System.EventStream; _bot = BuildBot(); Receive <RequestCookie>(x => HanldeRequestCookie(x)); }
public FeatureRequestCommand(TelegramBotClient bot, string featureRequestsFilePath):base(bot) { _featureRequestsFilePath = featureRequestsFilePath; _requests = new Dictionary<int, string>(); }
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)); } }
public DebugCommand(TelegramBotClient bot, DwellerBot dwellerBot):base(bot) { _dwellerBot = dwellerBot; }
static async void DelayedMessage(TelegramBotClient bot, long chatId, string message, int minutesToWait) { await Task.Delay(minutesToWait * 60000); await bot.SendTextMessageAsync(chatId, message); }
public SaveStateCommand(TelegramBotClient bot, DwellerBot dwellerBot):base(bot) { _dwellerBot = dwellerBot; }
static async Task MainLoop() { // Read Configuration var telegramKey = ConfigurationManager.AppSettings["TelegramKey"]; // Start Bot var bot = new TelegramBotClient(telegramKey); var me = await bot.GetMeAsync(); Console.WriteLine(me.Username + " started at " + DateTime.Now); var offset = 0; while (true) { var updates = new Update[0]; try { updates = await bot.GetUpdatesAsync(offset); } catch (TaskCanceledException) { // Don't care } catch (Exception ex) { Console.WriteLine("ERROR WHILE GETTIGN UPDATES - " + ex); } foreach (var update in updates) { offset = update.Id + 1; ProcessUpdate(bot, update, me); } await Task.Delay(1000); } }