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 void SavePVFValues(IList<PVFItem> inserted, IList<PVFItem> updated, IList<PVFItem> deleted) { using (TransactionScope scope = new TransactionScope()) { foreach (var item in inserted) { Insert<PVFItem> insert = new Insert<PVFItem>("PeakValleyFlat", item); insert.AddExcludeField("ID"); dataFactory.Save<PVFItem>(insert); } foreach (var item1 in updated) { Update<PVFItem> update = new Update<PVFItem>("PeakValleyFlat", item1); update.AddCriterion("ID", "ID", item1.ID, SqlServerDataAdapter.Infrastruction.CriteriaOperator.Equal); update.AddExcludeField("ID"); dataFactory.Save<PVFItem>(update); } foreach (var item2 in deleted) { Delete delete = new Delete("PeakValleyFlat"); delete.AddCriterions("ID", "ID",item2.ID, SqlServerDataAdapter.Infrastruction.CriteriaOperator.Equal); dataFactory.Remove(delete); } scope.Complete(); } }
public bool Equals(Update update) { bool results = false; if ((this.TopPatchId != null) && (update.TopPatchId != null)) { if (this.TopPatchId.Equals(update.TopPatchId)) { results = true; } } else if ((this.VendorId != null) && (update.VendorId != null)) { if ((this.VendorId.Equals(update.VendorId)) && (this.Name.Equals(update.Name))) { results = true; } } else { if (this.Name.Equals(update.Name)) { results = true; } } return results; }
public string ChangeFormulaYear(string tableName,IList<FormulaYear> deleteItems, IList<FormulaYear> updateItems, IList<FormulaYear> insertItems) { try { foreach (var item in deleteItems) { Delete delete = new Delete(tableName); delete.AddCriterions("KeyID","myKeyID", item.KeyID, CriteriaOperator.Equal); delete.AddCriterions("ID","myID", item.ID, CriteriaOperator.Equal); delete.AddSqlOperator(SqlOperator.AND); dataFactory.Remove(delete); } foreach (var item in updateItems) { Update<FormulaYear> update = new Update<FormulaYear>(tableName, item); update.AddCriterion("KeyID", "myKeyID",item.KeyID, CriteriaOperator.Equal); update.AddCriterion("ID", "myID",item.ID, CriteriaOperator.Equal); update.AddSqlOperator(SqlOperator.AND); update.AddExcludeField("Id"); dataFactory.Save<FormulaYear>(update); } foreach (var item in insertItems) { Insert<FormulaYear> insert = new Insert<FormulaYear>(tableName, item); insert.AddExcludeField("Id"); dataFactory.Save<FormulaYear>(insert); } } catch { return "0"; } return "1"; }
public MobileGame(AndroidContent.Context context, Setup setupDelegate, Update updateDelegate) : base(context) { window = new Window(this); this.setupDelegate = setupDelegate; this.updateDelegate = updateDelegate; }
public static string Download(Update update, Action<int> progressChanged) { var tmpFile = Path.GetTempFileName(); var waiter = new ManualResetEvent(false); Exception ex = null; var wc = new WebClient(); wc.DownloadProgressChanged += (sender, e) => progressChanged(e.ProgressPercentage); wc.DownloadFileCompleted += (sender, e) => { ex = e.Error; waiter.Set(); }; wc.Headers.Add(HttpRequestHeader.UserAgent, "Azyotter.Updater v" + AssemblyUtil.GetInformationalVersion()); wc.DownloadFileAsync(update.Uri, tmpFile); waiter.WaitOne(); if (ex != null) { File.Delete(tmpFile); throw ex; } return tmpFile; }
public UpdateWindow(Update update) { InitializeComponent(); _update = update; updateInfolbl.Text = update.Name; TerminateYnoteProcess(); PopulateUpdateFiles(); }
public void Update_SimpleSqlCheck() { SubSonic.SqlQuery u = new Update(Product.Schema).Set("UnitPrice").EqualTo(100).Where("productid").IsEqualTo(1); string sql = u.BuildSqlStatement(); //Assert.Fail("sql = " + sql); //Assert.IsTrue(sql == "UPDATE [dbo].[Products] SET [UnitPrice]=@up_UnitPrice\r\n WHERE [dbo].[Products].[ProductID] = @ProductID0\r\n"); Assert.IsTrue(sql == "UPDATE `main`.`Products` SET `UnitPrice`=@up_UnitPrice\r\n WHERE `main`.`Products`.`ProductID` = @ProductID0\r\n"); }
private void HandleNew(Update update) { Debug.Assert(update != null); if (update.Message == null) return; Console.WriteLine($" >{update.Message?.From.FirstName ?? "<no fname>"}: {update.Message.Text}"); _pluginOne.Handle(new MessageContext { Update = update }); }
public void ReleasePlayerTest(int playerID) { //Release Player to Free Agency var repo = new Update(); repo.ReleasePlayer(playerID); //Get Free Agency players and check for released player var readRepo = new Read(); var players = readRepo.GetFreeAgents(); var player = players.FirstOrDefault(p => p.PlayerID == playerID); Assert.AreEqual(player.PlayerID, playerID); }
public void Update_Simple() { int records = new Update(Product.Schema).Set("UnitPrice").EqualTo(100).Where("productid").IsEqualTo(1).Execute(); Assert.IsTrue(records == 1); //pull it back out Product p = new Product(1); Assert.IsTrue(p.UnitPrice == 100); //reset it to 50 p.UnitPrice = 50; p.Save("unit test"); }
/// <summary> /// Generate the form, load configs, show initial settings if needed. /// </summary> /// <param name="configs">Strings passed on the commandline</param> public FrmGlobalStatus(string[] commands) { InitializeComponent(); helper.UpdateSettings(); // if this is the first start: show settings if (Properties.Settings.Default.firstStart) { Properties.Settings.Default.firstStart = false; Properties.Settings.Default.Save(); ShowSettings(true); } ReadConfigs(); niIcon.Icon = Properties.Resources.TRAY_Disconnected; bool checkupdate = false; TimeSpan ts = Properties.Settings.Default.lastUpdateCheck - DateTime.Now; if (Properties.Settings.Default.searchUpdate == 0 || (ts.Days > 7 && Properties.Settings.Default.searchUpdate == 1) || (ts.Days > 30 && Properties.Settings.Default.searchUpdate == 2)) { checkupdate = true; Properties.Settings.Default.lastUpdateCheck = DateTime.Now; Properties.Settings.Default.Save(); } if (checkupdate) { Update u = new Update(true, this); if (u.checkUpdate()) { niIcon.ShowBalloonTip(5000, Program.res.GetString("QUICKINFO_Update"), Program.res.GetString("QUICKINFO_Update_More"), ToolTipIcon.Info); } } m_simpleComm.ReceivedLines += new EventHandler<SimpleComm.ReceivedLinesEventArgs>( m_simpleComm_ReceivedLines); parseCommandLine(commands); if(Properties.Settings.Default.allowRemoteControl) m_simpleComm.startServer(); }
internal void OnLoad(EventArgs args) { this._menu= new Menu(); this.spells=new Spells(); this._update=new Update(); this._draw=new Drawings(); this.DmgIndicator=new DamageIndicator(); DmgIndicator.Initialize(this); this.misc=new Misc(); this.targetSelected = new MyTs(); Gapcloser.OnGapcloser += this.OnGapCloser; EloBuddy.Game.OnUpdate += this.Onupdate; EloBuddy.Drawing.OnDraw += this.Ondraw; }
public static void UpdateProjectsInDB(List<ChildProject> cProjects) { var userConnection = TerrasoftApi.GetuserConnection(); foreach (var item in cProjects) { Update update = new Update(userConnection, "Project") .Set("StartDate", Column.Const(item.StartDate)) .Set("EndDate", Column.Const(item.EndDate)) .Where("Id").IsEqual(Column.Const(item.ChildId)) as Update; update.BuildParametersAsValue = true; using (var dbExecutor = userConnection.EnsureDBConnection()) { try { dbExecutor.StartTransaction(); var affectedRowsCount = update.Execute(dbExecutor); dbExecutor.CommitTransaction(); } catch (Exception ex) { dbExecutor.RollbackTransaction(); } } } var rootProjectId = cProjects[0].GetRootId(); var endDate = cProjects.Last().EndDate; Update updateRoot = new Update(userConnection, "Project") .Set("EndDate", Column.Const(endDate)) .Where("Id").IsEqual(Column.Const(rootProjectId)) as Update; updateRoot.BuildParametersAsValue = true; using (var dbExecutor = userConnection.EnsureDBConnection()) { try { dbExecutor.StartTransaction(); var affectedRowsCount = updateRoot.Execute(dbExecutor); dbExecutor.CommitTransaction(); } catch (Exception ex) { dbExecutor.RollbackTransaction(); } } }
static void Main() { System.Diagnostics.Process.Start("D:\\Solicitação de Prontuarios\\Sistema de Solicitação de Prontuários\\pastaDTI.bat"); Update updatando = new Update(); updatando.up(); if (updatando.Yn == true) { Environment.Exit(1); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MenuUpa()); }
public Task Update(Update value) { //Console.WriteLine("enter Update"); WithConnection( c => { value.ExecuteNonQuery(c); } ); return Task.FromResult(default(object)); }
public UpdateForm(Update.UpdateInfo updateinfo) { InitializeComponent(); AddToUpdate("Update Version: " + updateinfo.UpdateVersion); string[] changeLog = updateinfo.UpdateText.Split('`'); AddToUpdate("Changelog:"); for (int i = 0; i < changeLog.Length; i++) { if (changeLog[i] == "") { AddToUpdate(""); continue; } AddToUpdate("-" + changeLog[i]); } }
public Update CheckOperators(string version) { Update upd = new Update(); if (Singleton.Instance.LatestVersion == version) { upd.UpToDate = true; } else { upd.UpToDate = false; upd.OperatorList = Singleton.Instance.GatewayTable.Keys.ToArray<string>(); upd.NewVersion = Singleton.Instance.LatestVersion; } return upd; }
public void Acc_Update_Expression() { Product p = new Product(1); p.UnitPrice = 50; p.Save("unit test"); int records = new Update(Product.Schema) .SetExpression("UnitPrice").EqualTo("UnitPrice * 3") .Where("productid").IsEqualTo(1) .Execute(); Assert.IsTrue(records == 1); //pull it back out p = new Product(1); Assert.IsTrue(p.UnitPrice == 150); //reset it to 50 p.UnitPrice = 50; p.Save("unit test"); }
public Update CheckOperators(string version) { Update upd = new Update(); switch (version) { case "V07051430": upd.NewVersion = DateTime.Now.ToString(Settings.VERSION_PATTERN); upd.OperatorList = new string[] { "SmartBelize", "CubacelCuba", "MobitelSriLanka" }; upd.UpToDate = false; break; case "V06071434": upd.UpToDate = true; break; case "V05061020": upd.NewVersion = DateTime.Now.ToString(Settings.VERSION_PATTERN); upd.OperatorList = new string[] { "SmartBelize", "CubacelCuba", "OrangeDominicanRepublic" }; upd.UpToDate = false; break; } return upd; }
public static List<double> ComputeGains(ref Solution p1, ref Solution p2, ref Solution p3, ref Solution p12, ref Solution p23, ref Solution p31, ref Solution p123, int max_iters = 30, Update update = null, VrpSolver solver = null) { if (solver == null) solver = DefaultSolver; ///// for (var i = 0; i < max_iters; ++i) { p1 = solver.Solve(p1.Problem, p1); p2 = solver.Solve(p2.Problem, p2); p3 = solver.Solve(p3.Problem, p3); p12 = solver.Solve(p12.Problem, p12); p23 = solver.Solve(p23.Problem, p23); p31 = solver.Solve(p31.Problem, p31); p123 = solver.Solve(p123.Problem, p123); var v1 = p1.TotalDistance(); var v2 = p2.TotalDistance(); var v3 = p3.TotalDistance(); var v12 = p12.TotalDistance(); var v23 = p23.TotalDistance(); var v31 = p31.TotalDistance(); var v123 = p123.TotalDistance(); var phi1 = 1.0 * 3.0 / v1 + 1.0 / 6.0 * (v12 - v2) + 1.0 / 6.0 * (v31 - v3) + 1.0 / 3.0 * (v123 - v23); var phi2 = 1.0 * 3.0 / v2 + 1.0 / 6.0 * (v23 - v3) + 1.0 / 6.0 * (v12 - v1) + 1.0 / 3.0 * (v123 - v31); var phi3 = 1.0 * 3.0 / v3 + 1.0 / 6.0 * (v31 - v1) + 1.0 / 6.0 * (v23 - v2) + 1.0 / 3.0 * (v123 - v12); p1.Phi = v1 - phi1; p2.Phi = v2 - phi2; p3.Phi = v3 - phi3; update(max_iters, i); } return null; }
public async Task<string> DownloadUpdate(Update updt, IProgress<Tuple<double, long>> prog) { var response = (await this.Client.GetAsync(updt.DownloadUrl, HttpCompletionOption.ResponseHeadersRead)).Content; var tmpFile = System.IO.Path.GetTempPath() + "ArmAUIEditor\\" + updt.DownloadName; System.IO.Directory.CreateDirectory(System.IO.Path.GetTempPath() + "ArmAUIEditor\\"); double curLen = 0; using (var fStream = System.IO.File.Create(tmpFile)) { using (var hStream = await response.ReadAsStreamAsync()) { while(true) { byte[] buffer = new byte[256]; var readBytes = hStream.Read(buffer, 0, buffer.Length); if (readBytes == 0) break; fStream.Write(buffer, 0, readBytes); curLen += readBytes; prog.Report(new Tuple<double, long>(curLen, response.Headers.ContentLength.Value)); } } } return tmpFile; }
private void UpdateApplication(object sender, EventArgs e) { var project = vsMonitorSelection.GetActiveProject(); if (project == null) return; var cloudGuid = GetCurrentCloudGuid(project); var projectDirectories = GetProjectDirectories(project); Messenger.Default.Register<NotificationMessageAction<Guid>>(this, message => { if (message.Notification.Equals(Messages.SetUpdateAppData)) message.Execute(cloudGuid); }); Messenger.Default.Register<NotificationMessageAction<string>>(this, message => { if (message.Notification.Equals(Messages.SetPushAppDirectory)) message.Execute(projectDirectories.DeployFromPath); }); var window = new Update(); var helper = new WindowInteropHelper(window); helper.Owner = (IntPtr)(dte.MainWindow.HWnd); var result = window.ShowDialog(); if (!result.GetValueOrDefault()) return; UpdateViewModel modelData = null; Messenger.Default.Send(new NotificationMessageAction<UpdateViewModel>(Messages.GetUpdateAppData, model => modelData = model)); SetCurrentCloudGuid(project, modelData.SelectedCloud.ID); PerformAction("Update Application", project, modelData.SelectedCloud, projectDirectories, (c, d) => { c.Update(modelData.SelectedApplication.Name, d); c.Restart(new Application {Name = modelData.SelectedApplication.Name}); }); }
public CommandLogicException(Update update, string message) { Update = update; _message = message; }
public static void Reset() { Scores = new SafeDictionary<uint, Guild>(100); LeftGate.Mesh = (ushort)(240 + LeftGate.Mesh % 10); RightGate.Mesh = (ushort)(270 + LeftGate.Mesh % 10); LeftGate.Hitpoints = LeftGate.MaxHitpoints; RightGate.Hitpoints = RightGate.MaxHitpoints; Pole.Hitpoints = Pole.MaxHitpoints; Update upd = new Update(true); upd.UID = LeftGate.UID; upd.Append(Update.Mesh, LeftGate.Mesh); upd.Append(Update.Hitpoints, LeftGate.Hitpoints); ServerBase.Kernel.SendWorldMessage(upd, ServerBase.Kernel.GamePool.Values, (ushort)1038); upd.Clear(); upd.UID = RightGate.UID; upd.Append(Update.Mesh, RightGate.Mesh); upd.Append(Update.Hitpoints, RightGate.Hitpoints); ServerBase.Kernel.SendWorldMessage(upd, ServerBase.Kernel.GamePool.Values, (ushort)1038); foreach (Guild guild in ServerBase.Kernel.Guilds.Values) { guild.WarScore = 0; } IsWar = true; }
public static void Start() { Scores = new SafeDictionary<uint, Guild>(100); StartTime = DateTime.Now; LeftGate.Mesh = (ushort)(240 + LeftGate.Mesh % 10); RightGate.Mesh = (ushort)(270 + LeftGate.Mesh % 10); ServerBase.Kernel.SendWorldMessage(new Message("Guild war has began!", System.Drawing.Color.Red, Message.Center), ServerBase.Kernel.GamePool.Values); FirstRound = true; foreach (Guild guild in ServerBase.Kernel.Guilds.Values) { guild.WarScore = 0; } Update upd = new Update(true); upd.UID = LeftGate.UID; upd.Append(Update.Mesh, LeftGate.Mesh); upd.Append(Update.Hitpoints, LeftGate.Hitpoints); ServerBase.Kernel.SendWorldMessage(upd, ServerBase.Kernel.GamePool.Values, (ushort)1038); upd.Clear(); upd.UID = RightGate.UID; upd.Append(Update.Mesh, RightGate.Mesh); upd.Append(Update.Hitpoints, RightGate.Hitpoints); ServerBase.Kernel.SendWorldMessage(upd, ServerBase.Kernel.GamePool.Values, (ushort)1038); IsWar = true; }
/// <summary> /// Register /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_register_Click(object sender, RoutedEventArgs e) { try { // gender string gender = (bool)rb_male.IsChecked ? "Male" : "Female"; // customer object Customer customer = new Customer() { FirstName = tb_firstName.Text, LastName = tb_lastName.Text, Address = tb_address.Text, Phone = tb_phoneNumber.Text, BirthDate = dp_birth.Text, Gender = gender, EnmergencyName = tb_enName.Text, EnmergencyRelationship = tb_enRelation.Text, EnmergencyPhone = tb_enPhone.Text }; // Register as new customer if (editCustomer == null) { // create new database insert Database db = new Database(); Insert newCustomer = new Insert(); MySqlConnection conn = db.CreateConnection(); bool status = false; // open connection try { // customer object, it uses SETTER which will throw exception if empty conn.Open(); status = newCustomer.AddCustomer(db.CreateCommand(conn), customer); conn.Close(); if (status) { MessageBox.Show("Customer Added"); clear(); } else { MessageBox.Show("Fail to add customer"); } } catch (CustomerException c) { MessageBox.Show("Required: " + c.Message.ToString()); } catch (Exception ex) { MessageBox.Show("Database: " + ex.Message.ToString()); } // Edit the current customer in database } else { // call update on database Database db = new Database(); Update update = new Update(); MySqlConnection conn = db.CreateConnection(); conn.Open(); // set the uid for editing customer.Uid = editCustomer.Uid; if (update.EditCustomer(db.CreateCommand(conn), customer)) { MessageBox.Show("Customer Edited"); this.Close(); } else { MessageBox.Show("Fail to update information."); } conn.Close(); } } catch (Exception ex) { MessageBox.Show("Edit error: " + ex.Message.ToString()); } }
public static CommandLogicException AsCommandLogicException(this string self, Update update) => new CommandLogicException(update, self);
public void SendUpdates( NativeArray <ArchetypeChunk> chunkArray, ComponentSystemBase system, EntityManager entityManager, ComponentUpdateSystem componentUpdateSystem) { Profiler.BeginSample("ExhaustiveMapKey"); var spatialOSEntityType = system.GetArchetypeChunkComponentType <SpatialEntityId>(true); var componentType = system.GetArchetypeChunkComponentType <global::Improbable.TestSchema.ExhaustiveMapKey.Component>(); var authorityType = system.GetArchetypeChunkSharedComponentType <ComponentAuthority>(); foreach (var chunk in chunkArray) { var entityIdArray = chunk.GetNativeArray(spatialOSEntityType); var componentArray = chunk.GetNativeArray(componentType); var authorityIndex = chunk.GetSharedComponentIndex(authorityType); if (!entityManager.GetSharedComponentData <ComponentAuthority>(authorityIndex).HasAuthority) { continue; } for (var i = 0; i < componentArray.Length; i++) { var data = componentArray[i]; if (data.IsDataDirty()) { Update update = new Update(); if (data.IsDataDirty(0)) { update.Field1 = data.Field1; } if (data.IsDataDirty(1)) { update.Field2 = data.Field2; } if (data.IsDataDirty(2)) { update.Field3 = data.Field3; } if (data.IsDataDirty(3)) { update.Field4 = data.Field4; } if (data.IsDataDirty(4)) { update.Field5 = data.Field5; } if (data.IsDataDirty(5)) { update.Field6 = data.Field6; } if (data.IsDataDirty(6)) { update.Field7 = data.Field7; } if (data.IsDataDirty(7)) { update.Field8 = data.Field8; } if (data.IsDataDirty(8)) { update.Field9 = data.Field9; } if (data.IsDataDirty(9)) { update.Field10 = data.Field10; } if (data.IsDataDirty(10)) { update.Field11 = data.Field11; } if (data.IsDataDirty(11)) { update.Field12 = data.Field12; } if (data.IsDataDirty(12)) { update.Field13 = data.Field13; } if (data.IsDataDirty(13)) { update.Field14 = data.Field14; } if (data.IsDataDirty(14)) { update.Field15 = data.Field15; } if (data.IsDataDirty(15)) { update.Field16 = data.Field16; } if (data.IsDataDirty(16)) { update.Field17 = data.Field17; } if (data.IsDataDirty(17)) { update.Field18 = data.Field18; } componentUpdateSystem.SendUpdate(in update, entityIdArray[i].EntityId); data.MarkDataClean(); componentArray[i] = data; } } } Profiler.EndSample(); }
public void SendUpdates( NativeArray <ArchetypeChunk> chunkArray, ComponentSystemBase system, EntityManager entityManager, ComponentUpdateSystem componentUpdateSystem) { using (componentMarker.Auto()) { var spatialOSEntityType = system.GetArchetypeChunkComponentType <SpatialEntityId>(true); var componentType = system.GetArchetypeChunkComponentType <global::Improbable.TestSchema.ExhaustiveRepeated.Component>(); foreach (var chunk in chunkArray) { var entityIdArray = chunk.GetNativeArray(spatialOSEntityType); var componentArray = chunk.GetNativeArray(componentType); for (var i = 0; i < componentArray.Length; i++) { var data = componentArray[i]; if (data.IsDataDirty()) { var update = new Update(); if (data.IsDataDirty(0)) { update.Field1 = data.Field1; } if (data.IsDataDirty(1)) { update.Field2 = data.Field2; } if (data.IsDataDirty(2)) { update.Field3 = data.Field3; } if (data.IsDataDirty(3)) { update.Field4 = data.Field4; } if (data.IsDataDirty(4)) { update.Field5 = data.Field5; } if (data.IsDataDirty(5)) { update.Field6 = data.Field6; } if (data.IsDataDirty(6)) { update.Field7 = data.Field7; } if (data.IsDataDirty(7)) { update.Field8 = data.Field8; } if (data.IsDataDirty(8)) { update.Field9 = data.Field9; } if (data.IsDataDirty(9)) { update.Field10 = data.Field10; } if (data.IsDataDirty(10)) { update.Field11 = data.Field11; } if (data.IsDataDirty(11)) { update.Field12 = data.Field12; } if (data.IsDataDirty(12)) { update.Field13 = data.Field13; } if (data.IsDataDirty(13)) { update.Field14 = data.Field14; } if (data.IsDataDirty(14)) { update.Field15 = data.Field15; } if (data.IsDataDirty(15)) { update.Field16 = data.Field16; } if (data.IsDataDirty(16)) { update.Field17 = data.Field17; } if (data.IsDataDirty(17)) { update.Field18 = data.Field18; } componentUpdateSystem.SendUpdate(in update, entityIdArray[i].EntityId); data.MarkDataClean(); componentArray[i] = data; } } } } }
public void NewsDisableAll(object o, System.EventArgs e) { if (ShowNewsAdmin) { Update u = new Update(); u.Changes.Add(new Assign(Thread.Columns.IsNews, false)); u.Changes.Add(new Assign(Thread.Columns.NewsLevel, 0)); u.Changes.Add(new Assign(Thread.Columns.NewsModeratedByUsrK, Usr.Current.K)); u.Changes.Add(new Assign(Thread.Columns.NewsModerationDateTime, DateTime.Now)); u.Changes.Add(new Assign(Thread.Columns.NewsStatus, Thread.NewsStatusEnum.Done)); u.Where = new And( new Q(Thread.Columns.NewsStatus, Thread.NewsStatusEnum.Recommended), new Q(Thread.Columns.GroupK, CurrentGroup.K)); u.Table = TablesEnum.Thread; u.Run(); // Set NewsThreadsPage = 1, fixes bug when paged to any other page and disabling all news items. Neil Sankey on 8/8/07 NewsThreadsPage = 1; BindNewsDataGrid(); NewsThreadPanel.Visible = false; } }
/// <summary> /// Check for updates and new messages. /// </summary> /// <returns>A list of updates.</returns> public List<Update> Poll() { if (umqid == null) return null; String response = steamRequest("ISteamWebUserPresenceOAuth/Poll/v0001", "?access_token=" + accessToken + "&umqid=" + umqid + "&message=" + message); if (response != null) { JObject data = JObject.Parse(response); if (((String)data["error"]).Equals("OK")) { message = (int)data["messagelast"]; List<Update> updates = new List<Update>(); foreach (JObject info in data["messages"]) { Update update = new Update(); update.timestamp = unixTimestamp((long)info["timestamp"]); update.origin = (String)info["steamid_from"]; String type = (String)info["type"]; if (type.Equals("saytext") || type.Equals("my_saytext") || type.Equals("emote")) { update.type = type.Equals("emote") ? UpdateType.Emote : UpdateType.Message; update.message = (String)info["text"]; update.localMessage = type.Equals("my_saytext"); OnNewMessage(new SteamEvent(update)); } else if (type.Equals("typing")) { update.type = UpdateType.TypingNotification; update.message = (String)info["text"]; // Not sure if this is useful OnTyping(new SteamEvent(update)); } else if (type.Equals("personastate")) { update.type = UpdateType.UserUpdate; update.status = (UserStatus)(int)info["persona_state"]; update.nick = (String)info["persona_name"]; OnFriendStateChange(new SteamEvent(update)); } else { continue; } updates.Add(update); } return updates; } else { return null; } } else { return null; } }
public static void Init() { try { if (Global.Reset.Enabled) { Reset.Force(Global.Name, Global.Reset.MaxAge); } AppDomain.CurrentDomain.UnhandledException += delegate(object sender, UnhandledExceptionEventArgs eventArgs) { try { var ex = sender as Exception; if (ex != null) { Global.Logger.AddItem(new LogItem(ex)); } } catch (Exception ex) { Console.WriteLine(ex); } }; #region GameObjects GameObjects.Initialize(); #endregion GameObjects Global.SFX = new SFXHealth(); var app = new App(); CustomEvents.Game.OnGameLoad += delegate { Global.Features.AddRange( new List <IChild> { new Health(app) }); foreach (var feature in Global.Features) { try { feature.HandleEvents(); } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } } try { Update.Check( Global.Name, Assembly.GetExecutingAssembly().GetName().Version, Global.UpdatePath, 10000); } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } }; } catch (Exception ex) { Global.Logger.AddItem(new LogItem(ex)); } }
public async Task DeleteChecklistOwnership(DeleteChecklistRequest request) { var filter = Filter.Eq(x => x.Id, request.Auth.Id); var update = Update.PullFilter(x => x.Checklists, x => x.ChecklistId == request.ChecklistId && x.IsOwned); await Collection.UpdateOneAsync(filter, update); }
public Measurement(Update outcome, long latencyInTicks) { Update = outcome; LatencyMs = latencyInTicks / 10000d; TimeStamp = DateTime.UtcNow; }
protected override void Loaded(BehaviorLoadedEventArgs args) { args.TrackSubscription(Update.Where(_ => Target != null).Subscribe(OnUpdate)); }
public static void RestoreAccount(Update u, string[] args) { var score = 100; var result = ""; int oldid, newid; var param = args[1].Split(' '); if (!int.TryParse(param[0], out oldid) || !int.TryParse(param[1], out newid)) { //fail Send("usage: /restore <oldid> <newid>", u.Message.Chat.Id); return; } using (var db = new WWContext()) { var oldP = db.Players.FirstOrDefault(x => x.TelegramId == oldid); var newP = db.Players.FirstOrDefault(x => x.TelegramId == newid); if (oldP == null || newP == null) { Send("Account not found in database", u.Message.Chat.Id); return; } if (db.GlobalBans.Any(x => x.TelegramId == oldid)) { Send("Old account was global banned!", u.Message.Chat.Id); return; } if (oldid > newid || oldP.Id > newP.Id) { score -= 30; result += "Old account given is newer than new account\n"; } if (oldP.GamePlayers.Max(x => x.GameId) > newP.GamePlayers.Min(x => x.GameId)) { score -= 30; result += "Account games overlap - old account has played a game since new account started\n"; } //TODO Check groups played on old account vs new account var oldGrp = (from grp in db.Groups join g in db.Games on grp.Id equals g.GrpId join gp in db.GamePlayers on g.Id equals gp.GameId where gp.PlayerId == oldP.Id select grp).Distinct(); var newGrp = (from grp in db.Groups join g in db.Games on grp.Id equals g.GrpId join gp in db.GamePlayers on g.Id equals gp.GameId where gp.PlayerId == newP.Id select grp).Distinct(); //compare groups var total = newGrp.Count(); var likeness = newGrp.Count(x => oldGrp.Any(g => g.Id == x.Id)); var groupLike = ((likeness * 100) / total); score -= 20 - ((groupLike * 20) / 100); result += $"Percent of new groups that were in old account: {groupLike}%\n"; //TODO check names (username) likeness var undist = ComputeLevenshtein(oldP.UserName, newP.UserName); var dndist = ComputeLevenshtein(oldP.Name, newP.Name); if (undist == 0) { dndist = 0; } else { score -= (undist + dndist) / 2; result += $"\nLevenshtein Distince:\nUsernames: {undist}\nDisplay name: {dndist}\n\n"; } //TODO check languages set if (oldP.Language != newP.Language) { score -= 10; result += "Account languages are set differently\n"; } //TODO Send a result with the score, and buttons to approve or deny the account restore Send($"{result}Accuracy score: {score}%\n\nDo you want to restore the account?", u.Message.Chat.Id, customMenu: new InlineKeyboardMarkup(new[] { new InlineKeyboardButton("Yes", $"restore|{oldP.TelegramId}|{newP.TelegramId}"), new InlineKeyboardButton("No", "restore|no") })); } }
public SteamEvent(Update u = null) { update = u; }
/// <summary> /// Context Menu 右鍵->編輯 /// </summary> private void rmenuEdit_Click(object sender, RoutedEventArgs e) { // 每次編輯都要確認權限 if (!CheckRankOrActivity()) { return; } if (lvwClassify.SelectedItems.Count != 1) { return; } // 只能選取才編輯, 因為最後一層 File 不能編輯所以不用處理 List Mode else if (_isTileView) { StringBuilder pathServer = new StringBuilder(); StringBuilder pathId = new StringBuilder(); pathServer.Append(_ftpPath); pathId.Append(_idPath); Tile item = lvwClassify.SelectedItem as Tile; Dictionary<string, string> tag = item.Tag as Dictionary<string, string>; pathServer.Append(tag["Name"]); pathId.Append(tag["Id"]); Update getInput = new Update(400, 200, pathServer.ToString(), tag["NickName"]); getInput.ShowDialog(); if (getInput.IsDone) { string newNickName = getInput.NickName; string newSystemName = getInput.SystemName; string rebuildPath = getInput.NewPath; string rebuildPathId = pathId.ToString(); if (getInput.ClassifyId > 0) { rebuildPathId = "/" + getInput.ClassifyId + pathId.ToString().Substring(pathId.ToString().LastIndexOf('/')); } // 編輯更新欄位 RenameFolder(pathServer.ToString(), rebuildPathId, rebuildPath, newNickName); } } }
public static void RemAchievement(Update u, string[] args) { //get the user to add the achievement to //first, try by reply var id = 0; var achIndex = 0; var param = args[1].Split(' '); if (u.Message.ReplyToMessage != null) { var m = u.Message.ReplyToMessage; while (m.ReplyToMessage != null) { m = m.ReplyToMessage; } //check for forwarded message id = m.From.Id; if (m.ForwardFrom != null) { id = m.ForwardFrom.Id; } } else { //ok, check for a user mention var e = u.Message.Entities?.FirstOrDefault(); if (e != null) { switch (e.Type) { case MessageEntityType.Mention: //get user var username = u.Message.Text.Substring(e.Offset + 1, e.Length - 1); using (var db = new WWContext()) { id = db.Players.FirstOrDefault(x => x.UserName == username)?.TelegramId ?? 0; } break; case MessageEntityType.TextMention: id = e.User.Id; break; } achIndex = 1; } } if (id == 0) { //check for arguments then if (int.TryParse(param[0], out id)) { achIndex = 1; } else if (int.TryParse(param[1], out id)) { achIndex = 0; } } if (id != 0) { //try to get the achievement Achievements a; if (Enum.TryParse(param[achIndex], out a)) { //get the player from database using (var db = new WWContext()) { var p = db.Players.FirstOrDefault(x => x.TelegramId == id); if (p != null) { if (p.Achievements == null) { p.Achievements = 0; } var ach = (Achievements)p.Achievements; if (!ach.HasFlag(a)) { return; //no point making another db call if they already have it } ach &= ~a; p.Achievements = (long)ach; db.SaveChanges(); Send($"Achievement {a} removed from {p.Name}", u.Message.Chat.Id); } } } } }
/// <summary> /// Checks for application update /// </summary> private void CheckVersion() { string xmlURL = "https://raw.githubusercontent.com/liinko/FFXIVTexToolsWeb/master/version.xml"; string changeLog = ""; string siteURL = ""; Version v = null; try { using (XmlTextReader reader = new XmlTextReader(xmlURL)) { reader.MoveToContent(); string elementName = ""; if (reader.NodeType == XmlNodeType.Element && reader.Name == "FFXIVTexTools2") { while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { elementName = reader.Name; } else { if (reader.NodeType == XmlNodeType.Text && reader.HasValue) { switch (elementName) { case "version": v = new Version(reader.Value); break; case "url": siteURL = reader.Value; break; case "log": changeLog = reader.Value; break; } } } } } } Version curVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; if (curVersion.CompareTo(v) < 0) { Update up = new Update(); up.Message = "Version: " + v.ToString().Substring(0, 5) + "\n\nChange Log:\n" + changeLog + "\n\nPlease visit the website to download the update."; up.Show(); } } catch (Exception ex) { MessageBox.Show("There was an issue checking for updates. \n" + ex.Message, "Updater Error", MessageBoxButton.OK, MessageBoxImage.None); } }
public async Task <bool> ExecuteAsync(TelegramBotClient botClient, Update update) { try { Conf.Update Latest = Conf.CheckForUpdates(); if (Conf.IsNewerVersionAvailable(Latest)) { string UpdateString = Vars.CurrentLang.Message_UpdateAvailable .Replace("$1", Latest.Latest) .Replace("$2", Latest.Details); await botClient.SendTextMessageAsync( update.Message.From.Id, UpdateString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId); // where difference begins await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateProcessing, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId); // download compiled package Log("Starting update download... (pmcenter_update.zip)", "BOT"); WebClient Downloader = new WebClient(); Downloader.DownloadFile( new Uri(Vars.UpdateArchiveURL), Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); Log("Download complete. Extracting...", "BOT"); using (ZipArchive Zip = ZipFile.OpenRead(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip"))) { foreach (ZipArchiveEntry Entry in Zip.Entries) { Log("Extracting: " + Path.Combine(Vars.AppDirectory, Entry.FullName), "BOT"); Entry.ExtractToFile(Path.Combine(Vars.AppDirectory, Entry.FullName), true); } } if (Vars.CurrentConf.AutoLangUpdate) { Log("Starting automatic language file update...", "BOT"); await Downloader.DownloadFileTaskAsync( new Uri(Vars.CurrentConf.LangURL), Path.Combine(Vars.AppDirectory, "pmcenter_locale.json") ); } Log("Cleaning up temporary files...", "BOT"); System.IO.File.Delete(Path.Combine(Vars.AppDirectory, "pmcenter_update.zip")); await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_UpdateFinalizing, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId); Log("Exiting program... (Let the daemon do the restart job)", "BOT"); try { Environment.Exit(0); return(true); } catch (Exception ex) { Log("Failed to execute restart command: " + ex.ToString(), "BOT", LogLevel.ERROR); return(true); } // end of difference } else { await botClient.SendTextMessageAsync( update.Message.From.Id, Vars.CurrentLang.Message_AlreadyUpToDate .Replace("$1", Latest.Latest) .Replace("$2", Vars.AppVer.ToString()) .Replace("$3", Latest.Details), ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId); return(true); } } catch (Exception ex) { string ErrorString = Vars.CurrentLang.Message_UpdateCheckFailed.Replace("$1", ex.ToString()); await botClient.SendTextMessageAsync( update.Message.From.Id, ErrorString, ParseMode.Markdown, false, Vars.CurrentConf.DisableNotifications, update.Message.MessageId); return(true); } }
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); } }