Пример #1
0
        public async Task UpdatePoll(Poll poll, IUrlHelper urlHelper, CancellationToken cancellationToken = default)
        {
            var content = poll.GetMessageText(urlHelper, disableWebPreview: poll.DisableWebPreview());

            foreach (var message in poll.Messages)
            {
                try
                {
                    if (message.InlineMesssageId is string inlineMessageId)
                    {
                        await myBot.EditMessageTextAsync(inlineMessageId, content.MessageText, content.ParseMode, content.DisableWebPagePreview,
                                                         await message.GetReplyMarkup(myChatInfo, cancellationToken), cancellationToken);
                    }
                    else if (message.ChatId is long chatId && message.MesssageId is int messageId)
                    {
                        await myBot.EditMessageTextAsync(chatId, messageId, content.MessageText, content.ParseMode, content.DisableWebPagePreview,
                                                         await message.GetReplyMarkup(myChatInfo, cancellationToken), cancellationToken);
                    }
                }
                catch (Exception ex)
                {
                    myTelemetryClient.TrackExceptionEx(ex, message.GetTrackingProperties());
                }
            }
        }
Пример #2
0
        private static async void Bot_OnCallbackQuery(object sender, CallbackQueryEventArgs e)
        {
            if (e.CallbackQuery.Data == "12")
            {
                var inlineKeyboard = new InlineKeyboardMarkup(new[]
                {
                    // first row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("Недвижимость", "s_11"),
                        InlineKeyboardButton.WithCallbackData("Авто", "s_12"),
                        InlineKeyboardButton.WithCallbackData("Услуги", "s_13")
                    },
                    // second row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("Обмен криптовалюты", "s_21"),
                    },
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("Назад", "s_31"),
                    }
                });

                await botClient.EditMessageTextAsync(
                    chatId : e.CallbackQuery.Message.Chat.Id,
                    messageId : e.CallbackQuery.Message.MessageId,
                    text : "Сейчас можно продать, купить товары/услуги за BTC",
                    replyMarkup : inlineKeyboard
                    );
            }

            if (e.CallbackQuery.Data == "s_31")
            {
                var inlineKeyboard = new InlineKeyboardMarkup(new[]
                {
                    // first row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("Покупка", "11"),
                        InlineKeyboardButton.WithCallbackData("Продажа", "12"),
                    },
                    // second row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("Мои объявления", "21"),
                    }
                });

                await botClient.EditMessageTextAsync(
                    chatId : e.CallbackQuery.Message.Chat.Id,
                    messageId : e.CallbackQuery.Message.MessageId,
                    text : "Сейчас можно продать, купить товары/услуги за BTC",
                    replyMarkup : inlineKeyboard
                    );
            }
        }
        public async Task Send(long chatId, Func <Task <string> > messageFunc,
                               TimeSpan interval, TimeSpan duration, ParseMode parseMode = ParseMode.Html)
        {
            if (userTokens.ContainsKey(chatId))
            {
                lock (userTokens)
                {
                    if (userTokens.ContainsKey(chatId))
                    {
                        userTokens[chatId].Cancel();
                        userTokens.Remove(chatId);
                    }
                }
            }
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            cancellationTokenSource.CancelAfter(duration);
            userTokens.Add(chatId, cancellationTokenSource);

            string  messageText = "";
            Message sentMessage = null;
            await Repeat.Interval(interval, async() =>
            {
                var oldMessageText = messageText;
                messageText        = await messageFunc();
                if (messageText != oldMessageText)
                {
                    try
                    {
                        sentMessage = sentMessage?.MessageId == null
                        ? await _botClient.SendTextMessageAsync(chatId, "🔄 " + messageText, parseMode)
                        : await _botClient.EditMessageTextAsync(chatId, sentMessage.MessageId, "🔄 " + messageText, parseMode);
                    } catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error while sending self-updating message");
                    }
                }
            }, cancellationTokenSource.Token);

            try
            {
                if (sentMessage?.MessageId > 0)
                {
                    await _botClient.EditMessageTextAsync(chatId, sentMessage.MessageId, messageText, parseMode);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error trying to finalize self-updating message");
            }
        }
