private async Task OnBotMessage(ITelegramBotClient client, Message message, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Received a text message in {ChatId}, from: {UserId}. Message: {Message}", message.Chat.Id, message.From.Id, message.Text);
            if (message.Text?.StartsWith('/') == true)
            {
                await client.SendChatActionAsync(message.Chat, ChatAction.Typing, cancellationToken);
                await AnswerBotCommandAsync(client, message, cancellationToken);
            }
            else if (_session.Get(message.Chat.Id) is ChatSession session)
            {
                await client.SendChatActionAsync(message.Chat, ChatAction.Typing, cancellationToken);

                switch (session.Scope)
                {
                case SessionScope.Login:
                    await _startCommand.Login(client, message, cancellationToken);

                    break;

                default: break;
                }
            }

            return;
        }
Exemplo n.º 2
0
            // Send inline keyboard
            // You can process responses in BotOnCallbackQueryReceived handler
            static async Task SendInlineKeyboard(Message message)
            {
                await botClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                // Simulate longer running task
                await Task.Delay(500);

                var inlineKeyboard = new InlineKeyboardMarkup(new[]
                {
                    // first row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("1.1", "11"),
                        InlineKeyboardButton.WithCallbackData("1.2", "12"),
                    },
                    // second row
                    new []
                    {
                        InlineKeyboardButton.WithCallbackData("2.1", "21"),
                        InlineKeyboardButton.WithCallbackData("2.2", "22"),
                    }
                });
                await botClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : "Choose",
                    replyMarkup : inlineKeyboard
                    );
            }
Exemplo n.º 3
0
        protected override async Task HandleAsync(Message message, string[] arguments, RequestDelegate nextHandler)
        {
            var chatId = message.Chat.Id;

            var faculties = await _scheduleParser.ParseFacultiesAsync();

            var inlineKeyboard = faculties.ToInlineKeyboard
                                 (
                faculty => faculty.TitleAbbreviation,
                columnsCount: 2
                                 );

            await _client.SendChatActionAsync
            (
                chatId,
                chatAction : ChatAction.Typing
            );

            var request = await _client.SendTextMessageAsync
                          (
                chatId,
                text : "Выберите факультет, к которому Вас нужно прикрепить:",
                replyMarkup : inlineKeyboard
                          );

            _callbackQueryListener.RegisterRequest
            (
                request,
                HandleIncomingFacultyAsync
            );

            _logger?.LogInformation("Bind command processed");
        }
Exemplo n.º 4
0
        public async Task StartCommandAsync(Message message)
        {
            var isCommand = _commands.TryGetCommand(message.Text, out var command);

            try
            {
                if (isCommand)
                {
                    _logger.LogInformation($"Start command {command.GetType().Name}. UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}");
                    await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                    await command !.ExecuteCommandAsync(message);
                    _logger.LogInformation($"End command {command.GetType().Name}. UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}");
                }
                else
                {
                    var state   = _storageService.Get <BotStateType>(StorageKeys.BotCurrentState);
                    var isState = _stateHandlers.TryGetStateHandler(state, out var stateHandler);

                    if (isState)
                    {
                        _logger.LogInformation($"Start handler {stateHandler.GetType().Name}. UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}, State={state.ToString()}, Payload={message.Text}");
                        await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

                        await stateHandler.ExecuteHandlerAsync(message);

                        _logger.LogInformation($"End handler {stateHandler.GetType().Name}. UserId={message.From.Id.ToString()}, ChatId={message.Chat.Id.ToString()}, State={state.ToString()}, Payload={message.Text}");
                    }
                }
            }
            catch (ApiException ex)
            {
                _logger.LogError(ex, $"Error={ex.Message}, UserId={message.From.Id.ToString()}, Payload={message.Text}");

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetDigitalOceanApiErrorMessage(ex.Message));
            }
            catch (OperationCanceledException ex)
            {
                _logger.LogError(ex, $"Error={ex.Message}, UserId={message.From.Id.ToString()}, Payload={message.Text}");

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetOperationCanceledErrorMessage());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"Error={ex.Message}, UserId={message.From.Id.ToString()}, Payload={message.Text}");

                await _telegramBotClient.SendTextMessageAsync(
                    chatId : message.Chat.Id,
                    text : CommonMessage.GetCriticalErrorMessage(ex.Message));
            }
        }
