コード例 #1
0
        public async Task Should_Answer_InlineQuery_With_Game()
        {
            await _fixture.SendTestInstructionsAsync(
                "Staring the inline query with this message...",
                startInlineQuery : true
                );

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

            const string resultId = "game";
            await BotClient.AnswerInlineQueryAsync(
                inlineQueryId : queryUpdate.InlineQuery.Id,
                results : new InlineQueryResultBase[]
            {
                new InlineQueryResultGame(
                    id: resultId,
                    gameShortName: _classFixture.GameShortName
                    )
            },
                cacheTime : 0
                );

            (Update messageUpdate, Update chosenResultUpdate) =
                await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Game);

            Assert.Equal(MessageType.Game, messageUpdate.Message.Type);
            Assert.Equal(resultId, chosenResultUpdate.ChosenInlineResult.ResultId);
            Assert.Empty(chosenResultUpdate.ChosenInlineResult.Query);

            _classFixture.InlineGameMessageId = chosenResultUpdate.ChosenInlineResult.InlineMessageId;
        }
        public async Task Should_Receive_New_Chat_Member_Notification()
        {
            await _fixture.SendTestInstructionsAsync(
                $"@{_classFixture.RegularMemberUserName.Replace("_", @"\_")} should join the group using invite link sent to " +
                "him/her in private chat"
                );

            await _fixture.UpdateReceiver.DiscardNewUpdatesAsync();

            await BotClient.SendTextMessageAsync(
                chatId : _classFixture.RegularMemberChat,
                text : _classFixture.GroupInviteLink
                );

            Update update = (await _fixture.UpdateReceiver
                             .GetUpdatesAsync(u =>
                                              u.Message.Chat.Type == ChatType.Supergroup &&
                                              u.Message.Chat.Id.ToString() == _fixture.SupergroupChat.Id.ToString() &&
                                              u.Message.Type == MessageType.ChatMembersAdded,
                                              updateTypes: UpdateType.Message)
                             ).Single();

            await _fixture.UpdateReceiver.DiscardNewUpdatesAsync();

            Message serviceMsg = update.Message;

            Assert.Equal(_classFixture.RegularMemberUserId.ToString(),
                         serviceMsg.NewChatMembers.Single().Id.ToString());
        }
コード例 #3
0
        public async Task Should_Set_Game_Score()
        {
            int playerId = _classFixture.Player.Id;

            bool playerAlreadyHasScore = _classFixture.HighScores
                                         .Any(highScore => highScore.User.Id == playerId);

            int oldScore = playerAlreadyHasScore
                ? _classFixture.HighScores.Single(highScore => highScore.User.Id == playerId).Score
                : 0;

            int newScore = oldScore + 1 + new Random().Next(3);

            await _fixture.SendTestInstructionsAsync(
                $"Changing score from {oldScore} to {newScore} for {_classFixture.Player.Username.Replace("_", @"\_")}."
                );

            Message gameMessage = await BotClient.SetGameScoreAsync(
                /* userId: */ playerId,
                /* score: */ newScore,
                /* chatId: */ _fixture.SupergroupChat.Id,
                /* messageId: */ _classFixture.GameMessage.MessageId
                );

            Assert.Equal(_classFixture.GameMessage.MessageId, gameMessage.MessageId);

            // update the high scores cache
            await Task.Delay(1_000);

            _classFixture.HighScores = await BotClient.GetGameHighScoresAsync(
                playerId, _fixture.SupergroupChat.Id, gameMessage.MessageId
                );
        }