Пример #4
0
        static async void TgBot_OnMessage(object sender, MessageEventArgs e)
        {
            if (e.Message.Voice != null)
            {
                var message = await _tgBotClient.SendTextMessageAsync(
                    chatId : e.Message.Chat,
                    text : "Распознаю речь..."
                    );

                var tgAudioFilePath = $"{Guid.NewGuid()}.ogg";
                var tgAudioStream   = new FileStream(tgAudioFilePath, FileMode.Create);
                await _tgBotClient.GetInfoAndDownloadFileAsync(e.Message.Voice.FileId, tgAudioStream);

                tgAudioStream.Close();

                var resultTextMessage = await RecognizeText(tgAudioFilePath);

                File.Delete(tgAudioFilePath);

                await _tgBotClient.EditMessageTextAsync(
                    chatId : message.Chat.Id,
                    messageId : message.MessageId,
                    text : resultTextMessage
                    );
            }
        }
Пример #5
0
 public async Task <Message> SendOrUpdate(ChatId chat, string text, IReplyMarkup replyMarkup = null, int?messageId = null)
 {
     try
     {
         Message message;
         if (messageId.HasValue)
         {
             message = await _botClient.EditMessageTextAsync(
                 messageId : messageId.Value,
                 chatId : chat,
                 text : text,
                 replyMarkup : (InlineKeyboardMarkup)replyMarkup,
                 parseMode : ParseMode.Html
                 );
         }
         else
         {
             message = await _botClient.SendTextMessageAsync(
                 chat,
                 text,
                 replyMarkup : replyMarkup,
                 parseMode : ParseMode.Html
                 );
         }
         return(message);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"SendOrUpdate() Error for params: chat:{chat.Identifier}:{chat.Username}, text:{text}, isUpdate:{messageId.HasValue}");
         Console.WriteLine($"{ex.Message} - \n {ex.StackTrace}");
         return(null);
     }
 }
Пример #6
0
        private async void BotOnCallbackQueryReceived(object sender, CallbackQueryEventArgs callbackQueryEventArgs)
        {
            //Here implements actions on reciving
            var callbackQuery = callbackQueryEventArgs.CallbackQuery;

            var inlineKeyboard = GetInlineKeyboardMarkup(callbackQuery.Data);

#if DEBUG
            await _bot.AnswerCallbackQueryAsync(
                callbackQuery.Id,
                $"Received {callbackQuery.Data}");
#endif
            if (inlineKeyboard.Text != null && inlineKeyboard.ReplyMarkup != null)
            {
                await _bot.EditMessageTextAsync(
                    callbackQuery.Message.Chat.Id,
                    callbackQuery.Message.MessageId,
                    inlineKeyboard.Text,
                    ParseMode.Default,
                    false,
                    inlineKeyboard.ReplyMarkup);
            }

            //Send message back
            //await Bot.SendTextMessageAsync(
            //    callbackQuery.Message.Chat.Id,
            //    $"Received {callbackQuery.Data}");
        }
Пример #7
0
        public async Task TryEdit(Message message)
        {
            var messageType = _vacancyAnalyzer.GetMessageType(message);

            if (messageType == MessageTypes.Chat)
            {
                return;
            }

            if (messageType == MessageTypes.Vacancy)
            {
                if (!_vacancyAnalyzer.HasMissingTags(message))
                {
                    await TryDeleteMissingTagsWarning(message);
                }
            }

            if (_memoryCache.TryGetValue(GetKey(message), out ChatMessageId repostedMessageIds))
            {
                await _telegramBot.EditMessageTextAsync(
                    repostedMessageIds.ChatId,
                    repostedMessageIds.MessageId,
                    GetMessageWithAuthor(message),
                    ParseMode.Html);
            }
        }
Пример #8
0
        public void Execute()
        {
            Response <IList <RssEntity> > rssRemove = _queryRssService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id);

            InlineKeyboardButton[][] keyboardButtonsListrssRemove = new InlineKeyboardButton[rssRemove.ResponseData.Count + 1][];
            keyboardButtonsListrssRemove = new InlineKeyboardButton[rssRemove.ResponseData.Count + 1][];

            for (int i = 0; i < rssRemove.ResponseData.Count; i++)
            {
                int count = _queryRssChatRelationService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id, rssRemove.ResponseData[i].AliasName, CDO.Enums.Chat.ListChatRelation.ByAliasName).ResponseData.Count;
                if (count.Equals(0))
                {
                    keyboardButtonsListrssRemove[i] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData(rssRemove.ResponseData[i].AliasName, string.Concat("RemoveRss_", rssRemove.ResponseData[i].Id)) }
                }
                ;
            }

            keyboardButtonsListrssRemove[rssRemove.ResponseData.Count] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "you can only remove rss that is not attached to any group or channel. listed below that is not attached to any group or channel.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtonsListrssRemove.Where(x => x != null).ToArray())).GetAwaiter();
        }
    }