Exemplo n.º 5
0
        protected override async Task HandleAsync(Message message, string[] arguments, RequestDelegate nextHandler)
        {
            var chatId = message.Chat.Id;

            await _client.SendChatActionAsync
            (
                chatId,
                chatAction : ChatAction.Typing
            );

            var incomingDateTime = arguments.FirstOrDefault();

            if (DateTime.TryParse(incomingDateTime, out DateTime dateTime))
            {
                if (dateTime.DayOfWeek.Equals(DayOfWeek.Sunday))
                {
                    await _client.SendTextMessageAsync
                    (
                        chatId,
                        text : $"{dateTime.ToShortDateString()} - выходной день. Используйте /schedule, чтобы получить расписание на следующую неделю"
                    );
                }
                else
                {
                    var groupTitle = arguments.LastOrDefault();

                    if (arguments.Length > 1 && !string.IsNullOrWhiteSpace(groupTitle))
                    {
                        await SendScheduleAsync(chatId, dateTime, groupTitle);
                    }
                    else
                    {
                        await SendScheduleAsync(chatId, dateTime);
                    }
                }
            }
            else
            {
                var request = await _client.SendTextMessageAsync
                              (
                    chatId,
                    text : "Выберите учебную неделю:",
                    replyMarkup : DateTime.Today.ToWeekDatesKeyboard(_weekDatesProvider)
                              );

                _callbackQueryListener.RegisterRequest
                (
                    request,
                    HandleIncomingWeekAsync
                );
            }

            _logger?.LogInformation("Schedule command processed");
        }
        private async void _telegramBotClient_OnCallbackQuery(object sender, Telegram.Bot.Args.CallbackQueryEventArgs e)
        {
            await _telegramBotClient.SendChatActionAsync(e.CallbackQuery.Message.Chat.Id, ChatAction.Typing);

            var level = int.Parse(e.CallbackQuery.Data);

            await SendStartingMessage(e.CallbackQuery.Message);

            var story = await _storyRepository.GetAnyStoryAsync(level);

            if (story == null)
            {
                await _telegramBotClient.SendChatActionAsync(e.CallbackQuery.Message.Chat.Id, ChatAction.Typing);

                await _telegramBotClient.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, $"Ops! We are so sorry. 😿 We don't have A1 level story.");

                return;
            }

            await SendImageWhenExists(e.CallbackQuery.Message, story);

            await SendStoryInformation(e.CallbackQuery.Message, story);

            await SendStoryContent(e.CallbackQuery.Message, story);

            await SendSoundWhenExists(e.CallbackQuery.Message, story);

            await _telegramBotClient.SendTextMessageAsync(e.CallbackQuery.Message.Chat.Id, $"Don't be a stranger! 💖");
        }