コード例 #4
0
        public async Task Should_Send_Invoice()
        {
            await _fixture.SendTestInstructionsAsync(
                "Click on *Pay <amount>* and send your shipping address. " +
                "You should see shipment options afterwards. " +
                "Transaction should be completed.",
                chatid : _classFixture.PrivateChat.Id
                );

            _classFixture.Payload = "my-payload";
            const string url = "https://cdn.pixabay.com/photo/2017/09/07/08/54/money-2724241_640.jpg";

            LabeledPrice[] productPrices =
            {
                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    = productPrices.Sum(p => p.Amount),
                Description    = "PRODUCT_DESCRIPTION",
            };

            Message message = await BotClient.SendInvoiceAsync(
                chatId : (int)_classFixture.PrivateChat.Id,
                title : invoice.Title,
                description : invoice.Description,
                payload : _classFixture.Payload,
                providerToken : _classFixture.PaymentProviderToken,
                startParameter : invoice.StartParameter,
                currency : invoice.Currency,
                prices : productPrices,
                photoUrl : url,
                photoWidth : 600,
                photoHeight : 400,
                needShippingAddress : true,
                isFlexible : true,
                needName : true,
                needEmail : true,
                needPhoneNumber : true,
                sendEmailToProvider : true,
                sendPhoneNumberToProvider : true
                );

            Assert.Equal(MessageType.Invoice, message.Type);
            Assert.Equal(invoice.Title, message.Invoice.Title);
            Assert.Equal(invoice.Currency, message.Invoice.Currency);
            Assert.Equal(invoice.TotalAmount, message.Invoice.TotalAmount);
            Assert.Equal(invoice.Description, message.Invoice.Description);

            _classFixture.Invoice = message.Invoice;
        }
コード例 #5
0
        public async Task Should_Throw_Exception_When_Answering_Late()
        {
            await TestsFixture.SendTestInstructionsAsync(
                "Write an inline query that I'll never answer!",
                startInlineQuery : true
                );

            Update queryUpdate = await TestsFixture.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);

            InvalidQueryIdException exception = await Assert.ThrowsAsync <InvalidQueryIdException>(
                async() => await BotClient.AnswerInlineQueryAsync(
                    inlineQueryId: queryUpdate.InlineQuery !.Id,
                    results: results,
                    cacheTime: 0
                    )
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("query is too old and response timeout expired or query ID is invalid", exception.Message);
        }
コード例 #6
0
        public async Task Should_Receive_Poll_Answer_Update()
        {
            await _fixture.SendTestInstructionsAsync(
                "🗳 Choose any answer in the quiz above 👆"
                );

            Poll poll = _classFixture.OriginalPollMessage.Poll;

            Update pollAnswerUpdates = (await _fixture.UpdateReceiver.GetUpdatesAsync(
                                            update => update.PollAnswer.OptionIds.Length == 1 &&
                                            update.PollAnswer.PollId == poll.Id,
                                            updateTypes: UpdateType.PollAnswer
                                            )).Last();

            PollAnswer pollAnswer = pollAnswerUpdates.PollAnswer;

            Assert.Equal(poll.Id, pollAnswer.PollId);
            Assert.NotNull(pollAnswer.User);
            Assert.All(
                pollAnswer.OptionIds,
                optionId => Assert.True(optionId < poll.Options.Length)
                );

            _classFixture.PollAnswer = pollAnswer;
        }
コード例 #7
0
        public async Task Should_Delete_Message_From_InlineQuery()
        {
            await _fixture.SendTestInstructionsAsync(
                "Starting the inline query with this message...",
                startInlineQuery : true
                );

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

            await BotClient.AnswerInlineQueryAsync(
                inlineQueryId : queryUpdate.InlineQuery.Id,
                results : new[]
            {
                new InlineQueryResultArticle(
                    id: "article-to-delete",
                    title: "Telegram Bot API",
                    inputMessageContent: new InputTextMessageContent("https://www.telegram.org/")
                    )
            },
                cacheTime : 0
                );

            (Update messageUpdate, Update chosenResultUpdate) = await _fixture.UpdateReceiver
                                                                .GetInlineQueryResultUpdates(MessageType.Text);

            await Task.Delay(1_000);

            await BotClient.DeleteMessageAsync(
                chatId : messageUpdate.Message.Chat.Id,
                messageId : messageUpdate.Message.MessageId
                );
        }