Пример #9
0
    public static Task <Message> FinalizeStatusMessageAsync(this ITelegramBotClient client, Message message,
                                                            string postfix = "")
    {
        string text = $"_{message.Text}_ Готово\\.{postfix}";

        return(client.EditMessageTextAsync(message.Chat.Id, message.MessageId, text, ParseMode.MarkdownV2));
    }
        public void Execute()
        {
            Response <IList <ChannelEntity> > channelsRemove = _queryChannelService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id, CDO.Enums.Chat.ChatType.Group);

            InlineKeyboardButton[][] keyboardButtonsListChannelsRemove = new InlineKeyboardButton[channelsRemove.ResponseData.Count + 1][];
            keyboardButtonsListChannelsRemove = new InlineKeyboardButton[channelsRemove.ResponseData.Count + 1][];

            for (int i = 0; i < channelsRemove.ResponseData.Count; i++)
            {
                int count = _queryRssChatRelationService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id, channelsRemove.ResponseData[i].Name, CDO.Enums.Chat.ListChatRelation.ByChatName).ResponseData.Count;
                if (count.Equals(0))
                {
                    keyboardButtonsListChannelsRemove[i] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData(channelsRemove.ResponseData[i].Name, string.Concat("RemoveGroup_", channelsRemove.ResponseData[i].Name)) }
                }
                ;
            }

            keyboardButtonsListChannelsRemove[channelsRemove.ResponseData.Count] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "to remove channel, choose one.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtonsListChannelsRemove.Where(x => x != null).ToArray())).GetAwaiter();
        }
    }
Пример #11
0
 /// <summary>
 /// Edits a text message with auto retry to work around Telegram API's rate limit.
 /// </summary>
 /// <inheritdoc cref="TelegramBotClientExtensions.EditMessageTextAsync(ITelegramBotClient, ChatId, int, string, ParseMode?, IEnumerable{MessageEntity}?, bool?, InlineKeyboardMarkup?, CancellationToken)"/>
 public static async Task <Message> EditMessageTextWithRetryAsync(
     this ITelegramBotClient botClient,
     ChatId chatId,
     int messageId,
     string text,
     ParseMode?parseMode = null,
     IEnumerable <MessageEntity>?entities = null,
     bool?disableWebPagePreview           = null,
     InlineKeyboardMarkup?replyMarkup     = null,
     CancellationToken cancellationToken  = default)
 {
     while (true)
     {
         try
         {
             return(await botClient.EditMessageTextAsync(chatId,
                                                         messageId,
                                                         text,
                                                         parseMode,
                                                         entities,
                                                         disableWebPagePreview,
                                                         replyMarkup,
                                                         cancellationToken));
         }
         catch (ApiRequestException ex) when(ex.ErrorCode == 429)
         {
             await Task.Delay(GetRetryWaitTimeMs(ex), cancellationToken);
         }
     }
 }
Пример #12
0
        public override async Task RenderAsync(CallbackQuery callbackQuery)
        {
            var keyboardForm = new InlineKeyboardBuilder();

            keyboardForm.AddButtonRow(InlineKeyboardButton.WithCallbackData("Weather in realtime", "MainMenu.WeatherInRealTime+"));

            await _telegramBotClient.EditMessageTextAsync(callbackQuery.From.Id, callbackQuery.Message.MessageId, "Main Menu:", replyMarkup : keyboardForm.GetInlineKeyboard());
        }
