Пример #1
0
        public async Task Should_Throw_When_Send_Invoice_Invalid_Provider_Data()
        {
            PaymentsBuilder paymentsBuilder = new PaymentsBuilder()
                                              .WithProduct(_ => _
                                                           .WithTitle(title: "Reproduction of \"La nascita di Venere\"")
                                                           .WithDescription(description:
                                                                            "Sandro Botticelli`s the Birth of Venus depicts the goddess Venus arriving at the shore" +
                                                                            " after her birth, when she had emerged from the sea fully-grown ")
                                                           .WithProductPrice(label: "Price of the painting", amount: 500_000)
                                                           .WithProductPrice(label: "Wooden frame", amount: 100_000)
                                                           .WithPhoto(
                                                               url: "https://cdn.pixabay.com/photo/2012/10/26/03/16/painting-63186_1280.jpg",
                                                               width: 1280,
                                                               height: 820
                                                               ))
                                              .WithCurrency("USD")
                                              .WithPayload("<my-payload>")
                                              .WithProviderData("INVALID-JSON")
                                              .WithPaymentProviderToken(_classFixture.PaymentProviderToken)
                                              .ToChat(_classFixture.PrivateChat.Id);

            SendInvoiceRequest requestRequest = paymentsBuilder.BuildInvoiceRequest();

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(
                async() => await BotClient.MakeRequestAsync(requestRequest)
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: DATA_JSON_INVALID", exception.Message);
        }
    public async Task HandleError_ApiRequestException_Should_LogWarning(string exceptionMessage)
    {
        // Arrange
        var telegramBotMock   = new Mock <ITelegramBotClient>();
        var loggerMock        = new Mock <ILogger <TelegramUpdateHandler> >();
        var githubServiceMock = new Mock <IGithubService>();

        var handler = new TelegramUpdateHandler(null, githubServiceMock.Object, loggerMock.Object);

        var exception = new ApiRequestException(exceptionMessage);

        // Act
        await handler.HandleErrorAsync(telegramBotMock.Object, exception, default);

        // Assert

        // Verify LogWarning was called
        loggerMock.Verify(x => x.Log(
                              LogLevel.Warning,
                              It.IsAny <EventId>(),
                              It.IsAny <It.IsAnyType>(),
                              It.IsAny <Exception>(),
                              (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()));

        // Verify CreateBugIssue was never called
        githubServiceMock.Verify(x => x.CreateBugIssue(It.IsAny <string>(), It.IsAny <Exception>(), It.IsAny <GithubIssueLabels>()), Times.Never);
    }
        private async void BotOnOnUpdate(object sender, UpdateEventArgs e)
        {
            var update  = e.Update;
            var handler = update.Type switch
            {
                UpdateType.Message => BotOnMessageReceived(update.Message),
                UpdateType.CallbackQuery => BotOnCallbackQueryReceived(update.CallbackQuery),
                _ => null
            };

            try
            {
                if (handler == null)
                {
                    return;
                }

                await handler;
            }
            catch (Exception exception)
            {
                var errorMessage = exception switch
                {
                    ApiRequestException apiRequestException =>
                    $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                    _ => exception.ToString()
                };

                Log.Error(exception, errorMessage);
            }
        }
        protected override async Task HandleAsync(Update update, RequestDelegate nextHandler)
        {
            try
            {
                await nextHandler(update);
            }

            catch (Exception exception)
            {
                var errorMessage = exception switch
                {
                    ApiRequestException apiRequestException => $"Telegram API Error ({apiRequestException.ErrorCode}):\n{apiRequestException.Message}",
                    _ => exception.ToString()
                };

                if (update.GetChatId() is long chatId)
                {
                    await _client.SendTextMessageAsync
                    (
                        chatId,
                        text : "Произошла непредвиденная ошибка. Невозможно обработать Ваш запрос"
                    );
                }

                _logger?.LogError(errorMessage);
            }
        }
    }
Пример #5
0
        public static string ToCustomString(this ApiRequestException e)
        {
            return($@"ErrorCode: {e.ErrorCode}
MigrateToChatId: {e.Parameters?.MigrateToChatId}
RetryAfter: {e.Parameters?.RetryAfter} 
Exception: {e}");
        }
Пример #6
0
        public async Task Should_Throw_When_Send_Invoice_Invalid_Provider_Data()
        {
            const string payload = "my-payload";

            LabeledPrice[] prices =
            {
                new LabeledPrice("PART_OF_PRODUCT_PRICE_1",  150),
                new LabeledPrice("PART_OF_PRODUCT_PRICE_2", 2029),
            };
            Invoice invoice = new Invoice
            {
                Title          = "PRODUCT_TITLE",
                Currency       = "CAD",
                StartParameter = "start_param",
                TotalAmount    = prices.Sum(p => p.Amount),
                Description    = "PRODUCT_DESCRIPTION",
            };

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              BotClient.SendInvoiceAsync(
                                                                                                  chatId: (int)_classFixture.PrivateChat.Id,
                                                                                                  title: invoice.Title,
                                                                                                  description: invoice.Description,
                                                                                                  payload: payload,
                                                                                                  providerToken: _classFixture.PaymentProviderToken,
                                                                                                  startParameter: invoice.StartParameter,
                                                                                                  currency: invoice.Currency,
                                                                                                  prices: prices,
                                                                                                  providerData: "INVALID-JSON"
                                                                                                  ));

            // ToDo: Add exception
            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: DATA_JSON_INVALID", exception.Message);
        }
Пример #7
0
        public async Task Should_Throw_Exception_When_Answering_Late()
        {
            await _fixture.SendTestInstructionsAsync(
                "Write an inline query that I'll never answer!",
                startInlineQuery : true
                );

            Update queryUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync();

            InlineQueryResultBase[] results =
            {
                new InlineQueryResultArticle(
                    id: "article:bot-api",
                    title: "Telegram Bot API",
                    inputMessageContent: new InputTextMessageContent("https://core.telegram.org/bots/api"))
                {
                    Description = "The Bot API is an HTTP-based interface created for developers",
                },
            };

            await Task.Delay(10_000);

            ApiRequestException e = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                      BotClient.AnswerInlineQueryAsync(
                                                                                          inlineQueryId: queryUpdate.InlineQuery.Id,
                                                                                          results: results,
                                                                                          cacheTime: 0
                                                                                          )
                                                                                      );

            Assert.Equal("query is too old and response timeout expired or query ID is invalid", e.Message);
            Assert.Equal(400, e.ErrorCode);
        }