コード例 #8
0
        public async Task Should_Receive_Poll_State_Update()
        {
            string pollId = _classFixture.PollMessage.Poll.Id;

            await _fixture.SendTestInstructionsAsync("🗳 Vote for any of the options on the poll above 👆");

            Update update = (await _fixture.UpdateReceiver.GetUpdatesAsync(updateTypes: UpdateType.Poll))
                            .Last();

            Assert.Equal(UpdateType.Poll, update.Type);
            Assert.Equal(pollId, update.Poll.Id);
        }
コード例 #9
0
        public async Task Should_Answer_Shipping_Query_With_Ok()
        {
            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
                                                               ))
                                              .WithShipping(_ => _
                                                            .WithTitle(title: "DHL Express")
                                                            .WithId(id: "dhl-express")
                                                            .WithPrice(label: "Packaging", amount: 400_000)
                                                            .WithPrice(label: "Shipping price", amount: 337_600))
                                              .WithCurrency(currency: "USD")
                                              .WithPayload("<my-payload>")
                                              .WithFlexible()
                                              .RequireShippingAddress()
                                              .WithPaymentProviderToken(_classFixture.PaymentProviderToken)
                                              .ToChat(_classFixture.PrivateChat.Id);

            double totalCostWithoutShippingCost = paymentsBuilder
                                                  .GetTotalAmountWithoutShippingCost()
                                                  .CurrencyFormat();

            string instruction = FormatInstructionWithCurrency($"Click on *Pay {totalCostWithoutShippingCost:C}* and send your shipping address.");
            await _fixture.SendTestInstructionsAsync(instruction, chatId : _classFixture.PrivateChat.Id);

            SendInvoiceRequest requestRequest = paymentsBuilder.BuildInvoiceRequest();

            await BotClient.MakeRequestAsync(requestRequest);

            Update shippingUpdate = await GetShippingQueryUpdate();

            AnswerShippingQueryRequest shippingQueryRequest = paymentsBuilder.BuildShippingQueryRequest(
                shippingQueryId: shippingUpdate.ShippingQuery.Id
                );

            await BotClient.MakeRequestAsync(shippingQueryRequest);

            Assert.Equal(UpdateType.ShippingQuery, shippingUpdate.Type);
            Assert.Equal("<my-payload>", shippingUpdate.ShippingQuery.InvoicePayload);
            Assert.NotNull(shippingUpdate.ShippingQuery.ShippingAddress.CountryCode);
            Assert.NotNull(shippingUpdate.ShippingQuery.ShippingAddress.City);
            Assert.NotNull(shippingUpdate.ShippingQuery.ShippingAddress.State);
            Assert.NotNull(shippingUpdate.ShippingQuery.ShippingAddress.StreetLine1);
            Assert.NotNull(shippingUpdate.ShippingQuery.ShippingAddress.PostCode);
        }