Пример #13
0
 /// <summary>
 /// Редактирование сообщения
 /// </summary>
 /// <param name="message">Сообщение которое надо изменить</param>
 /// <param name="messageText">Текст нового сообщения</param>
 /// <param name="isAccumulate">Накапливать по умолчанию да</param>
 public void EditMessage(Message message, string messageText, bool isAccumulate = true)
 {
     if (isAccumulate)
     {
         message.Text += Environment.NewLine + messageText;
         messageText   = message.Text;
     }
     botClient.EditMessageTextAsync(message.Chat, message.MessageId, messageText, Telegram.Bot.Types.Enums.ParseMode.Html);
 }
        public override async Task RenderAsync(CallbackQuery callbackQuery)
        {
            var keyboardForm = new InlineKeyboardBuilder();

            keyboardForm.AddButtonRow(InlineKeyboardButton.WithCallbackData("MainMenu", "MainMenu+Unsubscribe"))
            .AddButtonRow(InlineKeyboardButton.WithCallbackData("StopAutoRefresh", "MainMenu.WeatherInRealTime+Unsubscribe"));

            await _telegramBotClient.EditMessageTextAsync(callbackQuery.From.Id, callbackQuery.Message.MessageId, "Autorefreshing\n CurrentWeather:\n" + CurrentWeather.Get(), replyMarkup : keyboardForm.GetInlineKeyboard());
        }
 public static async Task EditMessageAsync(ChatId chatId, string text, int messageId = 0,
                                           InlineKeyboardMarkup keyboardMarkup       = null)
 {
     await botClient.EditMessageTextAsync(
         chatId : chatId,
         messageId : messageId,
         text : text,
         replyMarkup : keyboardMarkup
         );
 }
Пример #16
0
        public async Task HandleCallbackQuery(CallbackQuery callbackQuery)
        {
            var userFrom     = callbackQuery.From;
            var userFullName = $"{userFrom.FirstName} {userFrom.LastName}";

            var originalMessageId = callbackQuery.Message.MessageId;

            if (callbackQuery.Data == CallbackButtonDataContants.OptIn)
            {
                var userParticipance = _botContext.Participance
                                       .SingleOrDefault(p => p.UserId == userFrom.Id && p.MessageId == originalMessageId);
                if (userParticipance is null)
                {
                    _botContext.Participance.Add(new Participance
                    {
                        UserId    = userFrom.Id,
                        MessageId = originalMessageId,
                        UserName  = userFullName
                    });
                    _botContext.SaveChanges();

                    await SendRegisteredNotification(callbackQuery.Message, userFullName);
                }
            }
            if (callbackQuery.Data == CallbackButtonDataContants.OptOut)
            {
                var p = _botContext.Participance.SingleOrDefault(p => p.UserId == userFrom.Id && p.MessageId == originalMessageId);
                if (p != null)
                {
                    _botContext.Participance.Remove(p);
                    _botContext.SaveChanges();

                    await SendChangedMindNotification(callbackQuery.Message, userFullName);
                }
            }

            var users = _botContext.Participance.Where(p => p.MessageId == originalMessageId).Select(p => p.UserName).ToList();

            var messageText = users.Count > 0
                ? $"Сегодня играют: {string.Join(", ", users)}"
                : "Кто был, уже все успели отказаться";

            if (callbackQuery.Message.Text == messageText)
            {
                return;
            }
            await _telegram.EditMessageTextAsync(
                callbackQuery.Message.Chat.Id,
                originalMessageId,
                messageText,
                replyMarkup : new InlineKeyboardButton[] {
                InlineKeyboardButton.WithCallbackData("Я в деле", CallbackButtonDataContants.OptIn),
                InlineKeyboardButton.WithCallbackData("Я передумал", CallbackButtonDataContants.OptOut)
            });
        }
Пример #17
0
        public async Task EditTextAsync(ChatId chatId, int messageId, string text,
                                        ParseMode parseMode        = ParseMode.Default,
                                        bool disableWebPagePreview = false, IReplyMarkup replyMarkup = null)
        {
            _logger.LogDebug("Editing text message...");

            var message = await _client.EditMessageTextAsync(chatId, messageId, text,
                                                             parseMode, disableWebPagePreview, replyMarkup);

            _logger.LogDebug("Message Edited");
            _logger.LogTrace($"<< {message.Chat.Id} {message.From.Id} {message.MessageId} {message.Type} {message.Text}");
        }
Пример #18
0
 public static Message Edit(long chatid, int messageid, string text, ParseMode parseMode = ParseMode.Html, bool disableWebPagePreview = true, IReplyMarkup replyMarkup = null)
 {
     try
     {
         return(Api.EditMessageTextAsync(chatid, messageid, text, parseMode, disableWebPagePreview, replyMarkup).Result);
     }
     catch
     {
         //...
         return(null);
     }
 }