Пример #8
0
    private static void Test_Get_Retry_Wait_Time(int seconds)
    {
        var ex = new ApiRequestException($"Too Many Requests: retry after {seconds}", 429);

        var waitTimeSec = ChatHelper.GetRetryWaitTimeMs(ex) / 1000;

        Assert.InRange(waitTimeSec, seconds + 1, seconds + 5);
    }
Пример #9
0
    public void Get_Retry_Wait_Time_Bad_Message(string message)
    {
        var ex = new ApiRequestException(message, 429);

        var waitTimeMs = ChatHelper.GetRetryWaitTimeMs(ex);

        Assert.Equal(15 * 1000, waitTimeMs);
    }
Пример #10
0
        public static async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var ErrorMessage = exception
                               switch {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            Console.WriteLine(ErrorMessage);
        }
        private void BotOnReceiveError(object sender, ReceiveErrorEventArgs e)
        {
            Debugger.Break();
            ApiRequestException ex = e.ApiRequestException;

            Console.WriteLine(ex.Message);
            ServiceTools.logToTextFile(errorFilename,
                                       "got API exception: " + ex.Message + Environment.NewLine + "Error code: " + ex.ErrorCode +
                                       Environment.NewLine + ex.StackTrace, true, true);
        }
Пример #12
0
        private async Task HandleErrorAsync(Exception exception, CancellationToken cancellationToken)
        {
            var ErrorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            _logger.LogError(ErrorMessage);
        }
Пример #13
0
        private void HandleError(Exception exception)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            _logger.LogDebug(errorMessage);
        }
    }
Пример #14
0
        private Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            _logger.LogError(errorMessage);
            return(Task.CompletedTask);
        }
Пример #15
0
        private void HandleError(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var ErrorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            _logger.LogDebug(ErrorMessage);
        }
    }
Пример #16
0
    static Task HandleErrorAsync(ITelegramBotClient arg1, Exception exception, CancellationToken cancellationToken)
    {
        string ErrorMessage = exception switch
        {
            ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}", _ => exception.ToString()
        };

        Console.WriteLine(ErrorMessage);
        return(Task.CompletedTask);
    }
}
Пример #17
0
        public async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            Log.Logger.Error("An error has occured while receiving updates. Error message: {0}", errorMessage);
            ErrorCount++;
        }
Пример #18
0
        public async Task Should_Throw_On_Setting_Chat_Sticker_Set()
        {
            const string setName = "EvilMinds";

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(async() =>
                                                                                              await _fixture.BotClient.SetChatStickerSetAsync(_classFixture.Chat.Id, setName)
                                                                                              );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: method is available only for supergroups", exception.Message);
        }
Пример #19
0
        public async Task Should_Throw_On_Setting_Chat_Sticker_Set()
        {
            const string setName = "EvilMinds";

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              BotClient.SetChatStickerSetAsync(_classFixture.Chat.Id, setName)
                                                                                              );

            // ToDo: Create exception type
            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: can't set supergroup sticker set", exception.Message);
        }