Exemplo n.º 7
0
        public async IAsyncEnumerable <MessageResponse> HandleMessageAsync(Message message, NextHandler nextHandler)
        {
            Message?respondedMessage = null;

            await using var enumerator = nextHandler().GetAsyncEnumerator();

            while (true)
            {
                MessageResponse response;

                try
                {
                    if (!await enumerator.MoveNextAsync())
                    {
                        break;
                    }

                    response = enumerator.Current;
                }
                catch (HandlerException e)
                {
                    response = e.Message.ToString();
                }

                await _client.SendChatActionAsync(message.Chat, ChatAction.Typing);

                if (respondedMessage is null || response.ForceNewMessage)
                {
                    respondedMessage = await _client.SendTextMessageAsync(message.Chat, response.ToString(),
                                                                          parseMode : response.ParseMode,
                                                                          disableWebPagePreview : true,
                                                                          replyToMessageId : message.Chat.Type != ChatType.Private?message.MessageId : 0,
                                                                          replyMarkup : GetReplyMarkup(response.ExtraMarkup));
                }
        public async Task Process(Update update)
        {
            if (update.Message.Text == "/switchDebug")
            {
                var existing = DebugSessions.FirstOrDefault(v => v.Identifier == update.Message.Chat.Id);
                if (existing != null)
                {
                    DebugSessions.Remove(existing);
                }
                else
                {
                    DebugSessions.Add(update.Message.Chat.Id);
                }
            }

            _logger.LogInformation(JsonConvert.SerializeObject(update));

            await Extensions.Retry(() => _client.SendChatActionAsync(update.Message.Chat.Id, ChatAction.Typing));

            try
            {
                var message = update.Message;

                var response = await _svc.SendRequest(update.Message.Text ?? "", message.Chat.Id.ToString());

                SendToDebug(response + "\r\n" + JsonConvert.SerializeObject(message));
            }
            catch (Exception ex)
            {
                SendToDebug(ex.ToString());
                _logger.LogError(ex.ToString());
            }
        }
Exemplo n.º 9
0
        public async Task <bool> SendMessageAsync(long chatId, ITgOutboundMessage message)
        {
            char[] toLog    = message.Message?.Take(100).ToArray();
            string msgToLog = toLog == null ? string.Empty : new string(toLog);

            Trace.TraceInformation($"SendMessage id: {chatId} msg: {msgToLog}...");

            try
            {
                IReplyMarkup replyMarkup = message.ReplyKeyboard;
                replyMarkup ??= new ReplyKeyboardRemove();

                foreach (string msg in SplitMessage(message.IsEscaped ? message.Message : message.Message.EscapeMessageForMarkupV2()))
                {
                    await Policy
                    .Handle <HttpRequestException>()
                    .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
                    .ExecuteAsync(async() =>
                    {
                        await _botClient.SendChatActionAsync(chatId, ChatAction.Typing);
                        await _botClient.SendTextMessageAsync(chatId, msg, parseMode: ParseMode.MarkdownV2, replyMarkup: replyMarkup);
                    });
                }
            }
            catch (Exception exception)
            {
                Trace.TraceInformation($"SendMessage: {chatId} {message} failed. Exception {exception.Message}{Environment.NewLine}{exception.StackTrace}");
                return(false);
            }

            return(true);
        }
Exemplo n.º 10
0
        private static async Task SendDialog(ITelegramBotClient bot, Session session, Dialog dialog)
        {
            for (var i = 0; i < dialog.Phrases.Length; i++)
            {
                await bot.SendChatActionAsync(session.Id, ChatAction.Typing);

                await Task.Delay(500);

                IReplyMarkup reply;
                if (i == dialog.Phrases.Length - 1 && dialog.Dialogs.Count > 0)
                {
                    var keyboard = new List <KeyboardButton>();
                    foreach (var choice in dialog.Dialogs)
                    {
                        keyboard.Add(new KeyboardButton(choice.Label));
                    }
                    reply = new ReplyKeyboardMarkup(keyboard.ToArray(), oneTimeKeyboard: true, resizeKeyboard: true);
                }
                else
                {
                    reply = new ReplyKeyboardRemove();
                }

                await bot.SendTextMessageAsync(
                    chatId : session.Id,
                    text : dialog.Phrases[i],
                    parseMode : ParseMode.Html,
                    replyMarkup : reply
                    );
            }
        }
Exemplo n.º 11
0
        protected override async Task HandleAsync(Message message, string[] arguments, RequestDelegate nextHandler)
        {
            var chatId         = message.Chat.Id;
            var chatParameters = await _chatParametersService.GetChatParametersAsync(chatId);

            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("<b>Текущие настройки:</b>");

            if (chatParameters is not null)
            {
                stringBuilder.AppendLine($"Факультет: <i>{chatParameters.FacultyTitleWithoutTag}</i>")
                .AppendLine($"Группа: <i>{chatParameters.GroupTitle}</i>");
            }
            else
            {
                stringBuilder.AppendLine($"Отсутствуют")
                .AppendLine($"Используйте /bind, чтобы начать работу с ботом");
            }

            await _client.SendChatActionAsync
            (
                chatId,
                chatAction : ChatAction.Typing
            );

            await _client.SendTextMessageAsync
            (
                chatId,
                text : stringBuilder.ToString(),
                parseMode : ParseMode.Html
            );

            _logger?.LogInformation("Settings command processed");
        }
Exemplo n.º 12
0
        public async Task SendTextAsync(ChatId chatId, string text,
                                        ParseMode parseMode        = ParseMode.Default,
                                        bool disableWebPagePreview = false, bool disableNotification = false,
                                        int replyToMessageId       = 0, IReplyMarkup replyMarkup     = null)
        {
            _logger.LogDebug("Sending text message...");

            await _client.SendChatActionAsync(chatId, ChatAction.Typing);

            var message = await _client.SendTextMessageAsync(chatId, text,
                                                             parseMode, disableWebPagePreview, disableNotification,
                                                             replyToMessageId, replyMarkup);

            _logger.LogDebug("Message sent");
            _logger.LogTrace($"<< {message.Chat.Id} {message.From.Id} {message.MessageId} {message.Type} {message.Text}");
        }
Exemplo n.º 13
0
        public async Task SendWordForRecallAsync(ITelegramBotClient telegramBotClient, Message message)
        {
            var word = new Word
            {
                Meanings = new List <string> {
                    "(англ.) Погнали"
                },
                Value        = "Let's go",
                RecallValues = new List <string>
                {
                    "Побігли",
                    "Ходу звідси"
                }
            };

            await telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            (var text, var inlineKeyboard) = GenerateRecallData(word);

            await telegramBotClient.SendTextMessageAsync(
                chatId : message.Chat.Id,
                text,
                parseMode : ParseMode.Markdown,
                replyMarkup : inlineKeyboard
                );
        }
Exemplo n.º 14
0
        private async void BotOnMessageReceived(object sender, MessageEventArgs messageEventArgs)
        {
            var message = messageEventArgs.Message;

            if (message == null || message.Type != MessageType.Text)
            {
                return;
            }

            await _client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            LogMessages(message.Text, UserInput);
            if (message.Text.StartsWith(IndicateStartPhrase))
            {
                _previousMessage = message.Text;

                var result = await _weatherPhraseFacade.GetForecast(message.Text, message.From.Username);

                LogMessages(result, BotResponse);

                await _client.SendTextMessageAsync(message.Chat.Id, result);
            }
            else
            {
                LogMessages(DontUnderstandError, BotResponse);

                await _client.SendTextMessageAsync(message.Chat.Id, DontUnderstandError);
            }
        }
Exemplo n.º 15
0
 public static async void SendAction(ITelegramBotClient botClient, long userId, ChatAction chatAction)
 {
     try
     {
         await botClient.SendChatActionAsync(userId, chatAction);
     }
     catch { }
 }
Exemplo n.º 16
0
        public async Task ExecuteAsync(Message message)
        {
            await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            var word = await _wordRepository.GetAnyWordAsync();

            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"🇬🇧: {word.En}.\n🇹🇷: {word.Tr}");
        }
Exemplo n.º 17
0
        public async Task ExecuteAsync(Message message)
        {
            await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            var phrase = await _dailyPhraseRepository.GetAnyDailyPhraseAsync();

            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"🇬🇧: {phrase.En}.\n🇹🇷: {phrase.Tr}");
        }