Пример #19
0
        public void Execute()
        {
            InlineKeyboardButton[][] keyboardButtons = new InlineKeyboardButton[1][];

            keyboardButtons[0] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Channels"), InlineKeyboardButton.WithCallbackData("Groups"), InlineKeyboardButton.WithCallbackData("Rss") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "List/Edit channels or groups or rss. Choose one of the below.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtons)).GetAwaiter();
        }
Пример #20
0
        public async Task ExecuteCallbackQueryAsync(long chatId, int messageId, string callbackQueryId, string payload)
        {
            var pageCount = int.Parse(payload);
            var pageModel = _firewallPaginatorService.GetPage(pageCount);

            await _telegramBotClient.EditMessageTextAsync(
                chatId : chatId,
                messageId : messageId,
                text : pageModel.MessageText,
                parseMode : ParseMode.Markdown,
                replyMarkup : pageModel.Keyboard);
        }
Пример #21
0
        public void Execute()
        {
            InlineKeyboardButton[][] keyboardButtonsRss = new InlineKeyboardButton[2][];
            keyboardButtonsRss[0] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("List Rss"), InlineKeyboardButton.WithCallbackData("Remove Rss"), InlineKeyboardButton.WithCallbackData("Add Rss") };
            keyboardButtonsRss[1] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "List/Edit Rss.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtonsRss)).GetAwaiter();
        }
Пример #22
0
        public async Task AnswerInlineKeyboard(ITelegramBotClient client, User from, Message message, string answer, CancellationToken cancellationToken)
        {
            var tasks = new List <Task>(2);

            tasks.Add(
                client.EditMessageTextAsync(message.Chat.Id, message.MessageId, string.Format(L10n.strings.InlineQueryAnswerMessage, message.Text, answer), parseMode: ParseMode.Markdown, cancellationToken: cancellationToken)
                );
            tasks.Add(_session.RemoveAsync(message.Chat.Id, cancellationToken));

            if (answer != L10n.strings.YesKeyword)
            {
                await Task.WhenAll(tasks); return;
            }

            tasks.Add(
                client.SendTextMessageAsync(message.Chat.Id, L10n.strings.StoppedBotMessage, cancellationToken: cancellationToken)
                );

            var user = await _userRepository.GetByIdentifierAsync(from.Id, cancellationToken);

            if (user.Identifier != from.Id)
            {
                var authorizedUser = user.AuthorizedUsers.Single(x => x.Identifier == from.Id);
                user.AuthorizedUsers.Remove(authorizedUser);
                _userCache.AddOrUpdate(user);
                tasks.Add(_userRepository.RemoveAuthorizedUserAsync(user.Identifier, authorizedUser, cancellationToken));
            }
            else
            {
                _userCache.Remove(user.Identifier);
                tasks.Add(_userRepository.DeleteAsync(user.Identifier, cancellationToken));
                tasks.Add(_packagesRepository.DeleteByUsernameAsync(user.Username, cancellationToken));
                if (user.AuthorizedUsers?.Any() == true)
                {
                    tasks.Add(
                        client.SendTextMessageAsync(message.Chat.Id, L10n.strings.StoppedBotFollowUpMessage, cancellationToken: cancellationToken)
                        );
                }

                foreach (var authorizedUser in user.AuthorizedUsers)
                {
                    tasks.Add(
                        client.SendTextMessageAsync(
                            authorizedUser.ChatIdentifier,
                            string.Format(L10n.strings.StoppedBotAuthorizedUsersMessage, user.Username),
                            cancellationToken: cancellationToken
                            )
                        );
                }
            }

            await Task.WhenAll(tasks);
        }
Пример #23
0
 public static Message Edit(string newtext, long chatid, int messageid, IReplyMarkup replyMarkup = null, ParseMode parseMode = ParseMode.Html, bool disableWebPagePreview = true)
 {
     try
     {
         var t = Api.EditMessageTextAsync(chatid, messageid, newtext, parseMode, disableWebPagePreview, replyMarkup);
         t.Wait();
         return(t.Result);
     }
     catch
     {
         return(null);
     }
 }