コード例 #10
0
        public async Task Should_Edit_Inline_Message_Text()
        {
            await _fixture.SendTestInstructionsAsync(
                "Starting the inline query with this message...",
                startInlineQuery : true
                );

            #region Answer Inline Query with an Article

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

            const string originalMessagePrefix = "original\n";
            (MessageEntityType Type, string Value)[] entityValueMappings =
コード例 #11
0
        public async Task Should_Edit_Inline_Message_Photo()
        {
            await _fixture.SendTestInstructionsAsync(
                "Starting the inline query with this message...",
                startInlineQuery : true
                );

            #region Answer Inline Query with a media message

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

            InlineQueryResultBase[] inlineQueryResults =
            {
                new InlineQueryResultPhoto(
                    id: "photo:rainbow-girl",
                    photoUrl: "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg",
                    thumbUrl: "https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_640.jpg")
                {
                    Caption     = "Rainbow Girl",
                    ReplyMarkup = InlineKeyboardButton.WithCallbackData("Click here to edit"),
                }
            };

            await BotClient.AnswerInlineQueryAsync(iqUpdate.InlineQuery.Id, inlineQueryResults, 0);

            #endregion

            // Bot waits for user to click on inline button under the media
            Update cqUpdate = await _fixture.UpdateReceiver.GetCallbackQueryUpdateAsync(data : "Click here to edit");

            // Change the photo for an audio. Note that, in the case of an inline message, the new media should be
            // either an URL or the file_id of a previously uploaded media.
            await BotClient.EditMessageMediaAsync(
                inlineMessageId : cqUpdate.CallbackQuery.InlineMessageId,
                media : new InputMediaAudio(
                    "https://upload.wikimedia.org/wikipedia/commons/transcoded/b/bb/" +
                    "Test_ogg_mp3_48kbps.wav/Test_ogg_mp3_48kbps.wav.mp3")
            {
                Caption   = "**Audio** in `.mp3` format",
                ParseMode = ParseMode.Markdown,
            }
                );
        }
コード例 #12
0
        public async Task Should_Throw_Exception_ChatNotInitiatedException()
        {
            //ToDo add exception. forward message from another bot. Forbidden: bot can't send messages to bots
            await _fixture.SendTestInstructionsAsync(
                "Forward a message to this chat from a user that never started a chat with this bot"
                );

            Update forwardedMessageUpdate = (await _fixture.UpdateReceiver.GetUpdatesAsync(u =>
                                                                                           u.Message.ForwardFrom != null, updateTypes: UpdateType.Message
                                                                                           )).Single();
            await _fixture.UpdateReceiver.DiscardNewUpdatesAsync();

            ForbiddenException e = await Assert.ThrowsAnyAsync <ForbiddenException>(() =>
                                                                                    BotClient.SendTextMessageAsync(
                                                                                        forwardedMessageUpdate.Message.ForwardFrom.Id,
                                                                                        $"Error! If you see this message, talk to @{forwardedMessageUpdate.Message.From.Username}"
                                                                                        )
                                                                                    );

            Assert.IsType <ChatNotInitiatedException>(e);
        }
コード例 #13
0
        public async Task Should_Receive_Poll_Answer_Update()
        {
            await _fixture.SendTestInstructionsAsync(
                "🗳 Vote for more than one option on the poll above 👆"
                );

            Update pollAnswerUpdate = (await _fixture.UpdateReceiver.GetUpdatesAsync(
                                           update => update.PollAnswer.OptionIds.Length > 1,
                                           updateTypes: UpdateType.PollAnswer
                                           )).First();

            Poll       poll       = _classFixture.OriginalPollMessage.Poll;
            PollAnswer pollAnswer = pollAnswerUpdate.PollAnswer;

            Assert.Equal(poll.Id, pollAnswer.PollId);
            Assert.NotNull(pollAnswer.User);
            Assert.All(
                pollAnswer.OptionIds,
                optionId => Assert.True(optionId < poll.Options.Length)
                );

            _classFixture.PollAnswer = pollAnswer;
        }
コード例 #14
0
        public async Task Should_Answer_Inline_Query_With_Article()
        {
            await _fixture.SendTestInstructionsAsync(
                "1. Start an inline query\n" +
                "2. Wait for bot to answer it\n" +
                "3. Choose the answer",
                startInlineQuery : true
                );

            // Wait for tester to start an inline query
            // This looks for an Update having a value on "inline_query" field
            Update iqUpdate = await _fixture.UpdateReceiver.GetInlineQueryUpdateAsync();

            // Prepare results of the query
            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",
                },
            };

            // Answer the query
            await BotClient.AnswerInlineQueryAsync(
                inlineQueryId : iqUpdate.InlineQuery.Id,
                results : results,
                cacheTime : 0
                );

            // Wait for tester to choose a result and send it(as a message) to the chat
            (
                Update messageUpdate,
                Update chosenResultUpdate
            ) = await _fixture.UpdateReceiver.GetInlineQueryResultUpdates(MessageType.Text);

            Assert.Equal(MessageType.Text, messageUpdate.Message.Type);
            Assert.Equal("article:bot-api", chosenResultUpdate.ChosenInlineResult.ResultId);
            Assert.Equal(iqUpdate.InlineQuery.Query, chosenResultUpdate.ChosenInlineResult.Query);
        }