Exemplo n.º 18
0
        private async Task BotOnMessageReceived(ITelegramBotClient client, Message message)
        {
            using var scope = _serviceScopeFactory.CreateScope();
            var serviceProvider = scope.ServiceProvider;

            if (message.Type != MessageType.Text) // We only analyze Text messages
            {
                return;
            }

            _logger.LogInformation($"Message received from chat id: {message.Chat.Id}");

            var chatConfig = await GetChatConfiguration(message.Chat.Id, serviceProvider, client);

            if (message.Text.StartsWith('/')) // Text is a command
            {
                var telegramCommandHandlerService = serviceProvider.GetService <ITelegramCommandHandlerService>();

                await telegramCommandHandlerService.HandleCommand(message);

                return;
            }

            if (chatConfig.IsBotStopped)
            {
                return;
            }

            var grammarService = GetConfiguredGrammarService(chatConfig, serviceProvider);

            // Remove emojis, hashtags, mentions and mentions of users without username
            var text = GetCleanedText(message);

            var corretionResult = await grammarService.GetCorrections(text);

            if (!corretionResult.HasCorrections)
            {
                return;
            }

            // Send "Typing..." notification
            await client.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            var messageBuilder = new StringBuilder();

            foreach (var correction in corretionResult.Corrections)
            {
                var correctionDetailMessage = !chatConfig.HideCorrectionDetails && !string.IsNullOrEmpty(correction.Message)
                    ? $"[{correction.Message}]"
                    : string.Empty;

                messageBuilder.AppendLine($"*{correction.PossibleReplacements.First()} {correctionDetailMessage}");
            }

            await client.SendTextMessageAsync(message.Chat.Id, messageBuilder.ToString(), replyToMessageId : message.MessageId);
        }