Пример #24
0
        // Todo Make it work as expected
        // Need to identify type of message and then call method with specified message
        public async Task <bool> EditMessage(long chatId, long messageId, OutMessage message)
        {
            try
            {
                await _api.EditMessageTextAsync((int)chatId, (int)messageId, message.Text).ConfigureAwait(false);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Пример #25
0
        public void Execute()
        {
            Response <IList <RssEntity> > rss = _queryRssService.GetList(_callbackQueryEventArgs.CallbackQuery.From.Id);

            if (!rss.ResponseData.Count.Equals(0))
            {
                InlineKeyboardButton[][] keyboardButtonsListrss = new InlineKeyboardButton[rss.ResponseData.Count + 1][];
                keyboardButtonsListrss = new InlineKeyboardButton[rss.ResponseData.Count + 1][];

                for (int i = 0; i < rss.ResponseData.Count; i++)
                {
                    int count = _queryRssChatRelationService.GetList(rss.ResponseData[i].AliasName).ResponseData.Count;
                    keyboardButtonsListrss[i] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData(string.Concat(rss.ResponseData[i].AliasName, " (", count, ")"), string.Concat("Rss_", rss.ResponseData[i].AliasName)) };
                }

                keyboardButtonsListrss[rss.ResponseData.Count] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

                _telegramBotClient.EditMessageTextAsync(
                    _callbackQueryEventArgs.CallbackQuery.From.Id,
                    _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                    "in order to list atached groups and channels, choose one.",
                    replyMarkup: new InlineKeyboardMarkup(keyboardButtonsListrss)).GetAwaiter();
            }
            else
            {
                InlineKeyboardButton[][] keyboardButtonsListrss = new InlineKeyboardButton[2][];
                keyboardButtonsListrss = new InlineKeyboardButton[2][];

                keyboardButtonsListrss[0] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Add Rss") };
                keyboardButtonsListrss[1] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

                _telegramBotClient.EditMessageTextAsync(
                    _callbackQueryEventArgs.CallbackQuery.From.Id,
                    _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                    "you don't have any rss link.",
                    replyMarkup: new InlineKeyboardMarkup(keyboardButtonsListrss)).GetAwaiter();
            }
        }
Пример #26
0
        public static async Task <Message?> SendOrUpdateMessage(this ITelegramBotClient bot, TelegramChatStatusDesc desc, string?text, IReplyMarkup replyMarkup = null, bool onlysend = false, CancellationToken ct = default(CancellationToken))
        {
            if (bot == null)
            {
                return(null);
            }
            if (desc == null)
            {
                return(null);
            }
            await bot.DeleteMessageIdAsync(desc, desc.DeleteAlsoMessageId);

            desc.DeleteAlsoMessageId = 0;
            int deleteNext = 0;

            if (onlysend)
            {
                // we save the previous message that will be deleted next time, so the next sent message will be under this one that we are sending now
                deleteNext         = desc.LastMessageId;
                desc.LastMessageId = 0;
            }
            int editMessageId = desc.LastMessageId;

            // try to edit/delete old message
            InlineKeyboardMarkup inreplyMarkup = replyMarkup as InlineKeyboardMarkup;

            if (editMessageId != 0 && (replyMarkup == null || inreplyMarkup != null))
            {
                if (desc.DeleteMessage == false)
                {
                    try
                    {
                        //System.Diagnostics.Debug.WriteLine($"1. msg to: {desc.ChatId.Identifier}, {text}");
                        var msgout = await bot.EditMessageTextAsync(desc.ChatId, editMessageId, text, parseMode : ParseMode.Html, disableWebPagePreview : true, replyMarkup : inreplyMarkup, cancellationToken : ct);

                        //System.Diagnostics.Debug.WriteLine($"2. msg to: {desc.ChatId.Identifier}, {text}");
                        return(msgout);
                    }
                    catch (ApiRequestException ar)
                    {
                        if (ar.Message.Contains("message is not modified"))
                        {
                            return(null);
                        }
                        else
                        {
                            log.Debug($"{desc}", ar);
                        }
                    }
                }
Пример #27
0
 public static async void EditMessage(ITelegramBotClient botClient, CallbackQueryEventArgs e, string text)
 {
     try
     {
         await botClient.EditMessageTextAsync(
             chatId : e.CallbackQuery.Message.Chat.Id,
             messageId : e.CallbackQuery.Message.MessageId,
             text : text,
             ParseMode.Default,
             false
             ).ConfigureAwait(false);
     }
     catch { }
 }
Пример #28
0
        public async Task AnswerLoginAttemptNotification(ITelegramBotClient client, User user, Message message, string answer, SecondaryUser attemptingUser, CancellationToken cancellationToken)
        {
            var tasks = new List <Task>(6);

            tasks.Add(
                client.EditMessageTextAsync(message.Chat.Id, message.MessageId, string.Format(L10n.strings.InlineQueryAnswerMessage, message.Text, answer), parseMode: ParseMode.Markdown, cancellationToken: cancellationToken)
                );
            if (answer == L10n.strings.LoginAttemptDenyKeyword)
            {
                tasks.AddRange(new[]
                {
                    client.SendTextMessageAsync(message.Chat, L10n.strings.ChangeYourPasswordWarningMessage, cancellationToken: cancellationToken),
                    client.SendTextMessageAsync(attemptingUser.ChatIdentifier, L10n.strings.DeniedLoginAttemptMessage, cancellationToken: cancellationToken),
                    _userRepository.UpdateUnauthorizedUsersAsync(user.Id, attemptingUser, cancellationToken)
                });
            }
            else if (answer == L10n.strings.LoginAttemptAllowKeyword)
            {
                tasks.AddRange(new[]
                {
                    client.SendTextMessageAsync(attemptingUser.ChatIdentifier, L10n.strings.AllowedLoginAttemptMessage, cancellationToken: cancellationToken),
                    _userRepository.UpdateAuthorizedUsersAsync(user.Id, attemptingUser, cancellationToken)
                });
            }

            tasks.AddRange(new[]
            {
                _session.RemoveAsync(attemptingUser.ChatIdentifier, cancellationToken),
                _session.RemoveAsync(message.Chat.Id, cancellationToken)
            });

            await Task.WhenAll(tasks);

            if (answer != L10n.strings.LoginAttemptAllowKeyword)
            {
                return;
            }

            var cachedUser = await _userCache.GetLoggedUserAsync(user.Id, cancellationToken);

            cachedUser.AuthorizedUsers = cachedUser.AuthorizedUsers ?? new List <SecondaryUser>(1);
            cachedUser.AuthorizedUsers.Add(attemptingUser);
            _userCache.AddOrUpdate(cachedUser);

            var packages = await _flypack.GetCurrentPackagesAsync(user.Id, cancellationToken);

            await SendPackagesToChat(client, packages, attemptingUser.ChatIdentifier, cancellationToken);
        }
        public void Execute()
        {
            InlineKeyboardButton[][] keyboardButtonsChannels = new InlineKeyboardButton[2][];
            keyboardButtonsChannels[0] = new InlineKeyboardButton[]
            {
                InlineKeyboardButton.WithCallbackData("List Channels"),
                InlineKeyboardButton.WithCallbackData("Remove Channel"),
                InlineKeyboardButton.WithCallbackData("Add Channel")
            };
            keyboardButtonsChannels[1] = new InlineKeyboardButton[] { InlineKeyboardButton.WithCallbackData("Back to Home") };

            _telegramBotClient.EditMessageTextAsync(
                _callbackQueryEventArgs.CallbackQuery.From.Id,
                _callbackQueryEventArgs.CallbackQuery.Message.MessageId,
                "to get updates from rss, you can add channels and attach rss to them.",
                replyMarkup: new InlineKeyboardMarkup(keyboardButtonsChannels)).GetAwaiter();
        }
Пример #30
0
        public async Task UpdateMessageAsync(InlineKeyboardMarkup replyMarkup = null)
        {
            var text = new StringBuilder()
                       .AppendLine("Let's send a smelly surprise!")
                       .AppendLine()
                       .AppendLine("*Animal* » " + Animal.Key)
                       .AppendLine("*Sticker* » " + Sticker.Key)
                       .AppendLine()
                       .AppendLine("*Recipient's full name* » " + RecipientFullName)
                       .AppendLine("*Street address* » " + StreetAddress)
                       .AppendLine("*Town / City* » " + TownCity)
                       .AppendLine("*Postcode* » " + Postcode)
                       .AppendLine("*State / County (optional)* » " + StateCounty)
                       .AppendLine("*Country* » " + Country.Key)
                       .AppendLine("*Message for the recipient (optional)* » " + Message)
                       .AppendLine()
                       .AppendLine("*Your email address (optional - notifications only)* » " + Email);

            await _bot.EditMessageTextAsync(_orderMessage.Chat, _orderMessage.MessageId, text.ToString(), ParseMode.Markdown, replyMarkup : replyMarkup ?? _menuReplyMarkup);
        }