internal async Task publishInDaily(long postId) { Message result; try { logger.Info("Es soll folgender Post in Top-Daily veröffentlicht werden: " + postId); result = await this.telegramPublishBot.SendTextMessageAsync( chatId : this.draumDailyChatId, parseMode : ParseMode.Html, disableWebPagePreview : true, text : this.textBuilder.buildPostingTextForTopTeaser(postId), replyMarkup : Keyboards.getTopPostLinkKeyboard(this.posts.getMessageId(postId), DRaumManager.Roomname) ).ConfigureAwait(false); } catch (Exception ex) { logger.Error(ex, "Fehler beim Publizieren des Posts im Daily-Kanal: " + postId); result = null; } if (result == null || result.MessageId == 0) { logger.Error("Ergebnis ist null oder keine Msg-ID für das Posting erhalten " + postId); } else { this.posts.setDailyChatMsgId(postId, result.MessageId); } }
internal async Task updatePostButtons(long postId, CancellationToken cancellationToken) { logger.Info("Buttons eines Posts (" + postId + ") werden aktualisiert"); try { await this.telegramPublishBot.EditMessageReplyMarkupAsync( chatId : this.draumChatId, messageId : this.posts.getMessageId(postId), replyMarkup : Keyboards.getPostKeyboard(this.posts.getUpVotes(postId), this.posts.getDownVotes(postId), postId), cancellationToken : cancellationToken).ConfigureAwait(false); this.posts.resetDirtyFlag(postId); } catch (OperationCanceledException) { // get out of loop } catch (Exception ex) { /// TODO Migrate! /*if (ex is MessageIsNotModifiedException) * { * this.posts.resetDirtyFlag(postId); * logger.Warn("Die Buttons des Posts " + postId + " waren nicht verändert"); * } * else*/ { logger.Error(ex, "Beim aktualisieren eines Buttons eines Beitrags (" + postId + ") trat ein Fehler auf: " + ex.Message); } } }
internal async Task updatePostText(long postId) { try { await this.telegramPublishBot.EditMessageTextAsync( chatId : this.draumChatId, disableWebPagePreview : true, parseMode : ParseMode.Html, replyMarkup : Keyboards.getPostKeyboard(this.posts.getUpVotes(postId), this.posts.getDownVotes(postId), postId), messageId : this.posts.getMessageId(postId), text : this.textBuilder.buildPostingText(postId)); this.posts.resetTextDirtyFlag(postId); } catch (Exception ex) { /// TODO Migrate! /*if (ex is MessageIsNotModifiedException) * { * this.posts.resetTextDirtyFlag(postId); * logger.Warn("Der Text des Posts " + postId + " ist nicht verändert"); * } * else */ { logger.Error(ex, "Beim aktualisieren eines Textes eines Beitrags (" + postId + ") trat ein Fehler auf: " + ex.Message); } } }
public void EditMessageCaptionTest() { mBotOkResponse.EditMessageCaption("TestChatId", 123, "TestInlineMessageId", "TestCaption", Keyboards.GetInlineKeyboard()); var request = MockServer.ServerOkResponse.SearchLogsFor( Requests.WithUrl("/botToken/editMessageCaption").UsingPost()); ConsoleUtlis.PrintResult(request); Assert.AreEqual("chat_id=TestChatId&" + "message_id=123&" + "inline_message_id=TestInlineMessageId&" + "caption=TestCaption&" + "reply_markup=%7B%0D%0A%20%20%22inline_keyboard" + "%22%3A%20%5B%0D%0A%20%20%20%20%5B%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20%22text" + "%22%3A%20%221%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20%22text" + "%22%3A%20%222%22%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%5D%2C%0D%0A%20%20%20%20%5B%0D%0A%20%20%20%20%20%20%7B" + "%0D%0A%20%20%20%20%20%20%20%20%22text%22%3A%20%223%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%7B%0D%0" + "A%20%20%20%20%20%20%20%20%22text%22%3A%20%224%22%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%5D%0D%0A%20%20%5D%0D%" + "0A%7D", request.FirstOrDefault()?.Body); Assert.AreEqual("/botToken/editMessageCaption", request.FirstOrDefault()?.Url); Assert.Throws <Exception>( () => mBotBadResponse.EditMessageCaption("TestChatId", 123, "TestInlineMessageId", "TestCaption", Keyboards.GetInlineKeyboard())); }
internal async Task handleErrorMemory(CancellationToken cancelToken) { MemoryTarget target = LogManager.Configuration.FindTargetByName <MemoryTarget>("errormemory"); while (target.Logs.Count > 0) { string s = target.Logs[0]; if (needToSendThis(s)) { await this.sendMessageWithKeyboard(s, Keyboards.getGotItDeleteButtonKeyboard()); try { await Task.Delay(3000, cancelToken); } catch (OperationCanceledException) { return; } updateLastSentMessage(s); } target.Logs.RemoveAt(0); if (cancelToken.IsCancellationRequested) { return; } } }
public void EditMessageTextTest() { mBotOkResponse.EditMessageText("TestText", "testChatId", 123, "testInlineMessageId", ParseMode.HTML, true, Keyboards.GetInlineKeyboard()); var request = MockServer.ServerOkResponse.SearchLogsFor( Requests.WithUrl("/botToken/editMessageText").UsingPost()); ConsoleUtlis.PrintResult(request); Assert.AreEqual("text=TestText&" + "chat_id=testChatId&" + "message_id=123&" + "inline_message_id=testInlineMessageId&" + "parse_mode=HTML&" + "disable_web_page_preview=True&" + "reply_markup=%7B%0D%0A%20%20%22inline_keyboard" + "%22%3A%20%5B%0D%0A%20%20%20%20%5B%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20%22text" + "%22%3A%20%221%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%20%7B%0D%0A%20%20%20%20%20%20%20%20%22text" + "%22%3A%20%222%22%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%5D%2C%0D%0A%20%20%20%20%5B%0D%0A%20%20%20%20%20%" + "20%7B%0D%0A%20%20%20%20%20%20%20%20%22text%22%3A%20%223%22%0D%0A%20%20%20%20%20%20%7D%2C%0D%0A%20%20%20%20%20%" + "20%7B%0D%0A%20%20%20%20%20%20%20%20%22text%22%3A%20%224%22%0D%0A%20%20%20%20%20%20%7D%0D%0A%20%20%20%20%5D%0D%" + "0A%20%20%5D%0D%0A%7D", request.FirstOrDefault()?.Body); Assert.AreEqual("/botToken/editMessageText", request.FirstOrDefault()?.Url); Assert.Throws <Exception>( () => mBotBadResponse.EditMessageText("TestText", "testChatId", 123, "testInlineMessageId", ParseMode.HTML, true, Keyboards.GetInlineKeyboard())); }
protected override Response Run(CallbackQuery message, Account account, Dictionary <string, string> values) { var boards = account.Controller.GetBoards(account); return(new Response().EditTextMessage(account, message.Message.MessageId, $"You have {boards.Length} boards.\nChoose one board to get more details:", Keyboards.BoardsKeyboard(boards))); }
public override Response Execute(Message message, Client.Client client, Account account) { var boards = account.Controller.GetBoards(account); return(new Response().TextMessage(account, $"You have {boards.Length} boards.\nChoose one board to get more details:", Keyboards.BoardsKeyboard(boards))); }
public override async void OnStateChange(Chat chat) { DateTime firstDate = DateTime.Now.AddDays(1); DateTime secondDate = firstDate.AddDays(6); List <string> dates = DbServices.GetIntermediateDates(firstDate, secondDate); await ServicesMessageController.SendMessageAsync( chat, "Введіть дату прибуття", Keyboards.NextDates(dates)); }
public override async void OnStateChange(Chat chat) { responder.userTempData.TryGetValue("DateOfArrival", out string firstDateString); DateTime firstDate = DateTime.Parse(firstDateString).AddDays(1); DateTime secondDate = firstDate.AddDays(6); List <string> dates = DbServices.GetIntermediateDates(firstDate, secondDate); await ServicesMessageController.SendMessageAsync( chat, "Введіть дату відбуття", Keyboards.NextDates(dates)); }
public override async Task <UpdateHandlingResult> HandleCommand(Update update, DefaultCommandArgs args) { await Bot.Client.SendTextMessageAsync( update.Message.Chat.Id, "Прости...", replyMarkup : Keyboards.GetMainOptionsKeyboard()); return(UpdateHandlingResult.Handled); }
private async Task onAdminCallback(ITelegramBotClient botClient, Update e, CancellationToken cancellationToken) { if (e.CallbackQuery.Data != null) { DRaumCallbackData callbackData = DRaumCallbackData.parseCallbackData(e.CallbackQuery.Data); if (callbackData.getPrefix().Equals(Keyboards.GenericMessageDeletePrefix)) { await this.adminBot.removeMessage(e.CallbackQuery.Message.MessageId); return; } if (callbackData.getPrefix().Equals(Keyboards.ModDeleteFlaggedPrefix)) { // Der Admin entscheidet den geflaggten Post zu entfernen long postingID = callbackData.getId(); int messageId = this.posts.getMessageId(postingID); int messageIdDaily = this.posts.getMessageIdDaily(postingID); int messageIdWeekly = this.posts.getMessageIdWeekly(postingID); if (!this.posts.removePost(postingID)) { logger.Error("Konnte den Post " + postingID + " nicht aus dem Datensatz löschen"); } await this.adminBot.sendMessageWithKeyboard("Bitte manuell löschen", Keyboards.getPostLinkWithCustomText(messageId, DRaumManager.Roomname, "Link zum D-Raum")); if (messageIdDaily != -1) { await this.adminBot.sendMessageWithKeyboard("Bitte manuell löschen", Keyboards.getPostLinkWithCustomText(messageIdDaily, DRaumManager.Roomname_daily, "Link zum D-Raum-Daily")); } if (messageIdWeekly != -1) { await this.adminBot.sendMessageWithKeyboard("Bitte manuell löschen", Keyboards.getPostLinkWithCustomText(messageIdWeekly, DRaumManager.Roomname_weekly, "Link zum D-Raum-Daily")); } // Nachricht aus dem Admin-Chat löschen await this.adminBot.removeMessage(e.CallbackQuery.Message.MessageId); return; } if (callbackData.getPrefix().Equals(Keyboards.ModClearFlagPrefix)) { // Der Admin entscheided, den Flag zurückzunehmen if (this.posts.removeFlagFromPost(callbackData.getId())) { await this.adminBot.removeMessage(e.CallbackQuery.Message.MessageId); await this.adminBot.replyToCallback(e.CallbackQuery.Id, "Flag wurde entfernt"); } else { logger.Error("Konnte das Flag vom Post nicht entfernen: " + callbackData.getId()); } } } }
public override async Task Execute(Message message) { var keyboard = Keyboards.FirstOrDefault(Name); if (keyboard == null) { throw new InvalidOperationException("could not find an appropriate keyboard"); } await keyboard.SendKeyboardAsync(message); }
public override async void OnStateChange(Chat chat) { List <HotelRoomType> listRoomTypes = ServicesHotelRoomType.GetHotelRoomTypes(); if (listRoomTypes.Count == 0) { await ServicesMessageController.SendMessageAsync(chat, "Номерів немає", Keyboards.ReturnMainMenu); return; } IReplyMarkup markup = Keyboards.GetRoomTypesMenu(listRoomTypes); await ServicesMessageController.SendMessageAsync(chat, "Оберіть тип номеру", markup); }
private void Form1_Load(object sender, EventArgs e) { //Start catching first. Keyboards.StartCatching(Handle, CaptureWhileActiveOnly); combiner = new Combiner(); combiner.TextCombined += Combiner_TextCombined; //Key processing is started when new instance created. keyboards = new Keyboards(Handle); keyboards.KeyStateChanged += Processor_KeyStateChanged; refreshDeviceList.PerformClick(); }
internal async Task removeMessage(int messageId) { try { await this.telegramAdminBot.SendTextMessageAsync( chatId : adminChatId, text : "Ein Posting soll gelöscht werden.", replyMarkup : Keyboards.getPostLinkWithCustomText(messageId, DRaumManager.Roomname, "Springe zum Post") ).ConfigureAwait(false); } catch (Exception ex) { logger.Error(ex, "Fehler beim Senden einer Lösch-Nachricht an den Admin, Msg-ID: " + messageId); } }
public override async void OnStateChange(Chat chat) { var listReservation = DbServices.GetValidReservation(chat.Id, DateTime.Now); if (listReservation.Count == 0) { await ServicesMessageController.SendMessageAsync(chat, "Бронювань немає", Keyboards.ReturnMainMenu); responder.SetState(new MainMenu()); return; } IReplyMarkup markup = Keyboards.GetReservationsMenu(listReservation); await ServicesMessageController.SendMessageAsync(chat, "Бронювання: ", markup); }
private void Input_OnKeyPressed(object sender, KeyPressedEventArgs e) { e.DeviceId = DeviceMap[e.DeviceName].PersistantId; if (Keyboards.ContainsKey(e.DeviceId)) { var inputTuple = Keyboards[e.DeviceId]; if (!inputTuple.Natural) { inputTuple.PreKeyData = inputTuple.LastKeyData; inputTuple.LastKeyData = e; OnVirtualKeyboardAction(e); e.Handled = true; } } }
public async Task ExecuteAsync(Message message) { var allEnvs = await environmentStorage.GetAllEnvironmentNamesAsync(); var keyboard = Keyboards.CreateKeyboard(allEnvs); await botService.Client.SendTextMessageAsync( message.Chat.Id, "Привет!\n" + "Чтобы забронировать площадку, используй /take названиеПлощадки\n" + "Чтобы освободить площадку напиши /free названиеПлощадки или /free all чтобы освободить все\n" + "Просмотреть свободные площадки - /list\n" + "Чтобы добавить новую площадку, напиши /add названиеПлощадки\n", replyMarkup : keyboard); }
public void Start() { Input = new Input { MouseFilterMode = MouseFilterMode.All, KeyboardFilterMode = KeyboardFilterMode.All, FilterType = FilterType.Whitelist }; Input.SetKeyboardDeviceList(Keyboards.Where(e => !e.Value.Natural).Select(e => DeviceMap.FirstOrDefault(f => f.Value.PersistantId == e.Key).Value.MaybeRealId).ToArray()); Input.SetMiceDeviceList(Mice.Where(e => !e.Value.Natural).Select(e => DeviceMap.FirstOrDefault(f => f.Value.PersistantId == e.Key).Value.MaybeRealId).ToArray()); //Input.KeyboardFilterMode = KeyboardFilterMode.All; Input.OnMouseAction += InputOnMouseAction; Input.OnKeyPressed += Input_OnKeyPressed; Input.Load(); }
public override async void OnStateChange(Chat chat) { responder.userTempData.TryGetValue("DateOfArrival", out arrival); responder.userTempData.TryGetValue("DateOfDeparture", out departure); responder.userTempData.TryGetValue("NumberOfAdults", out adults); responder.userTempData.TryGetValue("NumberOfChildren", out children); var listRoomTypes = DbServices.GetAviableRoomTypes(arrival, departure, int.Parse(adults), int.Parse(children)); if (listRoomTypes.Count <= 0) { await ServicesMessageController.SendMessageAsync( chat, "На вказаний період немає доступних номерів.", Keyboards.ReturnMainMenu); } IReplyMarkup markup = Keyboards.GetRoomTypesMenu(listRoomTypes, "Замовити: "); await ServicesMessageController.SendMessageAsync(chat, "Оберіть тип номеру", markup); }
private void RefreshDeviceList_Click(object sender, EventArgs e) { lock (singleThreadLock) { deviceList.BeginUpdate(); deviceList.Items.Clear(); var devices = Keyboards.Get().ToArray(); if (devices.Length > 0) { ListViewItem[] items = Array.ConvertAll(devices, i => new ListViewItem(new string[] { i.Handle.ToInt64().ToString(), i.Name, i.Type.ToString(), i.Description })); deviceList.Items.AddRange(items); } deviceList.EndUpdate(); } }
private async Task processFeedback() { if (!this.feedbackManager.feedBackAvailable() || this.feedbackManager.isWaitingForFeedbackReply()) { return; } // erhaltene Feedbacks verarbeiten, wenn grad keine Antwort geschrieben wird FeedbackElement feedback = this.feedbackManager.dequeueFeedback(); if (feedback != null) { Message msg = await this.feedbackBot.sendMessageWithKeyboard(feedback.Text, Keyboards.getFeedbackReplyKeyboard(feedback.ChatId)); if (msg == null || msg.MessageId == 0) { logger.Error( "Es gab ein Problem beim senden der Feedback-Nachricht. Feedback wird neu in die Liste einsortiert."); this.feedbackManager.enqueueFeedback(feedback); } } }
internal async Task publishInMainChannel(long postingId) { if (postingId != 0) { // Ab in den D-Raum damit logger.Info("Es soll folgender Post veröffentlicht werden: " + postingId); try { this.posts.setPublishTimestamp(postingId); Message result = await this.telegramPublishBot.SendTextMessageAsync( chatId : this.draumChatId, parseMode : ParseMode.Html, text : this.textBuilder.buildPostingText(postingId), disableWebPagePreview : true, replyMarkup : Keyboards.getPostKeyboard(this.posts.getUpVotes(postingId), this.posts.getDownVotes(postingId), postingId) ); if (result == null || result.MessageId == 0) { logger.Error("Fehler beim Publizieren des Posts (keine msg ID) bei Post " + postingId + " wird neu eingereiht."); this.posts.reAcceptFailedPost(postingId); this.posts.unsetPublishTimestamp(postingId); } else { this.posts.resetTextDirtyFlag(postingId); this.posts.resetDirtyFlag(postingId); this.posts.setChatMsgId(postingId, result.MessageId); } } catch (Exception ex) { logger.Error(ex, "Fehler beim Veröffentlichen eines Posts im D-Raum, PostingId: " + postingId + " wird neu eingereiht."); this.posts.reAcceptFailedPost(postingId); } } }
public override async Task <UpdateHandlingResult> HandleCommand(Update update, DefaultCommandArgs args) { var userAcademicGroup = (await Storage.GetGroupsForChatAsync(update.Message.Chat)).FirstOrDefault(g => g.GType == ScheduleGroupType.Academic); if (userAcademicGroup != null) { switch (userAcademicGroup.Name.ElementAt(3)) { case '6': args.RawInput = args.RawInput + "_2курс_1"; break; case '7': args.RawInput = args.RawInput + "_1курс"; if (Regex.IsMatch(userAcademicGroup.Name, $@"[1-5]$")) { args.RawInput = args.RawInput + "_1"; } else { args.RawInput = args.RawInput + "_2"; } break; } return(await base.HandleCommand(update, args)); } else { await Bot.Client.SendTextMessageAsync( update.Message.Chat.Id, "Сначала надо установить группу ☝️. Выбери курс.", replyMarkup : Keyboards.GetCoursesKeyboad()); return(UpdateHandlingResult.Handled); } }
private async Task <bool> acceptPostForPublishing(long postingId) { PostingPublishManager.PublishHourType publishType = this.authors.getPublishType(this.posts.getAuthorId(postingId), this.statistics.getPremiumLevelCap()); string result = ""; if (publishType != PostingPublishManager.PublishHourType.None) { result = this.posts.acceptPost(postingId, publishType); } if (!result.Equals("")) { string teaserText = this.posts.getPostingTeaser(postingId); long authorId = this.posts.getAuthorId(postingId); if (authorId != -1) { this.authors.publishedSuccessfully(authorId); await this.inputBot.sendMessage(authorId, "Der Post ist zum Veröffentlichen freigegeben: " + result + "\r\n\r\nVorschau: " + teaserText); } else { await this.moderateBot.sendMessageWithKeyboard( "Konnte den Userchat zu folgender Posting-ID nicht erreichen (Posting wird aber veröffentlicht): " + postingId + " Textvorschau: " + this.posts.getPostingTeaser(postingId), Keyboards.getGotItDeleteButtonKeyboard(), false); return(false); } } else { await this.adminBot.sendMessageWithKeyboard( "Der Post " + postingId + " konnte nicht in die Liste zu veröffentlichender Posts eingefügt werden, FEHLER!", Keyboards.getGotItDeleteButtonKeyboard()); return(false); } return(true); }
public async Task Execute(IClient client) { var update = await client.GetTextMessage(); //todo fast templates and change text on buttons var keys = Keyboards.AddType(_user); if (_user.PeopleInited() && _user.CategoriesInited()) { await client.SendTextMessage($"This is about", replyMarkup : keys); } else if (_user.PeopleInited()) { await client.SelectRecordType(_user, DB.Secondary.RecordType.Transaction); } else if (_user.CategoriesInited()) { await client.SelectRecordType(_user, DB.Secondary.RecordType.Expense); } else { await client.SendTextMessage($"Add category or person first", replyMarkup : keys); } }
private async Task GetFirewalls(Message message) { await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "\U0001F4C0 Loading your firewalls...", replyMarkup : Keyboards.GetFirewallMenuKeyboard()); var digitalOceanApi = _digitalOceanClientFactory.GetInstance(message.From.Id); var firewalls = await digitalOceanApi.Firewalls.GetAll(); if (firewalls.Count > 0) { _sessionRepo.Update(message.From.Id, session => { session.Data = firewalls; session.State = SessionState.FirewallsMenu; }); var droplets = await digitalOceanApi.Droplets.GetAll(); var page = _pageFactory.GetInstance <FirewallPage>(droplets); var pageModel = page.GetPage(message.From.Id, 0); var sendMessage = await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, pageModel.Message, ParseMode.Markdown, replyMarkup : pageModel.Keyboard); _handlerCallbackRepo.Update(message.From.Id, callback => { callback.MessageId = sendMessage.MessageId; callback.UserId = message.From.Id; callback.HandlerType = GetType().FullName; }); } else { await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "You dont have a firewalls \U0001F914"); } }
private void RunListeningBus() { _bus.Consume(_bus.QueueDeclare("auth-queue"), register => { register.Add <AuthMessage>(async(message, info) => { try { if (message.Body.IsSuccess) { _sessionRepo.Update(message.Body.UserId, (session) => { session.State = SessionState.MainMenu; }); await _telegramBotClient.SendTextMessageAsync(message.Body.ChatId, "Authentication completed \U0001F973", replyMarkup: Keyboards.GetMainMenuKeyboard()); } } catch (Exception ex) { _logger.LogError($"UserId={message.Body.UserId.ToString()}, ErrorMessage={ex.Message}, StackTrace={ex.StackTrace}"); } }); }); }
private async Task ChangePurpose(Message message) { var digitalOceanApi = _digitalOceanClientFactory.GetInstance(message.From.Id); var session = _sessionRepo.Get(message.From.Id); var projectId = session.Data.CastObject <string>(); await digitalOceanApi.Projects.Patch(projectId, new PatchProject { Purpose = message.Text }); _sessionRepo.Update(message.From.Id, session => { session.State = SessionState.SelectedProject; }); await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, "Done \U00002705", replyMarkup : Keyboards.GetSelectedProjectMenuKeyboard()); }