Exemplo n.º 19
0
        private async Task SendDocument(Message message)
        {
            await _client.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

            const string filePath = @"Files/tux.png";

            await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();
            await _client.SendPhotoAsync(message.Chat.Id, new InputOnlineFile(fileStream, fileName), "Nice Picture");
        }
Exemplo n.º 20
0
        public async Task ExecuteAsync(Message message)
        {
            await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            var text   = message.Text.Replace("/translate ", "");
            var result = await _translateService.Translate(new Translation("en", "tr", text));

            var firstSentence = result.Sentences.FirstOrDefault();

            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, $"🇬🇧: {firstSentence.Orig}\n🇹🇷: {firstSentence.Trans}");
        }
Exemplo n.º 21
0
        public async Task Execute(CallbackQuery callback, Message message, SessionState sessionState)
        {
            try
            {
                await _telegramBotClient.SendChatActionAsync(callback.From.Id, ChatAction.Typing);

                var callBackData = callback.Data.Split(';');

                switch (sessionState)
                {
                case SessionState.WaitChooseDropletsForFirewall when callBackData[0] == "SelectDroplet":
Exemplo n.º 22
0
        public async Task ExecuteAsync(Message message)
        {
            await _telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            string messageContent = $"🇬🇧: Hi {message.From.FirstName ?? message.From.Username} 👋\n" +
                                    $"I am Yusuf. I created this bot to make your work easier while you are studying English. I am here if you want to request a new feature, support or say hi. @yusufyilmazfr 🤗🌺\n\n" +

                                    $"🇹🇷: Merhaba {message.From.FirstName ?? message.From.Username} 👋\n" +
                                    $"Ben Yusuf. Bu botu, sizler İngilizce çalışırken işlerinizi kolaylaştırması için oluşturdum. Yeni özellik isteği, destek olmak veya bi' merhaba demek isterseniz buradayım ben. @yusufyilmazfr 🤗🌺";

            await _telegramBotClient.SendTextMessageAsync(message.Chat.Id, messageContent);
        }
Exemplo n.º 23
0
            static async Task <Message> SendFile(ITelegramBotClient botClient, Message message)
            {
                await botClient.SendChatActionAsync(message.Chat.Id, ChatAction.UploadPhoto);

                const string filePath = @"Files/tux.png";

                using FileStream fileStream = new(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                var fileName = filePath.Split(Path.DirectorySeparatorChar).Last();

                return(await botClient.SendPhotoAsync(chatId : message.Chat.Id,
                                                      photo : new InputOnlineFile(fileStream, fileName),
                                                      caption : "Nice Picture"));
            }
Exemplo n.º 24
0
        public async Task SendNewWordAsync(ITelegramBotClient telegramBotClient, Message message)
        {
            var words = await wordRepository.GetWordsAsync();

            var word = words.ToList().GetRandomElement();

            await telegramBotClient.SendChatActionAsync(message.Chat.Id, ChatAction.Typing);

            await telegramBotClient.SendTextMessageAsync(
                chatId : message.Chat.Id,
                text : FormatNewWordText(word),
                parseMode : ParseMode.Markdown
                );
        }
Exemplo n.º 25
0
        private static async void OnMessageReceivedAsync(object sender, MessageEventArgs messageEventArgs)
        {
            Message message = messageEventArgs.Message;

            if (message == null)
            {
                Console.WriteLine(@"Message is null.");
                return;
            }

            long chatId = message.Chat.Id;
            await _bot.SendChatActionAsync(chatId, ChatAction.Typing);

            await ProcessMessageParts(message, chatId);
        }
Exemplo n.º 26
0
        protected override async Task HandleAsync(Message message, string[] arguments, RequestDelegate nextHandler)
        {
            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("Чтобы обеспечить себе быстрый доступ к расписанию, используйте команду /bind.")
            .AppendLine("Также Вы можете добавить бота в свою Telegram-группу.")
            .AppendLine()
            .AppendLine("<i>Бот не хранит Ваши личные данные!</i>")
            .AppendLine()
            .AppendLine("<b>Вы можете использовать следующие команды:</b>")
            .AppendLine()
            .AppendLine("1. /settings - получить текущие настройки факультета и группы")
            .AppendLine()
            .AppendLine("2. /bind - изменить настройки факультета и группы")
            .AppendLine()
            .AppendLine("3. /schedule - получить актуальное расписание по заданной учебной неделе")
            .AppendLine()
            .AppendLine("4. /schedule <i>[дата (в любом формате)]</i> - получить актуальное расписание по заданному учебному дню")
            .AppendLine("Пример: <code>/schedule 01.09.2021</code>")
            .AppendLine()
            .AppendLine("5. /schedule <i>[дата (в любом формате)]</i> <i>[название группы]</i> - получить актуальное расписание по заданному учебному дню")
            .AppendLine("Пример: <code>/schedule 2021-9-1 ПМИ31</code>")
            .AppendLine()
            .AppendLine("6. /tomorrow - получить расписание на завтра")
            .AppendLine()
            .AppendLine("7. /tomorrow <i>[название группы]</i> - получить расписание на завтра для указанной группы.")
            .AppendLine("Пример: <code>/tomorrow ХИМ21</code>");

            var chatId = message.Chat.Id;

            await _client.SendChatActionAsync
            (
                chatId,
                chatAction : ChatAction.Typing
            );

            await _client.SendTextMessageAsync
            (
                chatId,
                text : stringBuilder.ToString(),
                parseMode : ParseMode.Html,
                disableWebPagePreview : true
            );

            _logger?.LogInformation("Help/Start command processed");
        }
        public async void SendTextMessage(string message, long chatId)
        {
            try
            {
                await bot.SendChatActionAsync(chatId, ChatAction.Typing);

                await Task.Delay(500);

                await bot.SendTextMessageAsync(
                    chatId : chatId,
                    text : message
                    );
            }
            catch (Exception ex)
            {
                //Some Exception logging process..
            }
        }
Exemplo n.º 28
0
 public async void SendMessageAsync(long chatId, string message)
 {
     Trace.TraceInformation($"SendMessage id: {chatId} msg: {new string(message.Take(100).ToArray())}...");
     try
     {
         await Policy
         .Handle <HttpRequestException>()
         .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
         .ExecuteAsync(async() =>
         {
             await _botClient.SendChatActionAsync(chatId, Telegram.Bot.Types.Enums.ChatAction.Typing);
             await _botClient.SendTextMessageAsync(chatId, message, parseMode: Telegram.Bot.Types.Enums.ParseMode.Markdown);
         });
     }
     catch (HttpRequestException ex)
     {
         Trace.TraceInformation("SendMessage: {chatId} {message} failed");
     }
 }
Exemplo n.º 29
0
        public async Task Handle(ITelegramBotClient client, Message message, CancellationToken cancellationToken)
        {
            await client.SendChatActionAsync(message.Chat, ChatAction.Typing, cancellationToken);

            var userExists = await _userRepository.ExistsAsync(message.From.Id, cancellationToken);

            var session = _session.Get(message.Chat.Id);

            if (userExists || session != null)
            {
                await client.SendTextMessageAsync(
                    chatId : message.Chat,
                    text : L10n.strings.WeHaveAlreadyMetMessage,
                    parseMode : ParseMode.Markdown,
                    replyToMessageId : message.MessageId,
                    cancellationToken : cancellationToken
                    );

                return;
            }

            await client.SendTextMessageAsync(
                chatId : message.Chat,
                text : L10n.strings.WelcomeMessage,
                parseMode : ParseMode.Markdown,
                cancellationToken : cancellationToken
                );

            await Task.Delay(_settings.ConsecutiveMessagesInterval, cancellationToken);

            var sent = await client.SendTextMessageAsync(
                chatId : message.Chat,
                text : L10n.strings.SendUsernameAndPasswordMessage,
                parseMode : ParseMode.Markdown,
                replyMarkup : new ForceReplyMarkup()
            {
                InputFieldPlaceholder = L10n.strings.UsernameAndPasswordPlaceholder
            },
                cancellationToken : cancellationToken
                );

            _session.Add(sent, message.From.Id, SessionScope.Login);
        }
        private async Task SendMessagesToChat(IEnumerable <string> messages, string lastMessage, long channel, CancellationToken cancellationToken)
        {
            foreach (var msg in messages)
            {
                await _telegram.SendTextMessageAsync(
                    chatId : channel,
                    text : msg,
                    parseMode : ParseMode.Markdown,
                    cancellationToken : cancellationToken
                    );

                if (msg != lastMessage)
                {
                    await _telegram.SendChatActionAsync(channel, ChatAction.Typing, cancellationToken);

                    await Task.Delay(_settings.ConsecutiveMessagesInterval, cancellationToken);
                }
            }
        }