public override bool Execute() { //Program.Logger.Debug($"{GetType().Name}: Parsing message size. Arguments: {Arguments}"); int messageSize; int.TryParse(Arguments, out messageSize); if (messageSize == 0) { messageSize = MaxPageSize; } messageSize = Math.Min(messageSize, MaxPageSize); //Program.Logger.Debug($"{GetType().Name}: Message size: {messageSize}"); List<string> suggestions; //Program.Logger.Debug($"{GetType().Name}: Retrieving shows list"); using (var db = new AppDbContext()) { try { suggestions = db.Suggestions.Select(s => "/" + s.Id + " " + s.Title + "\nрейтинг: "+ s.Rate + "\nпредложено " + s.AddedBy.FirstName + " " + s.AddedBy.LastName).ToList(); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while retrieving shows list", e); } } List<string> pagesList = new List<string>(); for (int i = 0; i < suggestions.Count; i += messageSize) { if (i > suggestions.Count) { break; } int count = Math.Min(suggestions.Count - i, messageSize); pagesList.Add( suggestions.GetRange(i, count) .Aggregate("", (s, s1) => s + "\n" + s1) ); } try { //Program.Logger.Debug($"{GetType().Name}: Sending shows list"); for (int i = 0; i < pagesList.Count; i++) { string page = pagesList[i]; ReplyKeyboardMarkup replyKB = new ReplyKeyboardMarkup(); replyKB.Keyboard = new string[][] { new string[] {"/next","/stop"} }; replyKB.OneTimeKeyboard = true; replyKB.ResizeKeyboard = true; replyKB.Selective = false; if (i != pagesList.Count - 1) { page += "\n/next or /stop"; replyKB.Keyboard[0]= new string[] {"/next","/stop"}; } if (i == pagesList.Count - 1) { page += "\n/stop"; replyKB.Keyboard[0]= new string[] {"/stop"}; } TelegramApi.SendMessage(Message.From, page,replyKB); Message message; /*ReplyKeyboardMarkup replyKB = new ReplyKeyboardMarkup(); replyKB.Keyboard = new string[][] { new string[] {"/next","/stop"} }; replyKB.OneTimeKeyboard = true; replyKB.ResizeKeyboard = true; replyKB.Selective = false;*/ ReplyKeyboardMarkup replyRateKB = new ReplyKeyboardMarkup(); replyRateKB.Keyboard = new string[][] { new string[] {"/+","/-"} }; replyRateKB.OneTimeKeyboard = true; replyRateKB.ResizeKeyboard = true; replyRateKB.Selective = false; string footerText = ""; do { message = TelegramApi.WaitForMessage(Message.From); if (message.Text != "/stop" && (i == pagesList.Count - 1 || message.Text != "/next" )) { //if (message.Text = ) string someMatch = SuggestionNumRegex.Match(message.Text).Groups[0].Value; if (someMatch == "" || someMatch == null) { if (i == pagesList.Count - 1) { footerText = "\n/stop or /+"; replyKB.Keyboard[0]= new string[] {"/stop"}; } else { footerText = "\n/next or /stop or /+"; replyKB.Keyboard[0]= new string[] {"/next","/stop"}; } TelegramApi.SendMessage(Message.From, footerText, replyKB); } else { using (var db = new AppDbContext()) { try { int sId = int.Parse(someMatch); Suggestion fullSuggestion = db.Suggestions.Include(s => s.AddedBy).FirstOrDefault(s => s.Id == sId); /*Console.WriteLine(fullSuggestion.Title + "\nдобавлено " + fullSuggestion.AddedBy.FirstName + " " + fullSuggestion.AddedBy.LastName + "\n рейтинг: " + fullSuggestion.Rate + "\n" + fullSuggestion.Text);*/ TelegramApi.SendMessage(Message.From, fullSuggestion.ToString(), replyRateKB); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending suggest description", e); } } } } } while (message.Text != "/stop" && (i == pagesList.Count - 1 || message.Text != "/next")); if (message.Text == "/stop") { break; } } } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending suggestions list", e); } Status = true; return true; }
public override bool Execute() { string suggestionId; if (string.IsNullOrEmpty(Arguments)) { Console.WriteLine(GetType().Name + ": Sending 'Enter suggestion number' prompt"); try { TelegramApi.SendMessage(Message.From, "Введите номер предложения"); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending prompt", e); } Console.WriteLine(GetType().Name + ": Waiting for a message that contains show title"); try { suggestionId = TelegramApi.WaitForMessage(Message.From).Text; } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while waiting for a message that contains show title", e); } } else { suggestionId = Arguments; } ReplyKeyboardMarkup replyRateKB = new ReplyKeyboardMarkup(); replyRateKB.Keyboard = new string[][] { new string[] {"/+","/-"}, new string[] {"/back"} }; replyRateKB.OneTimeKeyboard = true; replyRateKB.ResizeKeyboard = true; replyRateKB.Selective = false; int sId = int.Parse(suggestionId); using (var db = new AppDbContext()) { Suggestion suggestion; //Rating rating; try { suggestion = db.GetSuggestionById(sId); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while searching suggestion #" + suggestionId + " in database", e); } if (suggestion != null) { Console.WriteLine(GetType().Name + ": Searching user with TelegramId: " + Message.From.Id + " in database"); User user; try { user = db.GetUserByTelegramId(Message.From.Id); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while searching user in database", e); } bool newUser = false; if (user == null) { user = new User { TelegramUserId = Message.From.Id, FirstName = Message.From.FirstName, LastName = Message.From.LastName, Username = Message.From.Username }; newUser = true; } if (newUser) { Console.WriteLine(GetType().Name + ": " + user + " is new User"); } else { Console.WriteLine(GetType().Name + ": User " + user + " already exists"); } Rating rating; try { var _user = db.Users.Include(u => u.Ratings).FirstOrDefault(r => r.Id==user.Id); rating = _user.Ratings.FirstOrDefault(r => r.Suggestion.Id == suggestion.Id); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while checking for rating", e); } /* if (rating == null) { rating = new Rating { User = user, Suggestion = suggestion, isRatedUp = true } }*/ //} //do //{ //using (var db = new AppDbContext()) //{ /*if (suggestion.AddedBy == userRated) replyRateKB.Keyboard[1] = new string[] { "/delete" };*/ if (rating != null) { if (rating.isRatedUp) { replyRateKB.Keyboard[0] = new string[] { "/-" }; } else { replyRateKB.Keyboard[0] = new string[] { "/+" }; } } else { replyRateKB.Keyboard[0] = new string[] { "/+", "/-" }; } try { TelegramApi.SendMessage(Message.From, suggestion.ToString(), replyRateKB); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending suggest description", e); } Message message; try { message = TelegramApi.WaitForMessage(Message.From); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while waiting for a message with rate action", e); } /*if (suggestion.AddedBy != userRated) {*/ if (rating != null) { if (message.Text == "/+" && !rating.isRatedUp) { suggestion.Rate += 1; db.Ratings.Remove(rating); } else if (message.Text == "/-" && rating.isRatedUp) { suggestion.Rate -= 1; db.Ratings.Remove(rating); } } else { if (message.Text == "/+") { suggestion.Rate += 1; rating = new Rating() { User = user, Suggestion = suggestion, isRatedUp = true }; db.Ratings.Add(rating); } else if (message.Text == "/-") { suggestion.Rate -= 1; rating = new Rating() { User = user, Suggestion = suggestion, isRatedUp = false }; db.Ratings.Add(rating); } } //} db.SaveChanges(); } else { Console.WriteLine(GetType().Name + ": Suggestion does not exist"); try { TelegramApi.SendMessage(Message.From, "Suggestion does not exist"); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occured while sending notification of nonexistent suggestion", e); } } //} while (message.Text != "/+" && message.Text != "/-" && message.Text != "/delete" && message.Text != "/back"); } Status = true; return true; }
static void Main(string[] args) { TelegramApi telegram = new TelegramApi(_token); try { Console.WriteLine("Executing GetMe"); var botUser = telegram.GetMe(); Console.WriteLine("GetMe returned \n" + botUser.ToString()); } catch (Exception e) { Console.WriteLine("GetMe failed"); Console.WriteLine(e.Message); return; } using (var db = new AppDbContext()) { db.SaveChanges(); var query = from b in db.Suggestions orderby b.Id select b; Console.WriteLine("All suggestions:"); foreach (var item in query) { Console.WriteLine(item.Id + " " + item.Text); } //Console.ReadKey(); } /* ReplyKeyboardMarkup replyKB = new ReplyKeyboardMarkup(); replyKB.Keyboard = new string[][] { new string[] {"Yes","No"} }; replyKB.OneTimeKeyboard = false; replyKB.ResizeKeyboard = false; replyKB.Selective = false;*/ //string json = JsonConvert.SerializeObject(replyKB); StartPolling(telegram); var processingCommandUsers = new ConcurrentDictionary<Telegram.User, bool>(); Regex commandRegex = new Regex(@"(/\w+)\s*"); while (true) { foreach (var update in telegram.Updates) { if (processingCommandUsers.ContainsKey(update.Key) && processingCommandUsers[update.Key]) { continue; } if (update.Value.Count == 0) { continue; } Message message; update.Value.TryDequeue(out message); /*Logger.Debug($"Received message '{message.Text}' from " + $"{message.From.FirstName} {message.From.LastName}");*/ string commandTitle = commandRegex.Match(message.Text).Groups[1].Value; /*ReplyKeyboardMarkup replyKeyboard = new ReplyKeyboardMarkup() {Keyboard = new string[][] { new string[] {"Yes","No"} }, OneTimeKeyboard = true };*/ string testText = message.Text; Console.WriteLine("Received a message: " + testText); //Logger.Debug($"Creating command object for '{commandTitle}'"); var command = Command.CreateCommand(commandTitle); //Logger.Info($"Received {command.GetType().Name} from " + // $"{message.From.FirstName} {message.From.LastName}"); command.TelegramApi = telegram; command.Message = message; //Logger.Debug($"Executing {command.GetType().Name}"); processingCommandUsers[update.Key] = true; try { // telegram.SendMessage(message.From, testText, replyKeyboard); // telegram.SendMessage(message.From, " ", replyKeyboard); } catch (Exception e) { Console.WriteLine(e.Message); throw; } Task commandTask = Task.Run(() => { try { command.Execute(); } catch (Exception e) { /*Logger.Error($"An error occurred while executing {command.GetType().Name}.\n" + $"Message: {command.Message.Text}\n" + $"Arguments: {command.Arguments}\n" + $"User: {command.Message.From}"); Logger.Error(e);*/ Console.WriteLine(e.Message); } } ); commandTask.ContinueWith(task => { processingCommandUsers[update.Key] = false; /*Logger.Debug($"{command.GetType().Name} from " + $"{message.From.FirstName} {message.From.LastName} {(command.Status ? "succeeded" : "failed")}");*/ }); } Thread.Sleep(200); } }
public override bool Execute() { string suggestionTitle; string suggestionText; try { TelegramApi.SendMessage(Message.From, "Введите название для идеи"); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending prompt", e); } try { suggestionTitle = TelegramApi.WaitForMessage(Message.From).Text; } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while waiting for a message that contains show title", e); } try { TelegramApi.SendMessage(Message.From, "Введите текст самой идеи"); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending prompt", e); } try { suggestionText = TelegramApi.WaitForMessage(Message.From).Text; } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while waiting for a message that contains show title", e); } string response; using (AppDbContext db = new AppDbContext()) { Suggestion suggestion; /*if (suggestion.Title != "" && suggestion.Text != "") {*/ User user; try { user = db.GetUserByTelegramId(Message.From.Id); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while searching user in database", e); } bool newUser = false; if (user == null) { user = new User { TelegramUserId = Message.From.Id, FirstName = Message.From.FirstName, LastName = Message.From.LastName, Username = Message.From.Username }; newUser = true; } if (newUser) { Console.WriteLine(GetType().Name + ": " + user + " is new User"); } else { Console.WriteLine(GetType().Name + ": User " + user + " already exists"); } suggestion = new Suggestion { Title = suggestionTitle, Text = suggestionText, Rate = 0, AddedBy = user }; if (newUser) { db.Suggestions.Add(suggestion); db.Users.Add(user); } else { db.Suggestions.Add(suggestion); } response = "Ваша идея добавлена"; try { db.SaveChanges(); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while saving changes to database", e); } } try { TelegramApi.SendMessage(Message.From, response); } catch (Exception e) { throw new Exception(GetType().Name + ": An error occurred while sending response to " + Message.From, e); } Status = true; return true; }