Пример #20
0
        private async Task HandleErrorAsync(Exception exception, CancellationToken cancellationToken)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.Message
            };

            _logger.LogError(errorMessage);
            await Task.CompletedTask;
        }
    }
Пример #21
0
        public async Task HandleError(Exception exception, CancellationToken cancellationToken)
        {
            string errorMessage = exception switch
            {
                ApiRequestException apiRequestException => "Telegram API Error:\n" +
                $"[{apiRequestException.ErrorCode}]\n" +
                $"{apiRequestException.Message}",

                   _ => exception.ToString()
            };

            await Console.Error.WriteLineAsync(errorMessage);
        }
Пример #22
0
        public async Task Should_Throw_On_Setting_Chat_Sticker_Set()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowOnSettingChatStickerSet);

            const string setName = "EvilMinds";

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              _fixture.BotClient.SetChatStickerSetAsync(_classFixture.ChatId, setName)
                                                                                              );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: can't set channel sticker set", exception.Message);
        }
Пример #23
0
 static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
 {
     if (exception is ApiRequestException)
     {
         ApiRequestException apiRequestException = exception as ApiRequestException;
         Console.WriteLine("Telegram API Error:\n[{0}]\n{1}", apiRequestException.ErrorCode, apiRequestException.Message);
     }
     else
     {
         Console.WriteLine(exception.ToString());
     }
     return(Task.CompletedTask);
 }
Пример #24
0
        public async Task Should_Throw_Exception_Not_Enough_Options()
        {
            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              BotClient.SendPollAsync(
                                                                                                  chatId: _fixture.SupergroupChat,
                                                                                                  question: "You should never see this poll",
                                                                                                  options: new[] { "The only poll option" }
                                                                                                  )
                                                                                              );

            Assert.IsType <ApiRequestException>(exception);
            Assert.Equal("Bad Request: poll must have at least 2 option", exception.Message);
        }
Пример #25
0
        public async Task Should_Throw_On_Setting_Chat_Sticker_Set()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldThrowOnSetChannelStickerSet);

            const string setName = "EvilMinds";

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              _fixture.BotClient.SetChatStickerSetAsync(_classFixture.ChatId, setName)
                                                                                              );

            // ToDo: Create exception type
            Assert.Equal(400, exception.ErrorCode);
            Assert.Equal("Bad Request: method is available only for supergroups", exception.Message);
        }
Пример #26
0
        private async Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            await Task.Run(() =>
            {
                var errorMessage = exception switch
                {
                    ApiRequestException apiRequestException =>
                    $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                    _ => exception.ToString()
                };

                _logger.Error(() => errorMessage);
            }, cancellationToken);
        }
Пример #27
0
        private static Task HandlePollingErrorAsync(ITelegramBotClient client, Exception exception, CancellationToken cancellationToken)
        {
            var errorMessage = exception switch
            {
                ApiRequestException apiRequestException =>
                $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(errorMessage);
            Console.ResetColor();

            return(Task.CompletedTask);
        }
        public async Task Should_Throw_Exception_ApiRequestException()
        {
            ReplyKeyboardMarkup replyMarkup = new ReplyKeyboardMarkup(new[]
            {
                KeyboardButton.WithRequestContact("Share Contact"),
            });

            ApiRequestException exception = await Assert.ThrowsAnyAsync <ApiRequestException>(() =>
                                                                                              BotClient.SendTextMessageAsync(
                                                                                                  chatId: _fixture.SupergroupChat.Id,
                                                                                                  text: "You should never see this message",
                                                                                                  replyMarkup: replyMarkup
                                                                                                  )
                                                                                              );

            Assert.Equal(400, exception.ErrorCode);
        }
Пример #29
0
        public static ObjectResult GenerateErrorResponse(this ApiRequestException src)
        {
            string appStatusCode = string.Empty;

            if (!string.IsNullOrEmpty(src.AppStatusCode))
            {
                appStatusCode = $"App status code: {src.AppStatusCode}";
            }

            var message = $"{src.Message} {appStatusCode}";

            return(src.HttpStatusCode == null || src.HttpStatusCode == HttpStatusCode.BadRequest
                ? new BadRequestObjectResult(ErrorResponse.Create(message))
                : new ObjectResult(ErrorResponse.Create(message))
            {
                StatusCode = (int)src.HttpStatusCode
            });
        }
Пример #30
0
        public static Task HandleErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken)
        {
            var ErrorMessage = exception switch
            {
                ApiRequestException apiRequestException => $"Telegram API Error:\n[{apiRequestException.ErrorCode}]\n{apiRequestException.Message}",
                _ => exception.ToString()
            };

            Log(true, ErrorMessage);

            if (Debugger.IsAttached)
            {
                Debugger.Break();
            }

            return(Task.CompletedTask);
        }
    }