From d47ee877be5d1175bdc36f2d87881ddaf875a8e9 Mon Sep 17 00:00:00 2001 From: Oleg Morozenkov Date: Mon, 23 Jul 2018 01:56:42 +0300 Subject: Refactor http clients, fix webhook server, add more samples, change tabs to 4 spaces --- .dockerignore | 7 +- .editorconfig | 3 +- .gitignore | 9 +- .travis.yml | 4 +- CMakeLists.txt | 65 +- Dockerfile | 10 +- Dockerfile_test | 27 +- include/tgbot/Api.h | 1610 +++++----- include/tgbot/Bot.h | 71 +- include/tgbot/EventBroadcaster.h | 238 +- include/tgbot/EventHandler.h | 10 +- include/tgbot/TgException.h | 2 +- include/tgbot/TgTypeParser.h | 703 ++--- include/tgbot/net/BoostHttpOnlySslClient.h | 64 + include/tgbot/net/CurlHttpClient.h | 71 + include/tgbot/net/HttpClient.h | 69 +- include/tgbot/net/HttpParser.h | 34 +- include/tgbot/net/HttpReqArg.h | 51 +- include/tgbot/net/HttpServer.h | 190 +- include/tgbot/net/TgLongPoll.h | 24 +- include/tgbot/net/TgWebhookLocalServer.h | 26 +- include/tgbot/net/TgWebhookServer.h | 43 +- include/tgbot/net/TgWebhookTcpServer.h | 20 +- include/tgbot/net/Url.h | 42 +- include/tgbot/tgbot.h | 99 +- include/tgbot/tools/StringTools.h | 6 +- include/tgbot/types/Animation.h | 42 +- include/tgbot/types/Audio.h | 54 +- include/tgbot/types/CallbackGame.h | 2 +- include/tgbot/types/CallbackQuery.h | 72 +- include/tgbot/types/Chat.h | 166 +- include/tgbot/types/ChatMember.h | 162 +- include/tgbot/types/ChatPhoto.h | 18 +- include/tgbot/types/ChosenInlineResult.h | 58 +- include/tgbot/types/Contact.h | 34 +- include/tgbot/types/Document.h | 42 +- include/tgbot/types/File.h | 36 +- include/tgbot/types/ForceReply.h | 18 +- include/tgbot/types/Game.h | 54 +- include/tgbot/types/GameHighScore.h | 32 +- include/tgbot/types/GenericReply.h | 4 +- include/tgbot/types/InlineKeyboardButton.h | 70 +- include/tgbot/types/InlineKeyboardMarkup.h | 10 +- include/tgbot/types/InlineQuery.h | 52 +- include/tgbot/types/InlineQueryResult.h | 56 +- include/tgbot/types/InlineQueryResultArticle.h | 64 +- include/tgbot/types/InlineQueryResultAudio.h | 36 +- include/tgbot/types/InlineQueryResultCachedAudio.h | 18 +- .../tgbot/types/InlineQueryResultCachedDocument.h | 26 +- include/tgbot/types/InlineQueryResultCachedGif.h | 18 +- .../tgbot/types/InlineQueryResultCachedMpeg4Gif.h | 18 +- include/tgbot/types/InlineQueryResultCachedPhoto.h | 26 +- .../tgbot/types/InlineQueryResultCachedSticker.h | 18 +- include/tgbot/types/InlineQueryResultCachedVideo.h | 26 +- include/tgbot/types/InlineQueryResultCachedVoice.h | 18 +- include/tgbot/types/InlineQueryResultContact.h | 62 +- include/tgbot/types/InlineQueryResultDocument.h | 62 +- include/tgbot/types/InlineQueryResultGame.h | 18 +- include/tgbot/types/InlineQueryResultGif.h | 68 +- include/tgbot/types/InlineQueryResultLocation.h | 68 +- include/tgbot/types/InlineQueryResultMpeg4Gif.h | 68 +- include/tgbot/types/InlineQueryResultPhoto.h | 68 +- include/tgbot/types/InlineQueryResultVenue.h | 70 +- include/tgbot/types/InlineQueryResultVideo.h | 72 +- include/tgbot/types/InlineQueryResultVoice.h | 28 +- include/tgbot/types/InputContactMessageContent.h | 34 +- include/tgbot/types/InputFile.h | 34 +- include/tgbot/types/InputLocationMessageContent.h | 26 +- include/tgbot/types/InputMedia.h | 2 +- include/tgbot/types/InputMediaPhoto.h | 8 +- include/tgbot/types/InputMediaVideo.h | 8 +- include/tgbot/types/InputMessageContent.h | 32 +- include/tgbot/types/InputTextMessageContent.h | 34 +- include/tgbot/types/InputVenueMessageContent.h | 64 +- include/tgbot/types/Invoice.h | 58 +- include/tgbot/types/KeyboardButton.h | 12 +- include/tgbot/types/LabeledPrice.h | 32 +- include/tgbot/types/Location.h | 18 +- include/tgbot/types/MaskPosition.h | 30 +- include/tgbot/types/Message.h | 412 +-- include/tgbot/types/MessageEntity.h | 52 +- include/tgbot/types/PhotoSize.h | 34 +- include/tgbot/types/ReplyKeyboardMarkup.h | 38 +- include/tgbot/types/ReplyKeyboardRemove.h | 30 +- include/tgbot/types/ResponseParameters.h | 26 +- include/tgbot/types/Sticker.h | 82 +- include/tgbot/types/StickerSet.h | 24 +- include/tgbot/types/Update.h | 110 +- include/tgbot/types/User.h | 50 +- include/tgbot/types/UserProfilePhotos.h | 18 +- include/tgbot/types/Venue.h | 42 +- include/tgbot/types/Video.h | 58 +- include/tgbot/types/VideoNote.h | 40 +- include/tgbot/types/Voice.h | 42 +- include/tgbot/types/WebhookInfo.h | 72 +- regenerate-docs | 6 - samples/echobot-curl-client/CMakeLists.txt | 16 + samples/echobot-curl-client/Dockerfile | 8 + samples/echobot-curl-client/src/main.cpp | 48 + samples/echobot-webhook-server/CMakeLists.txt | 19 + samples/echobot-webhook-server/Dockerfile | 8 + samples/echobot-webhook-server/src/main.cpp | 42 + samples/echobot/CMakeLists.txt | 4 +- samples/echobot/Dockerfile | 2 +- samples/echobot/src/main.cpp | 88 +- samples/inline-keyboard/CMakeLists.txt | 4 +- samples/inline-keyboard/Dockerfile | 2 +- samples/inline-keyboard/src/main.cpp | 92 +- samples/photo/CMakeLists.txt | 4 +- samples/photo/Dockerfile | 2 +- samples/photo/src/main.cpp | 68 +- src/Api.cpp | 1899 ++++++------ src/EventHandler.cpp | 32 +- src/TgTypeParser.cpp | 3183 ++++++++++---------- src/net/BoostHttpOnlySslClient.cpp | 92 + src/net/CurlHttpClient.cpp | 94 + src/net/HttpClient.cpp | 162 - src/net/HttpParser.cpp | 314 +- src/net/TgLongPoll.cpp | 18 +- src/net/Url.cpp | 88 +- src/tools/FileTools.cpp | 30 +- src/tools/StringTools.cpp | 139 +- src/types/InputFile.cpp | 10 +- test/CMakeLists.txt | 8 +- test/tgbot/net/HttpParser.cpp | 167 +- test/tgbot/net/Url.cpp | 36 +- test/tgbot/tools/StringTools.cpp | 36 +- test/utils.h | 136 +- tools/docker-run-sample | 6 + tools/docker-run-sample-webhook | 6 + tools/docker-test | 6 + tools/generate-docs | 7 + tools/list-includes | 19 + tools/list-srcs | 4 + 134 files changed, 7095 insertions(+), 6664 deletions(-) mode change 120000 => 100644 .dockerignore create mode 100644 include/tgbot/net/BoostHttpOnlySslClient.h create mode 100644 include/tgbot/net/CurlHttpClient.h delete mode 100755 regenerate-docs create mode 100644 samples/echobot-curl-client/CMakeLists.txt create mode 100644 samples/echobot-curl-client/Dockerfile create mode 100644 samples/echobot-curl-client/src/main.cpp create mode 100644 samples/echobot-webhook-server/CMakeLists.txt create mode 100644 samples/echobot-webhook-server/Dockerfile create mode 100644 samples/echobot-webhook-server/src/main.cpp create mode 100644 src/net/BoostHttpOnlySslClient.cpp create mode 100644 src/net/CurlHttpClient.cpp delete mode 100644 src/net/HttpClient.cpp create mode 100755 tools/docker-run-sample create mode 100755 tools/docker-run-sample-webhook create mode 100755 tools/docker-test create mode 100755 tools/generate-docs create mode 100755 tools/list-includes create mode 100755 tools/list-srcs diff --git a/.dockerignore b/.dockerignore deleted file mode 120000 index 3e4e48b..0000000 --- a/.dockerignore +++ /dev/null @@ -1 +0,0 @@ -.gitignore \ No newline at end of file diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..e137e92 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +* +!include +!samples +!src +!test +!CMakeLists.txt \ No newline at end of file diff --git a/.editorconfig b/.editorconfig index 8c1f22e..291b386 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,4 +3,5 @@ root = true [*] end_of_line = lf charset = utf-8 -indent_style = tab +indent_style = space +indent_size = 4 diff --git a/.gitignore b/.gitignore index 7ba713b..15bd029 100644 --- a/.gitignore +++ b/.gitignore @@ -3,10 +3,11 @@ CMakeFiles Makefile *.cmake install_manifest.txt -.idea/ -Thumbs.db -doc/ *.cbp *.a -test/TgBot_test +*.so +doc/ +Thumbs.db +TgBot_test +.idea/ .vscode/ \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index 47656fe..e07cafa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,5 +4,5 @@ services: - docker script: - - docker build -t reo7sp/tgbot-cpp -f Dockerfile_test . - - docker run --rm reo7sp/tgbot-cpp + - + diff --git a/CMakeLists.txt b/CMakeLists.txt index 236acbb..a6d5c2e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,68 +1,69 @@ cmake_minimum_required(VERSION 2.8.4) project(TgBot) -### options +# options option(ENABLE_TESTS "Set to ON to enable building of tests" OFF) option(BUILD_SHARED_LIBS "Build tgbot-cpp shared/static library." OFF) -### sources +# sources set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -Wall") include_directories(include) set(SRC_LIST - src/Api.cpp - src/TgTypeParser.cpp - src/TgException.cpp - src/EventHandler.cpp - src/net/Url.cpp - src/net/HttpClient.cpp - src/net/HttpParser.cpp - src/net/TgLongPoll.cpp - src/tools/StringTools.cpp - src/tools/FileTools.cpp - src/types/InlineQueryResult.cpp - src/types/InputFile.cpp + src/Api.cpp + src/EventHandler.cpp + src/TgException.cpp + src/TgTypeParser.cpp + src/net/BoostHttpOnlySslClient.cpp + src/net/CurlHttpClient.cpp + src/net/HttpParser.cpp + src/net/TgLongPoll.cpp + src/net/Url.cpp + src/tools/FileTools.cpp + src/tools/StringTools.cpp + src/types/InlineQueryResult.cpp + src/types/InputFile.cpp ) -### libs -# threads +# libs +## threads find_package(Threads REQUIRED) -# openssl +## openssl find_package(OpenSSL REQUIRED) include_directories(${OPENSSL_INCLUDE_DIR}) -# curl +## curl find_package(CURL) if (CURL_FOUND) -include_directories(${CURL_INCLUDE_DIRS}) -add_definitions(-DHAVE_CURL) + include_directories(${CURL_INCLUDE_DIRS}) + add_definitions(-DHAVE_CURL) endif() -# boost +## boost set(Boost_USE_MULTITHREADED ON) if (ENABLE_TESTS) - find_package(Boost 1.59.0 COMPONENTS system unit_test_framework REQUIRED) + find_package(Boost 1.59.0 COMPONENTS system unit_test_framework REQUIRED) else() - find_package(Boost 1.59.0 COMPONENTS system REQUIRED) + find_package(Boost 1.59.0 COMPONENTS system REQUIRED) endif() include_directories(${Boost_INCLUDE_DIR}) set(LIB_LIST - ${CMAKE_THREAD_LIBS_INIT} - ${OPENSSL_LIBRARIES} - ${Boost_LIBRARIES} - ${CURL_LIBRARIES} + ${CMAKE_THREAD_LIBS_INIT} + ${OPENSSL_LIBRARIES} + ${Boost_LIBRARIES} + ${CURL_LIBRARIES} ) -### building project +# building project add_library(${PROJECT_NAME} ${SRC_LIST}) target_link_libraries(${PROJECT_NAME} ${LIB_LIST}) install(TARGETS ${PROJECT_NAME} DESTINATION lib) install(DIRECTORY include/ DESTINATION include) -### tests +# tests if (ENABLE_TESTS) - message(STATUS "Building of tests is enabled") - enable_testing() - add_subdirectory(test) + message(STATUS "Building of tests is enabled") + enable_testing() + add_subdirectory(test) endif() diff --git a/Dockerfile b/Dockerfile index 7c88fc2..500ad5b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -2,14 +2,14 @@ FROM debian:stretch MAINTAINER Oleg Morozenkov RUN apt-get -qq update && \ - apt-get -qq install -y g++ make binutils cmake libssl-dev libboost-system-dev libcurl4-openssl-dev + apt-get -qq install -y g++ make binutils cmake libssl-dev libboost-system-dev libcurl4-openssl-dev -WORKDIR /tmp/tgbot-cpp +WORKDIR /usr/src/tgbot-cpp COPY include include COPY src src COPY CMakeLists.txt ./ RUN cmake . && \ - make -j4 && \ - make install && \ - rm -rf /tmp/tgbot-cpp/* + make -j4 && \ + make install && \ + rm -rf /usr/src/tgbot-cpp/* diff --git a/Dockerfile_test b/Dockerfile_test index e1093bf..8d4bec0 100644 --- a/Dockerfile_test +++ b/Dockerfile_test @@ -2,31 +2,40 @@ FROM debian:stretch MAINTAINER Oleg Morozenkov RUN apt-get -qq update && \ - apt-get -qq install -y g++ make binutils cmake libssl-dev libboost-system-dev libboost-test-dev libcurl4-openssl-dev + apt-get -qq install -y g++ make binutils cmake libssl-dev libboost-system-dev libboost-test-dev libcurl4-openssl-dev -WORKDIR /tmp/tgbot-cpp +WORKDIR /usr/src/tgbot-cpp COPY include include COPY src src COPY test test -COPY samples samples COPY CMakeLists.txt ./ RUN cmake -DENABLE_TESTS=ON . && \ - make -j4 && \ - make install + make -j4 && \ + make install + +COPY samples samples + +WORKDIR /usr/src/tgbot-cpp/samples/echobot +RUN rm -rf CMakeCache.txt CMakeFiles/ && \ + cmake . && make -j4 + +WORKDIR /usr/src/tgbot-cpp/samples/echobot-curl-client +RUN rm -rf CMakeCache.txt CMakeFiles/ && \ + cmake . && make -j4 -WORKDIR /tmp/tgbot-cpp/samples/echobot +WORKDIR /usr/src/tgbot-cpp/samples/echobot-webhook-server RUN rm -rf CMakeCache.txt CMakeFiles/ && \ cmake . && make -j4 -WORKDIR /tmp/tgbot-cpp/samples/inline-keyboard +WORKDIR /usr/src/tgbot-cpp/samples/inline-keyboard RUN rm -rf CMakeCache.txt CMakeFiles/ && \ cmake . && make -j4 -WORKDIR /tmp/tgbot-cpp/samples/photo +WORKDIR /usr/src/tgbot-cpp/samples/photo RUN rm -rf CMakeCache.txt CMakeFiles/ && \ cmake . && make -j4 -WORKDIR /tmp/tgbot-cpp +WORKDIR /usr/src/tgbot-cpp ENV CTEST_OUTPUT_ON_FAILURE=1 CMD make test diff --git a/include/tgbot/Api.h b/include/tgbot/Api.h index 7dd5b92..0a781e6 100644 --- a/include/tgbot/Api.h +++ b/include/tgbot/Api.h @@ -28,6 +28,8 @@ #include +#include "tgbot/TgTypeParser.h" +#include "tgbot/net/HttpClient.h" #include "tgbot/net/HttpReqArg.h" #include "tgbot/types/User.h" #include "tgbot/types/Message.h" @@ -49,7 +51,6 @@ namespace TgBot { class Bot; -class HttpClient; /** * @brief This class executes telegram api methods. Telegram docs: @@ -63,336 +64,336 @@ typedef std::shared_ptr> StringArrayPtr; friend class Bot; public: - Api(const std::string& token, const HttpClient& httpClientDriver); - - /** - * @brief A simple method for testing your bot's auth token. - * @return Basic information about the bot in form of a User object. - */ - User::Ptr getMe() const; - - /** - * @brief Use this method to send text messages. - * @param chatId Unique identifier for the target chat. - * @param text Text of the message to be sent. - * @param disableWebPagePreview Optional. Disables link previews for links in this message. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendMessage(int64_t chatId, const std::string& text, bool disableWebPagePreview = false, int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to forward messages of any kind. - * @param chatId Unique identifier for the target chat. - * @param fromChatId Unique identifier for the chat where the original message was sent — User or GroupChat id. - * @param messageId Unique message identifier. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr forwardMessage(int64_t chatId, int64_t fromChatId, int32_t messageId, bool disableNotification = false) const; - - /** - * @brief Use this method to send photos. - * @param chatId Unique identifier for the target chat. - * @param photo Photo to send. - * @param caption Optional. Photo caption. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendPhoto(int64_t chatId, const InputFile::Ptr photo, const std::string& caption = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send photos. - * @param chatId Unique identifier for the target chat. - * @param photo Photo to send. Id of the photo that is already on the Telegram servers. - * @param caption Optional. Photo caption. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendPhoto(int64_t chatId, const std::string& photoId, const std::string& caption = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Document). - * @param chatId Unique identifier for the target chat. - * @param audio Audio to send. - * @param caption Audio caption, 0-200 characters - * @param duration Duration of sent audio in seconds. - * @param performer Performer - * @param title Track name - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendAudio(int64_t chatId, const InputFile::Ptr audio, const std::string &caption = "", int32_t duration = 0, - const std::string& performer = "", const std::string& title = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Document). - * @param chatId Unique identifier for the target chat. - * @param audio Id of the audio that is already on the Telegram servers. - * @param caption Audio caption, 0-200 characters - * @param duration Duration of sent audio in seconds. - * @param performer Performer - * @param title Track name - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendAudio(int64_t chatId, const std::string& audioId, const std::string &caption = "", int32_t duration = 0, - const std::string& performer = "", const std::string& title = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send general files. - * @param chatId Unique identifier for the target chat. - * @param document Document to send. - * @param caption Document caption (may also be used when resending documents by file_id), 0-200 characters - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendDocument(int64_t chatId, const InputFile::Ptr document, const std::string &caption = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send general files. - * @param chatId Unique identifier for the target chat. - * @param document Id of the document that is already on the Telegram servers. - * @param caption Document caption (may also be used when resending documents by file_id), 0-200 characters - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendDocument(int64_t chatId, const std::string& documentId, const std::string &caption = "", int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send invoices. - * @param chatId Unique identifier for the target private chat. - * @param title Product name, 1-32 characters. - * @param description Product description, 1-255 characters. - * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. - * @param providerToken Payments provider token, obtained via Botfather. - * @param startParameter Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter. - * @param currency Three-letter ISO 4217 currency code. - * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) - * @param providerData Optional. JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. - * @param photoUrl Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. - * @param photoSize Optional. Photo size - * @param photoWidth Optional. Photo width - * @param photoHeight Optional. Photo height - * @param needName Optional. Pass True, if you require the user's full name to complete the order. - * @param needPhoneNumber Optional. Pass True, if you require the user's phone number to complete the order. - * @param needEmail Optional. Pass True, if you require the user's email address to complete the order. - * @param needShippingAddress Optional. Pass True, if you require the user's shipping address to complete the order. - * @param sendPhoneNumberToProvider Optional. Pass True, if user's phone number should be sent to provider. - * @param sendEmailToProvider Optional. Pass True, if user's email address should be sent to provider - * @param isFlexible Optional. Pass True, if the final price depends on the shipping method. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. - * @param disableNotification Optional. Sends the message silently. Users will receive a notification with no sound. - * @return On success, the sent Message is returned. - */ - Message::Ptr sendInvoice(int64_t chatId, const std::string& title, const std::string& description, const std::string& payload, - const std::string& providerToken, const std::string& startParameter, const std::string& currency, const std::vector& prices, - const std::string& providerData = "", const std::string& photoUrl = "", int32_t photoSize = 0, - int32_t photoWidth = 0, int32_t photoHeight = 0, bool needName = false, - bool needPhoneNumber = false, bool needEmail = false, bool needShippingAddress = false, - bool sendPhoneNumberToProvider = false, bool sendEmailToProvider = false, bool isFlexible = false, - int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; - - /** - * @brief Use this method to reply to shipping queries. - * - * If you sent an invoice requesting a shipping address and the parameter isFlexible was specified, the Bot API will send an Update with a shipping_query field to the bot. - * - * @param shippingQueryId Unique identifier for the query to be answered. - * @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) - * @param shippingOptions Optional. Required if ok is True. A JSON-serialized array of available shipping options. - * @param errorMessage Optional. Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. - * @return On success, True is returned. - */ - bool answerShippingQuery(const std::string& shippingQueryId, bool ok, const std::vector& shippingOptions = std::vector(), const std::string& errorMessage = "") const; - - /** - * @brief Use this method to respond to such pre-checkout queries. - * - * Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field preCheckoutQuery. - * Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. - * - * @param preCheckoutQueryId Unique identifier for the query to be answered - * @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. - * @param errorMessage Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. - * @return On success, True is returned. - */ - bool answerPreCheckoutQuery(const std::string& preCheckoutQueryId, bool ok, const std::string& errorMessage = "") const; - - /** - * @brief Use this method to send .webp stickers. - * @param chatId Unique identifier for the target chat. - * @param sticker Sticker to send. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendSticker(int64_t chatId, const InputFile::Ptr sticker, int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; - - /** - * @brief Use this method to send .webp stickers. - * @param chatId Unique identifier for the target chat. - * @param stickerId Id of the sticker that is already on the Telegram servers. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendSticker(int64_t chatId, const std::string& stickerId, int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; - - /** - * @brief Use this method to get a sticker set. - * @param chatId Name of the sticker set. - * @return On success, a StickerSet object is returned. - */ - StickerSet::Ptr getStickerSet(const std::string& name) const; - - /** - * @brief Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). - * @param userId User identifier of sticker file owner. - * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. - * @return Returns the uploaded File on success. - */ - File::Ptr uploadStickerFile(int32_t userId, const InputFile::Ptr pngSticker) const; - - /** - * @brief Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. - * @param userId User identifier of created sticker set owner. - * @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_”. is case insensitive. 1-64 characters. - * @param title Sticker set title, 1-64 characters. - * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. - * @param emojis One or more emoji corresponding to the sticker. - * @param containsMasks Optional. Pass True, if a set of mask stickers should be created. - * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. - * @return Returns True on success. - */ - bool createNewStickerSet(int32_t userId, const std::string& name, const std::string& title, - InputFile::Ptr pngSticker, const std::string& emojis, bool containsMasks = false, MaskPosition::Ptr maskPosition = nullptr) const; - - /** - * @brief Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. - * @param userId User identifier of created sticker set owner. - * @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_”. is case insensitive. 1-64 characters. - * @param title Sticker set title, 1-64 characters. - * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet. - * @param emojis One or more emoji corresponding to the sticker. - * @param containsMasks Optional. Pass True, if a set of mask stickers should be created. - * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. - * @return Returns True on success. - */ - bool createNewStickerSet(int32_t userId, const std::string& name, const std::string& title, - const std::string& pngSticker, const std::string& emojis, bool containsMasks = false, MaskPosition::Ptr maskPosition = nullptr) const; - - /** - * @brief Use this method to add a new sticker to a set created by the bot. - * @param userId User identifier of created sticker set owner. - * @param name Sticker set name. - * @param title Sticker set title, 1-64 characters. - * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. - * @param emojis One or more emoji corresponding to the sticker. - * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. - * @return Returns True on success. - */ - bool addStickerToSet(int32_t userId, const std::string& name, const std::string& title, - InputFile::Ptr pngSticker, const std::string& emojis, MaskPosition::Ptr maskPosition = nullptr) const; - - /** - * @brief Use this method to add a new sticker to a set created by the bot. - * @param userId User identifier of created sticker set owner. - * @param name Sticker set name. - * @param title Sticker set title, 1-64 characters. - * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet. - * @param emojis One or more emoji corresponding to the sticker. - * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. - * @return Returns True on success. - */ - bool addStickerToSet(int32_t userId, const std::string& name, const std::string& title, - const std::string& pngSticker, const std::string& emojis, MaskPosition::Ptr maskPosition = nullptr) const; - - /** - * @brief Use this method to move a sticker in a set created by the bot to a specific position. - * @param stickers File identifier of the sticker. - * @param position New sticker position in the set, zero-based. - * @return Returns True on success. - */ - bool setStickerPositionInSet(const std::string& sticker, uint32_t position) const; - - /** - * @brief Use this method to delete a sticker from a set created by the bot. - * @param stickers File identifier of the sticker. - * @return Returns True on success. - */ - bool deleteStickerPositionInSet(const std::string& sticker) const; - - /** - * @brief Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). - * @param chatId Unique identifier for the target chat. - * @param video Video to send. - * @param supportsStreaming Optional. Pass True, if the uploaded video is suitable for streaming. - * @param duration Optional. Duration of sent video in seconds - * @param width Optional. Video width - * @param height Optional. Video height - * @param caption Optional. Video caption (may also be used when resending videos by file_id), 0-200 characters - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendVideo(int64_t chatId, const InputFile::Ptr video, bool supportsStreaming = false, int32_t duration = 0, int32_t width = 0, int32_t height = 0, const std::string& caption = "", - int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). - * @param chatId Unique identifier for the target chat. - * @param videoId Id of the video that is already on the Telegram servers. - * @param supportsStreaming Optional. Pass True, if the uploaded video is suitable for streaming. - * @param duration Optional. Duration of sent video in seconds - * @param width Optional. Video width - * @param height Optional. Video height - * @param caption Optional. Video caption (may also be used when resending videos by file_id), 0-200 characters - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendVideo(int64_t chatId, const std::string& videoId, bool supportsStreaming = false, int32_t duration = 0, int32_t width = 0, int32_t height = 0, const std::string& caption = "", - int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** + Api(std::string token, const HttpClient& httpClient); + + /** + * @brief A simple method for testing your bot's auth token. + * @return Basic information about the bot in form of a User object. + */ + User::Ptr getMe() const; + + /** + * @brief Use this method to send text messages. + * @param chatId Unique identifier for the target chat. + * @param text Text of the message to be sent. + * @param disableWebPagePreview Optional. Disables link previews for links in this message. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendMessage(int64_t chatId, const std::string& text, bool disableWebPagePreview = false, int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to forward messages of any kind. + * @param chatId Unique identifier for the target chat. + * @param fromChatId Unique identifier for the chat where the original message was sent — User or GroupChat id. + * @param messageId Unique message identifier. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr forwardMessage(int64_t chatId, int64_t fromChatId, int32_t messageId, bool disableNotification = false) const; + + /** + * @brief Use this method to send photos. + * @param chatId Unique identifier for the target chat. + * @param photo Photo to send. + * @param caption Optional. Photo caption. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendPhoto(int64_t chatId, InputFile::Ptr photo, const std::string& caption = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send photos. + * @param chatId Unique identifier for the target chat. + * @param photo Photo to send. Id of the photo that is already on the Telegram servers. + * @param caption Optional. Photo caption. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendPhoto(int64_t chatId, const std::string& photoId, const std::string& caption = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Document). + * @param chatId Unique identifier for the target chat. + * @param audio Audio to send. + * @param caption Audio caption, 0-200 characters + * @param duration Duration of sent audio in seconds. + * @param performer Performer + * @param title Track name + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendAudio(int64_t chatId, InputFile::Ptr audio, const std::string &caption = "", int32_t duration = 0, + const std::string& performer = "", const std::string& title = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Document). + * @param chatId Unique identifier for the target chat. + * @param audio Id of the audio that is already on the Telegram servers. + * @param caption Audio caption, 0-200 characters + * @param duration Duration of sent audio in seconds. + * @param performer Performer + * @param title Track name + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendAudio(int64_t chatId, const std::string& audioId, const std::string &caption = "", int32_t duration = 0, + const std::string& performer = "", const std::string& title = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send general files. + * @param chatId Unique identifier for the target chat. + * @param document Document to send. + * @param caption Document caption (may also be used when resending documents by file_id), 0-200 characters + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendDocument(int64_t chatId, InputFile::Ptr document, const std::string &caption = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send general files. + * @param chatId Unique identifier for the target chat. + * @param document Id of the document that is already on the Telegram servers. + * @param caption Document caption (may also be used when resending documents by file_id), 0-200 characters + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendDocument(int64_t chatId, const std::string& documentId, const std::string &caption = "", int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send invoices. + * @param chatId Unique identifier for the target private chat. + * @param title Product name, 1-32 characters. + * @param description Product description, 1-255 characters. + * @param payload Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + * @param providerToken Payments provider token, obtained via Botfather. + * @param startParameter Unique deep-linking parameter that can be used to generate this invoice when used as a start parameter. + * @param currency Three-letter ISO 4217 currency code. + * @param prices Price breakdown, a list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.) + * @param providerData Optional. JSON-encoded data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + * @param photoUrl Optional. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + * @param photoSize Optional. Photo size + * @param photoWidth Optional. Photo width + * @param photoHeight Optional. Photo height + * @param needName Optional. Pass True, if you require the user's full name to complete the order. + * @param needPhoneNumber Optional. Pass True, if you require the user's phone number to complete the order. + * @param needEmail Optional. Pass True, if you require the user's email address to complete the order. + * @param needShippingAddress Optional. Pass True, if you require the user's shipping address to complete the order. + * @param sendPhoneNumberToProvider Optional. Pass True, if user's phone number should be sent to provider. + * @param sendEmailToProvider Optional. Pass True, if user's email address should be sent to provider + * @param isFlexible Optional. Pass True, if the final price depends on the shipping method. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. A JSON-serialized object for an inline keyboard. If empty, one 'Pay total price' button will be shown. If not empty, the first button must be a Pay button. + * @param disableNotification Optional. Sends the message silently. Users will receive a notification with no sound. + * @return On success, the sent Message is returned. + */ + Message::Ptr sendInvoice(int64_t chatId, const std::string& title, const std::string& description, const std::string& payload, + const std::string& providerToken, const std::string& startParameter, const std::string& currency, const std::vector& prices, + const std::string& providerData = "", const std::string& photoUrl = "", int32_t photoSize = 0, + int32_t photoWidth = 0, int32_t photoHeight = 0, bool needName = false, + bool needPhoneNumber = false, bool needEmail = false, bool needShippingAddress = false, + bool sendPhoneNumberToProvider = false, bool sendEmailToProvider = false, bool isFlexible = false, + int32_t replyToMessageId = 0, GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; + + /** + * @brief Use this method to reply to shipping queries. + * + * If you sent an invoice requesting a shipping address and the parameter isFlexible was specified, the Bot API will send an Update with a shipping_query field to the bot. + * + * @param shippingQueryId Unique identifier for the query to be answered. + * @param ok Specify True if delivery to the specified address is possible and False if there are any problems (for example, if delivery to the specified address is not possible) + * @param shippingOptions Optional. Required if ok is True. A JSON-serialized array of available shipping options. + * @param errorMessage Optional. Required if ok is False. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. + * @return On success, True is returned. + */ + bool answerShippingQuery(const std::string& shippingQueryId, bool ok, const std::vector& shippingOptions = std::vector(), const std::string& errorMessage = "") const; + + /** + * @brief Use this method to respond to such pre-checkout queries. + * + * Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an Update with the field preCheckoutQuery. + * Note: The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + * + * @param preCheckoutQueryId Unique identifier for the query to be answered + * @param ok Specify True if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use False if there are any problems. + * @param errorMessage Required if ok is False. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + * @return On success, True is returned. + */ + bool answerPreCheckoutQuery(const std::string& preCheckoutQueryId, bool ok, const std::string& errorMessage = "") const; + + /** + * @brief Use this method to send .webp stickers. + * @param chatId Unique identifier for the target chat. + * @param sticker Sticker to send. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendSticker(int64_t chatId, InputFile::Ptr sticker, int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; + + /** + * @brief Use this method to send .webp stickers. + * @param chatId Unique identifier for the target chat. + * @param stickerId Id of the sticker that is already on the Telegram servers. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendSticker(int64_t chatId, const std::string& stickerId, int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; + + /** + * @brief Use this method to get a sticker set. + * @param chatId Name of the sticker set. + * @return On success, a StickerSet object is returned. + */ + StickerSet::Ptr getStickerSet(const std::string& name) const; + + /** + * @brief Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). + * @param userId User identifier of sticker file owner. + * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. + * @return Returns the uploaded File on success. + */ + File::Ptr uploadStickerFile(int32_t userId, InputFile::Ptr pngSticker) const; + + /** + * @brief Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. + * @param userId User identifier of created sticker set owner. + * @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_”. is case insensitive. 1-64 characters. + * @param title Sticker set title, 1-64 characters. + * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. + * @param emojis One or more emoji corresponding to the sticker. + * @param containsMasks Optional. Pass True, if a set of mask stickers should be created. + * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. + * @return Returns True on success. + */ + bool createNewStickerSet(int32_t userId, const std::string& name, const std::string& title, + InputFile::Ptr pngSticker, const std::string& emojis, bool containsMasks = false, MaskPosition::Ptr maskPosition = nullptr) const; + + /** + * @brief Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set. + * @param userId User identifier of created sticker set owner. + * @param name Short name of sticker set, to be used in t.me/addstickers/ URLs (e.g., animals). Can contain only english letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in “_by_”. is case insensitive. 1-64 characters. + * @param title Sticker set title, 1-64 characters. + * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet. + * @param emojis One or more emoji corresponding to the sticker. + * @param containsMasks Optional. Pass True, if a set of mask stickers should be created. + * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. + * @return Returns True on success. + */ + bool createNewStickerSet(int32_t userId, const std::string& name, const std::string& title, + const std::string& pngSticker, const std::string& emojis, bool containsMasks = false, MaskPosition::Ptr maskPosition = nullptr) const; + + /** + * @brief Use this method to add a new sticker to a set created by the bot. + * @param userId User identifier of created sticker set owner. + * @param name Sticker set name. + * @param title Sticker set title, 1-64 characters. + * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. + * @param emojis One or more emoji corresponding to the sticker. + * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. + * @return Returns True on success. + */ + bool addStickerToSet(int32_t userId, const std::string& name, const std::string& title, + InputFile::Ptr pngSticker, const std::string& emojis, MaskPosition::Ptr maskPosition = nullptr) const; + + /** + * @brief Use this method to add a new sticker to a set created by the bot. + * @param userId User identifier of created sticker set owner. + * @param name Sticker set name. + * @param title Sticker set title, 1-64 characters. + * @param pngSticker Png image with the sticker, must be up to 512 kilobytes in size, dimensions must not exceed 512px, and either width or height must be exactly 512px. Pass a file_id as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet. + * @param emojis One or more emoji corresponding to the sticker. + * @param maskPosition Optional. A JSON-serialized object for position where the mask should be placed on faces. + * @return Returns True on success. + */ + bool addStickerToSet(int32_t userId, const std::string& name, const std::string& title, + const std::string& pngSticker, const std::string& emojis, MaskPosition::Ptr maskPosition = nullptr) const; + + /** + * @brief Use this method to move a sticker in a set created by the bot to a specific position. + * @param stickers File identifier of the sticker. + * @param position New sticker position in the set, zero-based. + * @return Returns True on success. + */ + bool setStickerPositionInSet(const std::string& sticker, uint32_t position) const; + + /** + * @brief Use this method to delete a sticker from a set created by the bot. + * @param stickers File identifier of the sticker. + * @return Returns True on success. + */ + bool deleteStickerPositionInSet(const std::string& sticker) const; + + /** + * @brief Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). + * @param chatId Unique identifier for the target chat. + * @param video Video to send. + * @param supportsStreaming Optional. Pass True, if the uploaded video is suitable for streaming. + * @param duration Optional. Duration of sent video in seconds + * @param width Optional. Video width + * @param height Optional. Video height + * @param caption Optional. Video caption (may also be used when resending videos by file_id), 0-200 characters + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. An object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendVideo(int64_t chatId, InputFile::Ptr video, bool supportsStreaming = false, int32_t duration = 0, int32_t width = 0, int32_t height = 0, const std::string& caption = "", + int32_t replyToMessageId = 0, GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document). + * @param chatId Unique identifier for the target chat. + * @param videoId Id of the video that is already on the Telegram servers. + * @param supportsStreaming Optional. Pass True, if the uploaded video is suitable for streaming. + * @param duration Optional. Duration of sent video in seconds + * @param width Optional. Video width + * @param height Optional. Video height + * @param caption Optional. Video caption (may also be used when resending videos by file_id), 0-200 characters + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendVideo(int64_t chatId, const std::string& videoId, bool supportsStreaming = false, int32_t duration = 0, int32_t width = 0, int32_t height = 0, const std::string& caption = "", + int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** * @brief Use this method to send video messages. On success, the sent Message is returned. * @param chatId Unique identifier for the target chat. * @param videoNote Video note to send. @@ -403,8 +404,8 @@ public: * @param replyMarkup Additional interface options. A object for an inline keyboard, custom reply keyboard, instructions to remove reply keyboard or to force a reply from the user. * @return On success, the sent Message is returned. */ - Message::Ptr sendVideoNote(int64_t chatId, const InputFile::Ptr videoNote, int64_t replyToMessageId = 0, bool disableNotification = false, - int32_t duration = 0, int32_t length = 0, const GenericReply::Ptr replyMarkup = GenericReply::Ptr()); + Message::Ptr sendVideoNote(int64_t chatId, InputFile::Ptr videoNote, int64_t replyToMessageId = 0, bool disableNotification = false, + int32_t duration = 0, int32_t length = 0, GenericReply::Ptr replyMarkup = GenericReply::Ptr()); /** * @brief Use this method to send video messages. On success, the sent Message is returned. @@ -418,480 +419,481 @@ public: * @return On success, the sent Message is returned. */ Message::Ptr sendVideoNote(int64_t chatId, const std::string& videoNote, int64_t replyToMessageId = 0, bool disableNotification = false, - int32_t duration = 0, int32_t length = 0, const GenericReply::Ptr replyMarkup = GenericReply::Ptr()); - - /** - * @brief Use this method to send a group of photos or videos as an album. - * @param chatId Unique identifier for the target chat of the target channel. - * @param media A JSON-serialized array describing photos and videos to be sent, must include 2–10 items. - * @param disableNotification Optional. Sends the messages silently. Users will receive a notification with no sound. - * @param replyToMessageId Optional. If the messages are a reply, ID of the original message. - * @return On success, an array of the sent Messages is returned. - */ - std::vector sendMediaGroup(int64_t chatId, const std::vector& media, - bool disableNotification = false, int32_t replyToMessageId = 0) const; - - /** - * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. - * @param chatId Unique identifier for the target chat. - * @param voice Audio file to send. - * @param caption Voice message caption, 0-200 characters - * @param duration Duration of send audio in seconds. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendVoice(int64_t chatId, const InputFile::Ptr voice, const std::string& caption = "", int duration = 0, int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. - * @param chatId Unique identifier for the target chat. - * @param voiceId Id of the voice that is already on the Telegram servers. - * @param caption Voice message caption, 0-200 characters - * @param duration Duration of send audio in seconds. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendVoice(int64_t chatId, const std::string& voiceId, const std::string& caption = "", int duration = 0, int32_t replyToMessageId = 0, - const GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; - - /** - * @brief Use this method to send a game. - * @param chatId Unique identifier for the target chat. - * @param gameShortName Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendGame(int64_t chatId, const std::string& gameShortName, int32_t replyToMessageId = 0, - const InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; - - /** - * @brief Use this method to send point on the map. - * @param chatId Unique identifier for the target chat. - * @param latitude Latitude of location. - * @param longitude Longitude of location. - * @param livePeriod Optional. Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400). - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendLocation(int64_t chatId, float latitude, float longitude, uint32_t livePeriod = 0, - int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; - - /** - * @brief Use this method to edit live location messages sent by the bot or via the bot (for inline bots). - * @param latitude Latitude of new location. - * @param longitude Longitude of new location. - * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat of the target channel. - * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message. - * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message. - * @param replyMarkup Optional. A JSON-serialized object for a new inline keyboard. - * @return On success, if the edited message was sent by the bot, the edited Message is returned, otherwise nullptr is returned. - */ - Message::Ptr editMessageLiveLocation(float latitude, float longitude, int64_t chatId = 0, int32_t messageId = 0, - int32_t inlineMessageId = 0, const InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method to edit live location messages sent by the bot or via the bot (for inline bots). - * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat of the target channel. - * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message. - * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message. - * @param replyMarkup Optional. A JSON-serialized object for a new inline keyboard. - * @return On success, if the edited message was sent by the bot, the edited Message is returned, otherwise nullptr is returned. - */ - Message::Ptr stopMessageLiveLocation(int64_t chatId = 0, int32_t messageId = 0, int32_t inlineMessageId = 0, - const InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared()) const; - - - /** - * @brief Use this method to send information about a venue. On success, the sent Message is returned. - * @param chatId Unique identifier for the target chat. - * @param latitude Latitude of location. - * @param longitude Longitude of location. - * @param title Name of the venue. - * @param address Address of the venue. - * @param foursquare_id Foursquare identifier of the venue. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @param disableNotification Optional. Sends the message silenty. - * @return On success, the sent message is returned. - */ - Message::Ptr sendVenue(int64_t chatId, float latitude, float longitude, const std::string& title, const std::string& address, const std::string& foursquareId = "", - bool disableNotification = false, int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method to send phone contacts. On success, the sent Message is returned. - * @param chatId Unique identifier for the target chat. - * @param phoneNumber Contact's phone number. - * @param firstName Contact's first name. - * @param lastName Contact's last name. - * @param disableNotification Optional. Sends the message silenty. - * @param replyToMessageId Optional. If the message is a reply, ID of the original message. - * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. - * @return On success, the sent message is returned. - */ - Message::Ptr sendContact(int64_t chatId, const std::string& phoneNumber, const std::string& firstName, const std::string& lastName = "", bool disableNotification = false, - int32_t replyToMessageId = 0, const GenericReply::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). - * - * Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. - * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. - * - * @param chatId Unique identifier for the target chat. - * @param action Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_audio or upload_audio for audio files, upload_document for general files, find_location for location data. - */ - void sendChatAction(int64_t chatId, const std::string& action) const; - - /** - * @brief Use this method to get a list of profile pictures for a user. - * @param userId Unique identifier of the target user. - * @param offset Optional. Sequential number of the first photo to be returned. By default, all photos are returned. - * @param limit Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100. - * @return A UserProfilePhotos object. - */ - UserProfilePhotos::Ptr getUserProfilePhotos(int32_t userId, int32_t offset = 0, int32_t limit = 100) const; - - /** - * @brief Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. - * @param fileId File identifier to get info about - * @return A File object. - */ - File::Ptr getFile(const std::string &fileId) const; - - /** - * @brief Use this method for your bot to leave a group, supergroup or channel. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @return True on success - */ - bool leaveChat(int64_t chatId) const; - - /** - * @brief Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @return Chat object. - */ - Chat::Ptr getChat(int64_t chatId) const; - - /** - * @brief Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @return ChatMember object. - */ - std::vector getChatAdministrators(int64_t chatId) const; - - /** - * @brief Use this method to get the number of members in a chat. Returns Int on success. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @return Int. - */ - int32_t getChatMembersCount(int64_t chatId) const; - - /** - * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @param userId Unique identifier of the target user - * @return ChatMember object. - */ - ChatMember::Ptr getChatMember(int64_t chatId, int32_t userId) const; - - /** - * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @param stickerSetName Name of the sticker set to be set as the group sticker set. - * @return Returns True on success. - */ - bool setChatStickerSet(int64_t chatId, const std::string& stickerSetName) const; - - /** - * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. - * @param chatId Unique identifier for the target chat of the target supergroup or channel. - * @return Returns True on success. - */ - bool deleteChatStickerSet(int64_t chatId) const; - - - /** - * @brief Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. - * @param callbackQueryId Unique identifier for the query to be answered - * @param text Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters - * @param showAlert Optional If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. - * @param url Optional URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button - * @param cacheTime Optional The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. - * @return True on success - */ - bool answerCallbackQuery(const std::string & callbackQueryId, const std::string & text="", bool showAlert=false, const std::string &url="", int32_t cacheTime=0) const; - - /** - * @brief Use this method to edit text and game messages sent by the bot or via the bot (for inline bots) - * @param text New text of the message - * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. - * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message - * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message - * @param parseMode Optional Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. - * @param disableWebPagePreview Optional Disables link previews for links in this message - * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. - * @return Message object on success, otherwise nullptr - */ - Message::Ptr editMessageText(const std::string& text, int64_t chatId=0, int32_t messageId=0, const std::string& inlineMessageId="", - const std::string& parseMode = "", bool disableWebPagePreview = false, const GenericReply::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). - * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. - * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message - * @param caption Optional New caption of the message - * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message - * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. - * @return Message object on success, otherwise nullptr - */ - Message::Ptr editMessageCaption(int64_t chatId = 0, int32_t messageId = 0, const std::string& caption = "", - const std::string& inlineMessageId = "", const GenericReply::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). - * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. - * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message - * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message - * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. - * @return Message object on success, otherwise nullptr - */ - Message::Ptr editMessageReplyMarkup(int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "", - const GenericReply::Ptr replyMarkup = std::make_shared()) const; - - /** - * @brief Use this method to delete messages sent by bot (or by other users if bot is admin). - * @param chatId Unique identifier for the target chat. - * @param messageId Unique identifier for the target message. - */ - void deleteMessage(int64_t chatId, int32_t messageId) const; - - /** - * @brief Use this method to receive incoming updates using long polling. - * - * This method will not work if an outgoing webhook is set up. - * In order to avoid getting duplicate updates, recalculate offset after each server response. - * - * @param offset Optional. Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. - * @param limit Optional. Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. - * @param timeout Optional. Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. - * @param allowed_updates Optional. List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. - * @return An Array of Update objects - */ - std::vector getUpdates(int32_t offset = 0, int32_t limit = 100, int32_t timeout = 0, const StringArrayPtr &allowedUpdates = nullptr) const; - - /** - * @brief Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. - * - * If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. www.example.com/. Since nobody else knows your bot‘s token, you can be pretty sure it’s us. - * You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up. - * We currently do not support self-signed certificates. - * Ports currently supported for Webhooks: 443, 80, 88, 8443. - * - * @param url Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration. - */ - void setWebhook(const std::string& url = "", const InputFile::Ptr certificate = nullptr, int32_t maxConnection = 40, const StringArrayPtr &allowedUpdates = nullptr) const; - - /** - * @brief Use this method to remove webhook integration if you decide to switch back to getUpdates. - * - * Requires no parameters. - * - * @return Returns True on success. - */ - bool deleteWebhook() const; - - /** - * @brief Use this method to get current webhook status. - * - * Requires no parameters. - * If the bot is using getUpdates, will return an object with the url field empty. - * - * @return On success, returns a WebhookInfo object. - */ - WebhookInfo::Ptr getWebhookInfo() const; - - /** - * @brief Use this method to send answers to an inline query. - * No mode that 50 results per query are allowed. - * @param inlineQueryId Unique identifier for the answered query. - * @param results Array of results for the inline query. - * @param cacheTime The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. - * @param isPersonal Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. - * @param nextOffset Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. - * @param switchPmText If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter - * @param switchPmParameter Parameter for the start message sent to the bot when user presses the switch button - * @return True on success - */ - bool answerInlineQuery(const std::string& inlineQueryId, const std::vector& results, - int32_t cacheTime = 300, bool isPersonal = false, const std::string& nextOffset = "", const std::string& switchPmText = "", const std::string& switchPmParameter = "") const; - - /** - * @brief Use this method to kick a user from a group or a supergroup. - * @param chatId Unique identifier for the target group. - * @param userId Unique identifier of the target user. - * @param untilDate Optional. Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. - * @return True on success - */ - bool kickChatMember(int64_t chatId, int32_t userId, uint64_t untilDate = 0) const; - - /** - * @brief Use this method to unban a previously kicked user in a supergroup. - * @param chatId Unique identifier for the target group. - * @param userId Unique identifier of the target user. - * @return True on success - */ - bool unbanChatMember(int64_t chatId, int32_t userId) const; - - /** - * @brief Use this method to restrict a user in a supergroup. - * @param chatId Unique identifier for the target chat of the target supergroup. - * @param userId Unique identifier of the target user. - * @param untilDate Optional. Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever. - * @param canSendMessages Optional. Pass True, if the user can send text messages, contacts, locations and venues. - * @param canSendMediaMessages Optional. Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages. - * @param canSendOtherMessages Optional. Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages. - * @param canAddWebPagePreviews Optional. Pass True, if the user may add web page previews to their messages, implies can_send_media_messages. - * @return True on success - */ - bool restrictChatMember(int64_t chatId, int32_t userId, uint64_t untilDate = 0, bool canSendMessages = false, - bool canSendMediaMessages = false, bool canSendOtherMessages = false, bool canAddWebPagePreviews = false) const; - - /** - * @brief Use this method to promote or demote a user in a supergroup or a channel. - * @param chatId Unique identifier for the target chat of the target supergroup or channal. - * @param userId Unique identifier of the target user. - * @param canChangeInfo Optional. Pass True, if the administrator can change chat title, photo and other settings. - * @param canPostMessages Optional. Pass True, if the administrator can create channel posts, channels only. - * @param canEditMessages Optional. Pass True, if the administrator can edit messages of other users and can pin messages, channels only. - * @param canDeleteMessages Optional. Pass True, if the administrator can delete messages of other users. - * @param canInviteUsers Optional. Pass True, if the administrator can invite new users to the chat. - * @param canRestrictMembers Optional. Pass True, if the administrator can restrict, ban or unban chat members. - * @param canPinMessages Optional. Pass True, if the administrator can pin messages, supergroups only. - * @param canPromoteMembers Optional. Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him). - * @return True on success - */ - bool promoteChatMember(int64_t chatId, int32_t userId, bool canChangeInfo = false, bool canPostMessages = false, - bool canEditMessages = false, bool canDeleteMessages = false, bool canInviteUsers = false, bool canPinMessages = false, bool canPromoteMembers = false) const; - - /** - * @brief Use this method to generate a new invite link for a chat; any previously generated link is revoked. - * @param chatId Unique identifier for the target chat. - * @return The new invite link as String on success. - */ - std::string exportChatInviteLink(int64_t chatId) const; - - /** - * @brief Use this method to set a new profile photo for the chat. - * - * Photos can't be changed for private chats. - * - * @param chatId Unique identifier for the target chat. - * @param photo New chat photo. - * @return True on success - */ - bool setChatPhoto(int64_t chatId, const InputFile::Ptr photo) const; - - /** - * @brief Use this method to delete a chat photo. - * - * Photos can't be changed for private chats. - * - * @param chatId Unique identifier for the target chat. - * @return True on success - */ - bool deleteChatPhoto(int64_t chatId) const; - - /** - * @brief Use this method to change the title of a chat. - * - * Titles can't be changed for private chats. - * - * @param chatId Unique identifier for the target chat. - * @param title New chat title, 1-255 characters. - * @return True on success - */ - bool setChatTitle(int64_t chatId, const std::string& title) const; - - /** - * @brief Use this method to change the description of a supergroup or a channel. - * @param chatId Unique identifier for the target chat. - * @param description New chat description, 1-255 characters. - * @return True on success - */ - bool setChatDescription(int64_t chatId, const std::string& description) const; - - /** - * @brief Use this method to pin a message in a supergroup or a channel. - * @param chatId Unique identifier for the target chat. - * @param messageId Identifier of a message to pin. - * @param disableNotification Optional. Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels. - * @return True on success - */ - bool pinChatMessage(int64_t chatId, int32_t messageId, bool disableNotification = false) const; - - /** - * @brief Use this method to unpin a message in a supergroup or a channel. - * @param chatId Unique identifier for the target chat. - * @return True on success - */ - bool unpinChatMessage(int64_t chatId) const; - - /** - * @brief Use this method to set the score of the specified user in a game. - * - * Returns an error, if the new score is not greater than the user's current score in the chat and force is False. - * - * @param userId User identifier. - * @param score New score, must be non-negative. - * @param force Optional. Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters. - * @param disableEditMessage Optional. Pass True, if the game message should not be automatically edited to include the current scoreboard. - * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat - * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message - * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message - * @return On success, if the message was sent by the bot, returns the edited Message, otherwise returns nullptr. - */ - Message::Ptr setGameScore(int32_t userId, int32_t score, bool force = false, bool disableEditMessage = false, - int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "") const; - - /** - * @brief Use this method to get data for high score tables. - * - * Will return the score of the specified user and several of his neighbors in a game. - * - * @param userId User identifier. - * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat - * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message - * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message - * @return On success, returns an Array of GameHighScore objects. - */ - std::vector getGameHighScores(int32_t userId, int32_t score, bool force = false, - bool disableEditMessage = false, int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "") const; - - - /** - * @brief Downloads file from Telegram and saves it in memory. - * @param filePath Telegram file path. - * @param args Additional api parameters. - * @return File contents in a string. - */ - std::string downloadFile(const std::string& filePath, const std::vector& args = std::vector()) const; + int32_t duration = 0, int32_t length = 0, GenericReply::Ptr replyMarkup = GenericReply::Ptr()); + + /** + * @brief Use this method to send a group of photos or videos as an album. + * @param chatId Unique identifier for the target chat of the target channel. + * @param media A JSON-serialized array describing photos and videos to be sent, must include 2–10 items. + * @param disableNotification Optional. Sends the messages silently. Users will receive a notification with no sound. + * @param replyToMessageId Optional. If the messages are a reply, ID of the original message. + * @return On success, an array of the sent Messages is returned. + */ + std::vector sendMediaGroup(int64_t chatId, const std::vector& media, + bool disableNotification = false, int32_t replyToMessageId = 0) const; + + /** + * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. + * @param chatId Unique identifier for the target chat. + * @param voice Audio file to send. + * @param caption Voice message caption, 0-200 characters + * @param duration Duration of send audio in seconds. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendVoice(int64_t chatId, InputFile::Ptr voice, const std::string& caption = "", int duration = 0, int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. + * @param chatId Unique identifier for the target chat. + * @param voiceId Id of the voice that is already on the Telegram servers. + * @param caption Voice message caption, 0-200 characters + * @param duration Duration of send audio in seconds. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param parseMode Optional. Set it to "Markdown" or "HTML" if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendVoice(int64_t chatId, const std::string& voiceId, const std::string& caption = "", int duration = 0, int32_t replyToMessageId = 0, + GenericReply::Ptr replyMarkup = std::make_shared(), const std::string& parseMode = "", bool disableNotification = false) const; + + /** + * @brief Use this method to send a game. + * @param chatId Unique identifier for the target chat. + * @param gameShortName Short name of the game, serves as the unique identifier for the game. Set up your games via Botfather. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. A JSON-serialized object for an inline keyboard. If empty, one ‘Play game_title’ button will be shown. If not empty, the first button must launch the game. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendGame(int64_t chatId, const std::string& gameShortName, int32_t replyToMessageId = 0, + InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; + + /** + * @brief Use this method to send point on the map. + * @param chatId Unique identifier for the target chat. + * @param latitude Latitude of location. + * @param longitude Longitude of location. + * @param livePeriod Optional. Period in seconds for which the location will be updated (see Live Locations, should be between 60 and 86400). + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendLocation(int64_t chatId, float latitude, float longitude, uint32_t livePeriod = 0, + int32_t replyToMessageId = 0, GenericReply::Ptr replyMarkup = std::make_shared(), bool disableNotification = false) const; + + /** + * @brief Use this method to edit live location messages sent by the bot or via the bot (for inline bots). + * @param latitude Latitude of new location. + * @param longitude Longitude of new location. + * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat of the target channel. + * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message. + * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message. + * @param replyMarkup Optional. A JSON-serialized object for a new inline keyboard. + * @return On success, if the edited message was sent by the bot, the edited Message is returned, otherwise nullptr is returned. + */ + Message::Ptr editMessageLiveLocation(float latitude, float longitude, int64_t chatId = 0, int32_t messageId = 0, + int32_t inlineMessageId = 0, InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method to edit live location messages sent by the bot or via the bot (for inline bots). + * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat of the target channel. + * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message. + * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message. + * @param replyMarkup Optional. A JSON-serialized object for a new inline keyboard. + * @return On success, if the edited message was sent by the bot, the edited Message is returned, otherwise nullptr is returned. + */ + Message::Ptr stopMessageLiveLocation(int64_t chatId = 0, int32_t messageId = 0, int32_t inlineMessageId = 0, + InlineKeyboardMarkup::Ptr replyMarkup = std::make_shared()) const; + + + /** + * @brief Use this method to send information about a venue. On success, the sent Message is returned. + * @param chatId Unique identifier for the target chat. + * @param latitude Latitude of location. + * @param longitude Longitude of location. + * @param title Name of the venue. + * @param address Address of the venue. + * @param foursquare_id Foursquare identifier of the venue. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @param disableNotification Optional. Sends the message silenty. + * @return On success, the sent message is returned. + */ + Message::Ptr sendVenue(int64_t chatId, float latitude, float longitude, const std::string& title, const std::string& address, const std::string& foursquareId = "", + bool disableNotification = false, int32_t replyToMessageId = 0, GenericReply::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method to send phone contacts. On success, the sent Message is returned. + * @param chatId Unique identifier for the target chat. + * @param phoneNumber Contact's phone number. + * @param firstName Contact's first name. + * @param lastName Contact's last name. + * @param disableNotification Optional. Sends the message silenty. + * @param replyToMessageId Optional. If the message is a reply, ID of the original message. + * @param replyMarkup Optional. Additional interface options. A object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. + * @return On success, the sent message is returned. + */ + Message::Ptr sendContact(int64_t chatId, const std::string& phoneNumber, const std::string& firstName, const std::string& lastName = "", bool disableNotification = false, + int32_t replyToMessageId = 0, GenericReply::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). + * + * Example: The ImageBot needs some time to process a request and upload the image. Instead of sending a text message along the lines of “Retrieving image, please wait…”, the bot may use sendChatAction with action = upload_photo. The user will see a “sending photo” status for the bot. + * We only recommend using this method when a response from the bot will take a noticeable amount of time to arrive. + * + * @param chatId Unique identifier for the target chat. + * @param action Type of action to broadcast. Choose one, depending on what the user is about to receive: typing for text messages, upload_photo for photos, record_video or upload_video for videos, record_audio or upload_audio for audio files, upload_document for general files, find_location for location data. + */ + void sendChatAction(int64_t chatId, const std::string& action) const; + + /** + * @brief Use this method to get a list of profile pictures for a user. + * @param userId Unique identifier of the target user. + * @param offset Optional. Sequential number of the first photo to be returned. By default, all photos are returned. + * @param limit Optional. Limits the number of photos to be retrieved. Values between 1—100 are accepted. Defaults to 100. + * @return A UserProfilePhotos object. + */ + UserProfilePhotos::Ptr getUserProfilePhotos(int32_t userId, int32_t offset = 0, int32_t limit = 100) const; + + /** + * @brief Use this method to get basic info about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. + * @param fileId File identifier to get info about + * @return A File object. + */ + File::Ptr getFile(const std::string &fileId) const; + + /** + * @brief Use this method for your bot to leave a group, supergroup or channel. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @return True on success + */ + bool leaveChat(int64_t chatId) const; + + /** + * @brief Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @return Chat object. + */ + Chat::Ptr getChat(int64_t chatId) const; + + /** + * @brief Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @return ChatMember object. + */ + std::vector getChatAdministrators(int64_t chatId) const; + + /** + * @brief Use this method to get the number of members in a chat. Returns Int on success. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @return Int. + */ + int32_t getChatMembersCount(int64_t chatId) const; + + /** + * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @param userId Unique identifier of the target user + * @return ChatMember object. + */ + ChatMember::Ptr getChatMember(int64_t chatId, int32_t userId) const; + + /** + * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @param stickerSetName Name of the sticker set to be set as the group sticker set. + * @return Returns True on success. + */ + bool setChatStickerSet(int64_t chatId, const std::string& stickerSetName) const; + + /** + * @brief Use this method to get information about a member of a chat. Returns a ChatMember object on success. + * @param chatId Unique identifier for the target chat of the target supergroup or channel. + * @return Returns True on success. + */ + bool deleteChatStickerSet(int64_t chatId) const; + + + /** + * @brief Use this method to send answers to callback queries sent from inline keyboards. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. + * @param callbackQueryId Unique identifier for the query to be answered + * @param text Optional Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + * @param showAlert Optional If true, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to false. + * @param url Optional URL that will be opened by the user's client. If you have created a Game and accepted the conditions via @Botfather, specify the URL that opens your game – note that this will only work if the query comes from a callback_game button + * @param cacheTime Optional The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + * @return True on success + */ + bool answerCallbackQuery(const std::string & callbackQueryId, const std::string & text="", bool showAlert=false, const std::string &url="", int32_t cacheTime=0) const; + + /** + * @brief Use this method to edit text and game messages sent by the bot or via the bot (for inline bots) + * @param text New text of the message + * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. + * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message + * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message + * @param parseMode Optional Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message. + * @param disableWebPagePreview Optional Disables link previews for links in this message + * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. + * @return Message object on success, otherwise nullptr + */ + Message::Ptr editMessageText(const std::string& text, int64_t chatId=0, int32_t messageId=0, const std::string& inlineMessageId="", + const std::string& parseMode = "", bool disableWebPagePreview = false, GenericReply::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). + * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. + * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message + * @param caption Optional New caption of the message + * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message + * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. + * @return Message object on success, otherwise nullptr + */ + Message::Ptr editMessageCaption(int64_t chatId = 0, int32_t messageId = 0, const std::string& caption = "", + const std::string& inlineMessageId = "", GenericReply::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots). + * @param chatId Optional Required if inline_message_id is not specified. Unique identifier for the target chat of the target channel. + * @param messageId Optional Required if inline_message_id is not specified. Identifier of the sent message + * @param inlineMessageId Optional Required if chat_id and message_id are not specified. Identifier of the inline message + * @param replyMarkup Optional A JSON-serialized object for an inline keyboard. + * @return Message object on success, otherwise nullptr + */ + Message::Ptr editMessageReplyMarkup(int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "", + const GenericReply::Ptr replyMarkup = std::make_shared()) const; + + /** + * @brief Use this method to delete messages sent by bot (or by other users if bot is admin). + * @param chatId Unique identifier for the target chat. + * @param messageId Unique identifier for the target message. + */ + void deleteMessage(int64_t chatId, int32_t messageId) const; + + /** + * @brief Use this method to receive incoming updates using long polling. + * + * This method will not work if an outgoing webhook is set up. + * In order to avoid getting duplicate updates, recalculate offset after each server response. + * + * @param offset Optional. Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. + * @param limit Optional. Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. + * @param timeout Optional. Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. + * @param allowed_updates Optional. List the types of updates you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types. See Update for a complete list of available update types. Specify an empty list to receive all updates regardless of type (default). If not specified, the previous setting will be used. + * @return An Array of Update objects + */ + std::vector getUpdates(int32_t offset = 0, int32_t limit = 100, int32_t timeout = 0, const StringArrayPtr &allowedUpdates = nullptr) const; + + /** + * @brief Use this method to specify a url and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. + * + * If you'd like to make sure that the Webhook request comes from Telegram, we recommend using a secret path in the URL, e.g. www.example.com/. Since nobody else knows your bot‘s token, you can be pretty sure it’s us. + * You will not be able to receive updates using getUpdates for as long as an outgoing webhook is set up. + * We currently do not support self-signed certificates. + * Ports currently supported for Webhooks: 443, 80, 88, 8443. + * + * @param url Optional. HTTPS url to send updates to. Use an empty string to remove webhook integration. + */ + void setWebhook(const std::string& url = "", InputFile::Ptr certificate = nullptr, int32_t maxConnection = 40, const StringArrayPtr &allowedUpdates = nullptr) const; + + /** + * @brief Use this method to remove webhook integration if you decide to switch back to getUpdates. + * + * Requires no parameters. + * + * @return Returns True on success. + */ + bool deleteWebhook() const; + + /** + * @brief Use this method to get current webhook status. + * + * Requires no parameters. + * If the bot is using getUpdates, will return an object with the url field empty. + * + * @return On success, returns a WebhookInfo object. + */ + WebhookInfo::Ptr getWebhookInfo() const; + + /** + * @brief Use this method to send answers to an inline query. + * No mode that 50 results per query are allowed. + * @param inlineQueryId Unique identifier for the answered query. + * @param results Array of results for the inline query. + * @param cacheTime The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. + * @param isPersonal Pass True, if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. + * @param nextOffset Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. + * @param switchPmText If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter + * @param switchPmParameter Parameter for the start message sent to the bot when user presses the switch button + * @return True on success + */ + bool answerInlineQuery(const std::string& inlineQueryId, const std::vector& results, + int32_t cacheTime = 300, bool isPersonal = false, const std::string& nextOffset = "", const std::string& switchPmText = "", const std::string& switchPmParameter = "") const; + + /** + * @brief Use this method to kick a user from a group or a supergroup. + * @param chatId Unique identifier for the target group. + * @param userId Unique identifier of the target user. + * @param untilDate Optional. Date when the user will be unbanned, unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. + * @return True on success + */ + bool kickChatMember(int64_t chatId, int32_t userId, uint64_t untilDate = 0) const; + + /** + * @brief Use this method to unban a previously kicked user in a supergroup. + * @param chatId Unique identifier for the target group. + * @param userId Unique identifier of the target user. + * @return True on success + */ + bool unbanChatMember(int64_t chatId, int32_t userId) const; + + /** + * @brief Use this method to restrict a user in a supergroup. + * @param chatId Unique identifier for the target chat of the target supergroup. + * @param userId Unique identifier of the target user. + * @param untilDate Optional. Date when restrictions will be lifted for the user, unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever. + * @param canSendMessages Optional. Pass True, if the user can send text messages, contacts, locations and venues. + * @param canSendMediaMessages Optional. Pass True, if the user can send audios, documents, photos, videos, video notes and voice notes, implies can_send_messages. + * @param canSendOtherMessages Optional. Pass True, if the user can send animations, games, stickers and use inline bots, implies can_send_media_messages. + * @param canAddWebPagePreviews Optional. Pass True, if the user may add web page previews to their messages, implies can_send_media_messages. + * @return True on success + */ + bool restrictChatMember(int64_t chatId, int32_t userId, uint64_t untilDate = 0, bool canSendMessages = false, + bool canSendMediaMessages = false, bool canSendOtherMessages = false, bool canAddWebPagePreviews = false) const; + + /** + * @brief Use this method to promote or demote a user in a supergroup or a channel. + * @param chatId Unique identifier for the target chat of the target supergroup or channal. + * @param userId Unique identifier of the target user. + * @param canChangeInfo Optional. Pass True, if the administrator can change chat title, photo and other settings. + * @param canPostMessages Optional. Pass True, if the administrator can create channel posts, channels only. + * @param canEditMessages Optional. Pass True, if the administrator can edit messages of other users and can pin messages, channels only. + * @param canDeleteMessages Optional. Pass True, if the administrator can delete messages of other users. + * @param canInviteUsers Optional. Pass True, if the administrator can invite new users to the chat. + * @param canRestrictMembers Optional. Pass True, if the administrator can restrict, ban or unban chat members. + * @param canPinMessages Optional. Pass True, if the administrator can pin messages, supergroups only. + * @param canPromoteMembers Optional. Pass True, if the administrator can add new administrators with a subset of his own privileges or demote administrators that he has promoted, directly or indirectly (promoted by administrators that were appointed by him). + * @return True on success + */ + bool promoteChatMember(int64_t chatId, int32_t userId, bool canChangeInfo = false, bool canPostMessages = false, + bool canEditMessages = false, bool canDeleteMessages = false, bool canInviteUsers = false, bool canPinMessages = false, bool canPromoteMembers = false) const; + + /** + * @brief Use this method to generate a new invite link for a chat; any previously generated link is revoked. + * @param chatId Unique identifier for the target chat. + * @return The new invite link as String on success. + */ + std::string exportChatInviteLink(int64_t chatId) const; + + /** + * @brief Use this method to set a new profile photo for the chat. + * + * Photos can't be changed for private chats. + * + * @param chatId Unique identifier for the target chat. + * @param photo New chat photo. + * @return True on success + */ + bool setChatPhoto(int64_t chatId, InputFile::Ptr photo) const; + + /** + * @brief Use this method to delete a chat photo. + * + * Photos can't be changed for private chats. + * + * @param chatId Unique identifier for the target chat. + * @return True on success + */ + bool deleteChatPhoto(int64_t chatId) const; + + /** + * @brief Use this method to change the title of a chat. + * + * Titles can't be changed for private chats. + * + * @param chatId Unique identifier for the target chat. + * @param title New chat title, 1-255 characters. + * @return True on success + */ + bool setChatTitle(int64_t chatId, const std::string& title) const; + + /** + * @brief Use this method to change the description of a supergroup or a channel. + * @param chatId Unique identifier for the target chat. + * @param description New chat description, 1-255 characters. + * @return True on success + */ + bool setChatDescription(int64_t chatId, const std::string& description) const; + + /** + * @brief Use this method to pin a message in a supergroup or a channel. + * @param chatId Unique identifier for the target chat. + * @param messageId Identifier of a message to pin. + * @param disableNotification Optional. Pass True, if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels. + * @return True on success + */ + bool pinChatMessage(int64_t chatId, int32_t messageId, bool disableNotification = false) const; + + /** + * @brief Use this method to unpin a message in a supergroup or a channel. + * @param chatId Unique identifier for the target chat. + * @return True on success + */ + bool unpinChatMessage(int64_t chatId) const; + + /** + * @brief Use this method to set the score of the specified user in a game. + * + * Returns an error, if the new score is not greater than the user's current score in the chat and force is False. + * + * @param userId User identifier. + * @param score New score, must be non-negative. + * @param force Optional. Pass True, if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters. + * @param disableEditMessage Optional. Pass True, if the game message should not be automatically edited to include the current scoreboard. + * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat + * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message + * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message + * @return On success, if the message was sent by the bot, returns the edited Message, otherwise returns nullptr. + */ + Message::Ptr setGameScore(int32_t userId, int32_t score, bool force = false, bool disableEditMessage = false, + int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "") const; + + /** + * @brief Use this method to get data for high score tables. + * + * Will return the score of the specified user and several of his neighbors in a game. + * + * @param userId User identifier. + * @param chatId Optional. Required if inlineMessageId is not specified. Unique identifier for the target chat + * @param messageId Optional. Required if inlineMessageId is not specified. Identifier of the sent message + * @param inlineMessageId Optional. Required if chatId and messageId are not specified. Identifier of the inline message + * @return On success, returns an Array of GameHighScore objects. + */ + std::vector getGameHighScores(int32_t userId, int32_t score, bool force = false, + bool disableEditMessage = false, int64_t chatId = 0, int32_t messageId = 0, const std::string& inlineMessageId = "") const; + + + /** + * @brief Downloads file from Telegram and saves it in memory. + * @param filePath Telegram file path. + * @param args Additional api parameters. + * @return File contents in a string. + */ + std::string downloadFile(const std::string& filePath, const std::vector& args = std::vector()) const; private: - boost::property_tree::ptree sendRequest(const std::string& method, const std::vector& args = std::vector()) const; + boost::property_tree::ptree sendRequest(const std::string& method, const std::vector& args = std::vector()) const; - const std::string _token; - const HttpClient& _httpClientDriver; + const std::string _token; + const HttpClient& _httpClient; + const TgTypeParser _tgTypeParser; }; } diff --git a/include/tgbot/Bot.h b/include/tgbot/Bot.h index b8c8a85..e2d9027 100644 --- a/include/tgbot/Bot.h +++ b/include/tgbot/Bot.h @@ -24,11 +24,12 @@ #define TGBOT_CPP_BOT_H #include - +#include #include "tgbot/Api.h" #include "tgbot/EventBroadcaster.h" #include "tgbot/EventHandler.h" #include "tgbot/net/HttpClient.h" +#include "tgbot/net/BoostHttpOnlySslClient.h" namespace TgBot { @@ -40,44 +41,48 @@ namespace TgBot { class Bot { public: - explicit Bot(const std::string& token, const HttpClient &httpClientDriver = BoostHttpClient::getInstance()) - : _token(token), _api(token, httpClientDriver), _eventHandler(&_eventBroadcaster), _httpClientDriver(httpClientDriver) { - } + explicit Bot(std::string token, const HttpClient& httpClient = _getDefaultHttpClient()) + : _token(std::move(token)), _api(_token, httpClient), _eventHandler(_eventBroadcaster) { + } - /** - * @return Token for accessing api. - */ - inline const std::string& getToken() const { - return _token; - } + /** + * @return Token for accessing api. + */ + inline const std::string& getToken() const { + return _token; + } - /** - * @return Object which can execute Telegram Bot API methods. - */ - inline const Api& getApi() const { - return _api; - } + /** + * @return Object which can execute Telegram Bot API methods. + */ + inline const Api& getApi() const { + return _api; + } - /** - * @return Object which holds all event listeners. - */ - inline EventBroadcaster& getEvents() { - return _eventBroadcaster; - } + /** + * @return Object which holds all event listeners. + */ + inline EventBroadcaster& getEvents() { + return _eventBroadcaster; + } - /** - * @return Object which handles new update objects. Usually it's only needed for TgLongPoll, TgWebhookLocalServer and TgWebhookTcpServer objects. - */ - inline const EventHandler& getEventHandler() const { - return _eventHandler; - } + /** + * @return Object which handles new update objects. Usually it's only needed for TgLongPoll, TgWebhookLocalServer and TgWebhookTcpServer objects. + */ + inline const EventHandler& getEventHandler() const { + return _eventHandler; + } private: - const std::string _token; - const Api _api; - EventBroadcaster _eventBroadcaster; - const EventHandler _eventHandler; - const HttpClient& _httpClientDriver; + static HttpClient& _getDefaultHttpClient() { + static BoostHttpOnlySslClient instance; + return instance; + } + + const std::string _token; + const Api _api; + EventBroadcaster _eventBroadcaster; + const EventHandler _eventHandler; }; } diff --git a/include/tgbot/EventBroadcaster.h b/include/tgbot/EventBroadcaster.h index 0a4ebe9..d879ab4 100644 --- a/include/tgbot/EventBroadcaster.h +++ b/include/tgbot/EventBroadcaster.h @@ -47,127 +47,127 @@ class EventBroadcaster { friend EventHandler; public: - typedef std::function MessageListener; - typedef std::function InlineQueryListener; - typedef std::function ChosenInlineResultListener; - typedef std::function CallbackQueryListener; - - /** - * @brief Registers listener which receives all messages which the bot can ever receive. - * @param listener Listener. - */ - inline void onAnyMessage(const MessageListener& listener) { - _onAnyMessageListeners.push_back(listener); - } - - /** - * @brief Registers listener which receives all messages with commands (messages with leading '/' char). - * @param commandName Command name which listener can handle. - * @param listener Listener. - */ - inline void onCommand(const std::string& commandName, const MessageListener& listener) { - _onCommandListeners[commandName] = listener; - } - - /** - * @brief Registers listener which receives all messages with commands (messages with leading '/' char). - * @param commandsList Commands names which listener can handle. - * @param listener Listener. - */ - inline void onCommand(const std::initializer_list& commandsList, const MessageListener& listener) { - for (const auto& command : commandsList) - { - _onCommandListeners[command] = listener; - } - } - - /** - * @brief Registers listener which receives all messages with commands (messages with leading '/' char) which haven't been handled by other listeners. - * @param listener Listener. - */ - inline void onUnknownCommand(const MessageListener& listener) { - _onUnknownCommandListeners.push_back(listener); - } - - /** - * @brief Registers listener which receives all messages without commands (messages with no leading '/' char) - * @param listener Listener. - */ - inline void onNonCommandMessage(const MessageListener& listener) { - _onNonCommandMessageListeners.push_back(listener); - } - - /** - * @brief Registers listener which receives all the inline query. - * @param listener Listener. - */ - inline void onInlineQuery(const InlineQueryListener& listener) { - _onInlineQueryListeners.push_back(listener); - } - - /** - * @brief Registers listener which receives all the chosen inline result. - * @param listener Listener. - */ - inline void onChosenInlineResult(const ChosenInlineResultListener& listener){ - _onChosenInlineResultListeners.push_back(listener); - } - - inline void onCallbackQuery(const CallbackQueryListener& listener){ - _onCallbackQueryListeners.push_back(listener); - } + typedef std::function MessageListener; + typedef std::function InlineQueryListener; + typedef std::function ChosenInlineResultListener; + typedef std::function CallbackQueryListener; + + /** + * @brief Registers listener which receives all messages which the bot can ever receive. + * @param listener Listener. + */ + inline void onAnyMessage(const MessageListener& listener) { + _onAnyMessageListeners.push_back(listener); + } + + /** + * @brief Registers listener which receives all messages with commands (messages with leading '/' char). + * @param commandName Command name which listener can handle. + * @param listener Listener. + */ + inline void onCommand(const std::string& commandName, const MessageListener& listener) { + _onCommandListeners[commandName] = listener; + } + + /** + * @brief Registers listener which receives all messages with commands (messages with leading '/' char). + * @param commandsList Commands names which listener can handle. + * @param listener Listener. + */ + inline void onCommand(const std::initializer_list& commandsList, const MessageListener& listener) { + for (const auto& command : commandsList) + { + _onCommandListeners[command] = listener; + } + } + + /** + * @brief Registers listener which receives all messages with commands (messages with leading '/' char) which haven't been handled by other listeners. + * @param listener Listener. + */ + inline void onUnknownCommand(const MessageListener& listener) { + _onUnknownCommandListeners.push_back(listener); + } + + /** + * @brief Registers listener which receives all messages without commands (messages with no leading '/' char) + * @param listener Listener. + */ + inline void onNonCommandMessage(const MessageListener& listener) { + _onNonCommandMessageListeners.push_back(listener); + } + + /** + * @brief Registers listener which receives all the inline query. + * @param listener Listener. + */ + inline void onInlineQuery(const InlineQueryListener& listener) { + _onInlineQueryListeners.push_back(listener); + } + + /** + * @brief Registers listener which receives all the chosen inline result. + * @param listener Listener. + */ + inline void onChosenInlineResult(const ChosenInlineResultListener& listener){ + _onChosenInlineResultListeners.push_back(listener); + } + + inline void onCallbackQuery(const CallbackQueryListener& listener){ + _onCallbackQueryListeners.push_back(listener); + } private: - template - inline void broadcast(const std::vector& listeners, const ObjectType object) const { - if (!object) - return; - - for (const ListenerType& item : listeners) { - item(object); - } - } - - inline void broadcastAnyMessage(const Message::Ptr message) const { - broadcast(_onAnyMessageListeners, message); - } - - inline bool broadcastCommand(const std::string command, const Message::Ptr message) const { - std::unordered_map::const_iterator iter = _onCommandListeners.find(command); - if (iter == _onCommandListeners.end()) { - return false; - } - iter->second(message); - return true; - } - - inline void broadcastUnknownCommand(const Message::Ptr message) const { - broadcast(_onUnknownCommandListeners, message); - } - - inline void broadcastNonCommandMessage(const Message::Ptr message) const { - broadcast(_onNonCommandMessageListeners, message); - } - - inline void broadcastInlineQuery(const InlineQuery::Ptr query) const { - broadcast(_onInlineQueryListeners, query); - } - - inline void broadcastChosenInlineResult(const ChosenInlineResult::Ptr result) const { - broadcast(_onChosenInlineResultListeners, result); - } - - inline void broadcastCallbackQuery(const CallbackQuery::Ptr result) const { - broadcast(_onCallbackQueryListeners, result); - } - - std::vector _onAnyMessageListeners; - std::unordered_map _onCommandListeners; - std::vector _onUnknownCommandListeners; - std::vector _onNonCommandMessageListeners; - std::vector _onInlineQueryListeners; - std::vector _onChosenInlineResultListeners; - std::vector _onCallbackQueryListeners; + template + inline void broadcast(const std::vector& listeners, const ObjectType object) const { + if (!object) + return; + + for (const ListenerType& item : listeners) { + item(object); + } + } + + inline void broadcastAnyMessage(const Message::Ptr message) const { + broadcast(_onAnyMessageListeners, message); + } + + inline bool broadcastCommand(const std::string command, const Message::Ptr message) const { + std::unordered_map::const_iterator iter = _onCommandListeners.find(command); + if (iter == _onCommandListeners.end()) { + return false; + } + iter->second(message); + return true; + } + + inline void broadcastUnknownCommand(const Message::Ptr message) const { + broadcast(_onUnknownCommandListeners, message); + } + + inline void broadcastNonCommandMessage(const Message::Ptr message) const { + broadcast(_onNonCommandMessageListeners, message); + } + + inline void broadcastInlineQuery(const InlineQuery::Ptr query) const { + broadcast(_onInlineQueryListeners, query); + } + + inline void broadcastChosenInlineResult(const ChosenInlineResult::Ptr result) const { + broadcast(_onChosenInlineResultListeners, result); + } + + inline void broadcastCallbackQuery(const CallbackQuery::Ptr result) const { + broadcast(_onCallbackQueryListeners, result); + } + + std::vector _onAnyMessageListeners; + std::unordered_map _onCommandListeners; + std::vector _onUnknownCommandListeners; + std::vector _onNonCommandMessageListeners; + std::vector _onInlineQueryListeners; + std::vector _onChosenInlineResultListeners; + std::vector _onCallbackQueryListeners; }; } diff --git a/include/tgbot/EventHandler.h b/include/tgbot/EventHandler.h index 7fa68ee..edc84dc 100644 --- a/include/tgbot/EventHandler.h +++ b/include/tgbot/EventHandler.h @@ -32,15 +32,15 @@ namespace TgBot { class EventHandler { public: - explicit EventHandler(const EventBroadcaster* broadcaster) : _broadcaster(broadcaster) { - } + explicit EventHandler(const EventBroadcaster& broadcaster) : _broadcaster(broadcaster) { + } - void handleUpdate(const Update::Ptr update) const; + void handleUpdate(Update::Ptr update) const; private: - const EventBroadcaster* _broadcaster; + const EventBroadcaster& _broadcaster; - void handleMessage(const Message::Ptr message) const; + void handleMessage(Message::Ptr message) const; }; } diff --git a/include/tgbot/TgException.h b/include/tgbot/TgException.h index 4b03e1c..d6ff7d7 100644 --- a/include/tgbot/TgException.h +++ b/include/tgbot/TgException.h @@ -36,7 +36,7 @@ namespace TgBot { class TgException : public std::runtime_error { public: - explicit TgException(const std::string description); + explicit TgException(const std::string description); }; } diff --git a/include/tgbot/TgTypeParser.h b/include/tgbot/TgTypeParser.h index 356b69e..656007b 100644 --- a/include/tgbot/TgTypeParser.h +++ b/include/tgbot/TgTypeParser.h @@ -105,348 +105,371 @@ namespace TgBot { class TgTypeParser { public: - template - using JsonToTgTypeFunc = std::shared_ptr (TgTypeParser::*)(const boost::property_tree::ptree&) const; - - template - using TgTypeToJsonFunc = std::string (TgTypeParser::*)(const std::shared_ptr&) const; - - static TgTypeParser& getInstance(); - - Chat::Ptr parseJsonAndGetChat(const boost::property_tree::ptree& data) const; - std::string parseChat(const Chat::Ptr& object) const; - User::Ptr parseJsonAndGetUser(const boost::property_tree::ptree& data) const; - std::string parseUser(const User::Ptr& object) const; - MessageEntity::Ptr parseJsonAndGetMessageEntity(const boost::property_tree::ptree& data) const; - std::string parseMessageEntity(const MessageEntity::Ptr& object) const; - Message::Ptr parseJsonAndGetMessage(const boost::property_tree::ptree& data) const; - std::string parseMessage(const Message::Ptr& object) const; - PhotoSize::Ptr parseJsonAndGetPhotoSize(const boost::property_tree::ptree& data) const; - std::string parsePhotoSize(const PhotoSize::Ptr& object) const; - Audio::Ptr parseJsonAndGetAudio(const boost::property_tree::ptree& data) const; - std::string parseAudio(const Audio::Ptr& object) const; - Document::Ptr parseJsonAndGetDocument(const boost::property_tree::ptree& data) const; - std::string parseDocument(const Document::Ptr& object) const; - Sticker::Ptr parseJsonAndGetSticker(const boost::property_tree::ptree& data) const; - std::string parseSticker(const Sticker::Ptr& object) const; - StickerSet::Ptr parseJsonAndGetStickerSet(const boost::property_tree::ptree& data) const; - std::string parseStickerSet(const StickerSet::Ptr& object) const; - MaskPosition::Ptr parseJsonAndGetMaskPosition(const boost::property_tree::ptree& data) const; - std::string parseMaskPosition(const MaskPosition::Ptr& object) const; - Video::Ptr parseJsonAndGetVideo(const boost::property_tree::ptree& data) const; - std::string parseVideo(const Video::Ptr& object) const; - VideoNote::Ptr parseJsonAndGetVideoNote(const boost::property_tree::ptree& data) const; - std::string parseVideoNote(const VideoNote::Ptr& object) const; - Game::Ptr parseJsonAndGetGame(const boost::property_tree::ptree& data) const; - std::string parseGame(const Game::Ptr& object) const; - GameHighScore::Ptr parseJsonAndGetGameHighScore(const boost::property_tree::ptree& data) const; - std::string parseGameHighScore(const GameHighScore::Ptr& object) const; - Animation::Ptr parseJsonAndGetAnimation(const boost::property_tree::ptree& data) const; - std::string parseAnimation(const Animation::Ptr& object) const; - Contact::Ptr parseJsonAndGetContact(const boost::property_tree::ptree& data) const; - std::string parseContact(const Contact::Ptr& object) const; - Location::Ptr parseJsonAndGetLocation(const boost::property_tree::ptree& data) const; - std::string parseLocation(const Location::Ptr& object) const; - Update::Ptr parseJsonAndGetUpdate(const boost::property_tree::ptree& data) const; - std::string parseUpdate(const Update::Ptr& object) const; - UserProfilePhotos::Ptr parseJsonAndGetUserProfilePhotos(const boost::property_tree::ptree& data) const; - std::string parseUserProfilePhotos(const UserProfilePhotos::Ptr& object) const; - InputMedia::Ptr parseJsonAndGetInputMedia(const boost::property_tree::ptree& data) const; - std::string parseInputMedia(const InputMedia::Ptr& object) const; - - File::Ptr parseJsonAndGetFile(const boost::property_tree::ptree& data) const; - std::string parseFile(const File::Ptr& object) const; - - ReplyKeyboardMarkup::Ptr parseJsonAndGetReplyKeyboardMarkup(const boost::property_tree::ptree& data) const; - std::string parseReplyKeyboardMarkup(const ReplyKeyboardMarkup::Ptr& object) const; - - KeyboardButton::Ptr parseJsonAndGetKeyboardButton(const boost::property_tree::ptree& data) const; - std::string parseKeyboardButton(const KeyboardButton::Ptr& object) const; - - ReplyKeyboardRemove::Ptr parseJsonAndGetReplyKeyboardRemove(const boost::property_tree::ptree& data) const; - std::string parseReplyKeyboardRemove(const ReplyKeyboardRemove::Ptr& object) const; - - ForceReply::Ptr parseJsonAndGetForceReply(const boost::property_tree::ptree& data) const; - std::string parseForceReply(const ForceReply::Ptr& object) const; - - ChatMember::Ptr parseJsonAndGetChatMember(const boost::property_tree::ptree& data) const; - std::string parseChatMember(const ChatMember::Ptr& object) const; - - ChatPhoto::Ptr parseJsonAndGetChatPhoto(const boost::property_tree::ptree& data) const; - std::string parseChatPhoto(const ChatPhoto::Ptr& object) const; - - ResponseParameters::Ptr parseJsonAndGetResponseParameters(const boost::property_tree::ptree& data) const; - std::string parseResponseParameters(const ResponseParameters::Ptr& object) const; - - GenericReply::Ptr parseJsonAndGetGenericReply(const boost::property_tree::ptree& data) const; - std::string parseGenericReply(const GenericReply::Ptr& object) const; - - InlineQuery::Ptr parseJsonAndGetInlineQuery(const boost::property_tree::ptree& data) const; - std::string parseInlineQuery(const InlineQuery::Ptr& object) const; - - InlineQueryResult::Ptr parseJsonAndGetInlineQueryResult(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResult(const InlineQueryResult::Ptr& object) const; - - InlineQueryResultCachedAudio::Ptr parseJsonAndGetInlineQueryResultCachedAudio(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedAudio(const InlineQueryResultCachedAudio::Ptr& object) const; - - InlineQueryResultCachedDocument::Ptr parseJsonAndGetInlineQueryResultCachedDocument(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedDocument(const InlineQueryResultCachedDocument::Ptr& object) const; - - InlineQueryResultCachedGif::Ptr parseJsonAndGetInlineQueryResultCachedGif(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedGif(const InlineQueryResultCachedGif::Ptr& object) const; - - InlineQueryResultCachedMpeg4Gif::Ptr parseJsonAndGetInlineQueryResultCachedMpeg4Gif(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedMpeg4Gif(const InlineQueryResultCachedMpeg4Gif::Ptr& object) const; - - InlineQueryResultCachedPhoto::Ptr parseJsonAndGetInlineQueryResultCachedPhoto(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedPhoto(const InlineQueryResultCachedPhoto::Ptr& object) const; - - InlineQueryResultCachedSticker::Ptr parseJsonAndGetInlineQueryResultCachedSticker(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedSticker(const InlineQueryResultCachedSticker::Ptr& object) const; - - InlineQueryResultCachedVideo::Ptr parseJsonAndGetInlineQueryResultCachedVideo(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedVideo(const InlineQueryResultCachedVideo::Ptr& object) const; - - InlineQueryResultCachedVoice::Ptr parseJsonAndGetInlineQueryResultCachedVoice(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultCachedVoice(const InlineQueryResultCachedVoice::Ptr& object) const; - - InlineQueryResultArticle::Ptr parseJsonAndGetInlineQueryResultArticle(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultArticle(const InlineQueryResultArticle::Ptr& object) const; - - InlineQueryResultAudio::Ptr parseJsonAndGetInlineQueryResultAudio(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultAudio(const InlineQueryResultAudio::Ptr& object) const; - - InlineQueryResultContact::Ptr parseJsonAndGetInlineQueryResultContact(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultContact(const InlineQueryResultContact::Ptr& object) const; - - InlineQueryResultGame::Ptr parseJsonAndGetInlineQueryResultGame(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultGame(const InlineQueryResultGame::Ptr& object) const; - - InlineQueryResultDocument::Ptr parseJsonAndGetInlineQueryResultDocument(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultDocument(const InlineQueryResultDocument::Ptr& object) const; - - InlineQueryResultLocation::Ptr parseJsonAndGetInlineQueryResultLocation(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultLocation(const InlineQueryResultLocation::Ptr& object) const; - - InlineQueryResultVenue::Ptr parseJsonAndGetInlineQueryResultVenue(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultVenue(const InlineQueryResultVenue::Ptr& object) const; - - InlineQueryResultVoice::Ptr parseJsonAndGetInlineQueryResultVoice(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultVoice(const InlineQueryResultVoice::Ptr& object) const; - - InlineQueryResultPhoto::Ptr parseJsonAndGetInlineQueryResultPhoto(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultPhoto(const InlineQueryResultPhoto::Ptr& object) const; - InlineQueryResultGif::Ptr parseJsonAndGetInlineQueryResultGif(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultGif(const InlineQueryResultGif::Ptr& object) const; - InlineQueryResultMpeg4Gif::Ptr parseJsonAndGetInlineQueryResultMpeg4Gif(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultMpeg4Gif(const InlineQueryResultMpeg4Gif::Ptr& object) const; - InlineQueryResultVideo::Ptr parseJsonAndGetInlineQueryResultVideo(const boost::property_tree::ptree& data) const; - std::string parseInlineQueryResultVideo(const InlineQueryResultVideo::Ptr& object) const; - ChosenInlineResult::Ptr parseJsonAndGetChosenInlineResult(const boost::property_tree::ptree& data) const; - std::string parseChosenInlineResult(const ChosenInlineResult::Ptr& object) const; - - CallbackQuery::Ptr parseJsonAndGetCallbackQuery(const boost::property_tree::ptree& data) const; - std::string parseCallbackQuery(const CallbackQuery::Ptr& object) const; - InlineKeyboardMarkup::Ptr parseJsonAndGetInlineKeyboardMarkup(const boost::property_tree::ptree& data) const; - std::string parseInlineKeyboardMarkup(const InlineKeyboardMarkup::Ptr& object) const; - InlineKeyboardButton::Ptr parseJsonAndGetInlineKeyboardButton(const boost::property_tree::ptree& data) const; - std::string parseInlineKeyboardButton(const InlineKeyboardButton::Ptr& object) const; - - WebhookInfo::Ptr parseJsonAndGetWebhookInfo(const boost::property_tree::ptree& data) const; - std::string parseWebhookInfo(const WebhookInfo::Ptr& object) const; - - InputMessageContent::Ptr parseJsonAndGetInputMessageContent(const boost::property_tree::ptree& data) const; - std::string parseInputMessageContent(const InputMessageContent::Ptr& object) const; - - InputTextMessageContent::Ptr parseJsonAndGetInputTextMessageContent(const boost::property_tree::ptree& data) const; - std::string parseInputTextMessageContent(const InputTextMessageContent::Ptr& object) const; - - InputLocationMessageContent::Ptr parseJsonAndGetInputLocationMessageContent(const boost::property_tree::ptree& data) const; - std::string parseInputLocationMessageContent(const InputLocationMessageContent::Ptr& object) const; - - InputVenueMessageContent::Ptr parseJsonAndGetInputVenueMessageContent(const boost::property_tree::ptree& data) const; - std::string parseInputVenueMessageContent(const InputVenueMessageContent::Ptr& object) const; - - InputContactMessageContent::Ptr parseJsonAndGetInputContactMessageContent(const boost::property_tree::ptree& data) const; - std::string parseInputContactMessageContent(const InputContactMessageContent::Ptr& object) const; - - Invoice::Ptr parseJsonAndGetInvoice(const boost::property_tree::ptree& data) const; - std::string parseInvoice(const Invoice::Ptr& object) const; - - LabeledPrice::Ptr parseJsonAndGetLabeledPrice(const boost::property_tree::ptree& data) const; - std::string parseLabeledPrice(const LabeledPrice::Ptr& object) const; - - OrderInfo::Ptr parseJsonAndGetOrderInfo(const boost::property_tree::ptree& data) const; - std::string parseOrderInfo(const OrderInfo::Ptr& object) const; - - PreCheckoutQuery::Ptr parseJsonAndGetPreCheckoutQuery(const boost::property_tree::ptree& data) const; - std::string parsePreCheckoutQuery(const PreCheckoutQuery::Ptr& object) const; - - ShippingAddress::Ptr parseJsonAndGetShippingAddress(const boost::property_tree::ptree& data) const; - std::string parseShippingAddress(const ShippingAddress::Ptr& object) const; - - ShippingOption::Ptr parseJsonAndGetShippingOption(const boost::property_tree::ptree& data) const; - std::string parseShippingOption(const ShippingOption::Ptr& object) const; - - ShippingQuery::Ptr parseJsonAndGetShippingQuery(const boost::property_tree::ptree& data) const; - std::string parseShippingQuery(const ShippingQuery::Ptr& object) const; - - SuccessfulPayment::Ptr parseJsonAndGetSuccessfulPayment(const boost::property_tree::ptree& data) const; - std::string parseSuccessfulPayment(const SuccessfulPayment::Ptr& object) const; - - inline boost::property_tree::ptree parseJson(const std::string& json) const { - boost::property_tree::ptree tree; - std::istringstream input(json); - boost::property_tree::read_json(input, tree); - return tree; - } - - template - std::shared_ptr tryParseJson(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { - auto treeItem = data.find(keyName); - if (treeItem == data.not_found()) { - return std::shared_ptr(); - } - return (this->*parseFunc)(treeItem->second); - } - - template - std::vector> parseJsonAndGetArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data) const { - std::vector> result; - result.reserve(data.size()); - for (const std::pair& innerTreeItem : data) { - result.push_back((this->*parseFunc)(innerTreeItem.second)); - } - return result; - } - - template - std::vector parseJsonAndGetArray(std::function parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { - std::vector result; - auto treeItem = data.find(keyName); - if (treeItem == data.not_found()) { - return result; - } - result.reserve(treeItem->second.size()); - for (const std::pair& innerTreeItem : treeItem->second) { - result.push_back(parseFunc(innerTreeItem.second)); - } - return result; - } - - template - std::vector> parseJsonAndGetArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { - std::vector> result; - auto treeItem = data.find(keyName); - if (treeItem == data.not_found()) { - return result; - } - result.reserve(treeItem->second.size()); - for (const std::pair& innerTreeItem : treeItem->second) { - result.push_back((this->*parseFunc)(innerTreeItem.second)); - } - return result; - } - - template - std::vector>> parseJsonAndGet2DArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { - std::vector>> result; - auto treeItem = data.find(keyName); - if (treeItem == data.not_found()) { - return result; - } - result.reserve(treeItem->second.size()); - for (const std::pair& innerTreeItem : treeItem->second) { - std::vector> innerResult; - for (const std::pair& innerInnerTreeItem : innerTreeItem.second) { - innerResult.push_back((this->*parseFunc)(innerInnerTreeItem.second)); - } - result.push_back(innerResult); - } - return result; - } - - template - std::string parseArray(TgTypeToJsonFunc parseFunc, const std::vector>& objects) const { - if (objects.empty()) - return ""; - std::string result; - result += '['; - for (const std::shared_ptr& item : objects) { - result += (this->*parseFunc)(item); - result += ','; - } - result.erase(result.length() - 1); - result += ']'; - return result; - } - - template - std::string parseArray(std::function parseFunc, const std::vector& objects) const { - if (objects.empty()) - return ""; - std::string result; - result += '['; - for (const T& item : objects) { - result += parseFunc(item); - result += ','; - } - result.erase(result.length() - 1); - result += ']'; - return result; - } - - template - std::string parse2DArray(TgTypeToJsonFunc parseFunc, const std::vector>>& objects) const { - if (objects.empty()) - return ""; - std::string result; - result += '['; - for (const std::vector>& item : objects) { - result += parseArray(parseFunc, item); - result += ','; - } - result.erase(result.length() - 1); - result += ']'; - return result; - } + template + using JsonToTgTypeFunc = std::shared_ptr (TgTypeParser::*)(const boost::property_tree::ptree&) const; + + template + using TgTypeToJsonFunc = std::string (TgTypeParser::*)(const std::shared_ptr&) const; + + Chat::Ptr parseJsonAndGetChat(const boost::property_tree::ptree& data) const; + std::string parseChat(const Chat::Ptr& object) const; + + User::Ptr parseJsonAndGetUser(const boost::property_tree::ptree& data) const; + std::string parseUser(const User::Ptr& object) const; + + MessageEntity::Ptr parseJsonAndGetMessageEntity(const boost::property_tree::ptree& data) const; + std::string parseMessageEntity(const MessageEntity::Ptr& object) const; + + Message::Ptr parseJsonAndGetMessage(const boost::property_tree::ptree& data) const; + std::string parseMessage(const Message::Ptr& object) const; + + PhotoSize::Ptr parseJsonAndGetPhotoSize(const boost::property_tree::ptree& data) const; + std::string parsePhotoSize(const PhotoSize::Ptr& object) const; + + Audio::Ptr parseJsonAndGetAudio(const boost::property_tree::ptree& data) const; + std::string parseAudio(const Audio::Ptr& object) const; + + Document::Ptr parseJsonAndGetDocument(const boost::property_tree::ptree& data) const; + std::string parseDocument(const Document::Ptr& object) const; + + Sticker::Ptr parseJsonAndGetSticker(const boost::property_tree::ptree& data) const; + std::string parseSticker(const Sticker::Ptr& object) const; + + StickerSet::Ptr parseJsonAndGetStickerSet(const boost::property_tree::ptree& data) const; + std::string parseStickerSet(const StickerSet::Ptr& object) const; + + MaskPosition::Ptr parseJsonAndGetMaskPosition(const boost::property_tree::ptree& data) const; + std::string parseMaskPosition(const MaskPosition::Ptr& object) const; + + Video::Ptr parseJsonAndGetVideo(const boost::property_tree::ptree& data) const; + std::string parseVideo(const Video::Ptr& object) const; + + VideoNote::Ptr parseJsonAndGetVideoNote(const boost::property_tree::ptree& data) const; + std::string parseVideoNote(const VideoNote::Ptr& object) const; + + Game::Ptr parseJsonAndGetGame(const boost::property_tree::ptree& data) const; + std::string parseGame(const Game::Ptr& object) const; + + GameHighScore::Ptr parseJsonAndGetGameHighScore(const boost::property_tree::ptree& data) const; + std::string parseGameHighScore(const GameHighScore::Ptr& object) const; + + Animation::Ptr parseJsonAndGetAnimation(const boost::property_tree::ptree& data) const; + std::string parseAnimation(const Animation::Ptr& object) const; + + Contact::Ptr parseJsonAndGetContact(const boost::property_tree::ptree& data) const; + std::string parseContact(const Contact::Ptr& object) const; + + Location::Ptr parseJsonAndGetLocation(const boost::property_tree::ptree& data) const; + std::string parseLocation(const Location::Ptr& object) const; + + Update::Ptr parseJsonAndGetUpdate(const boost::property_tree::ptree& data) const; + std::string parseUpdate(const Update::Ptr& object) const; + + UserProfilePhotos::Ptr parseJsonAndGetUserProfilePhotos(const boost::property_tree::ptree& data) const; + std::string parseUserProfilePhotos(const UserProfilePhotos::Ptr& object) const; + + InputMedia::Ptr parseJsonAndGetInputMedia(const boost::property_tree::ptree& data) const; + std::string parseInputMedia(const InputMedia::Ptr& object) const; + + File::Ptr parseJsonAndGetFile(const boost::property_tree::ptree& data) const; + std::string parseFile(const File::Ptr& object) const; + + ReplyKeyboardMarkup::Ptr parseJsonAndGetReplyKeyboardMarkup(const boost::property_tree::ptree& data) const; + std::string parseReplyKeyboardMarkup(const ReplyKeyboardMarkup::Ptr& object) const; + + KeyboardButton::Ptr parseJsonAndGetKeyboardButton(const boost::property_tree::ptree& data) const; + std::string parseKeyboardButton(const KeyboardButton::Ptr& object) const; + + ReplyKeyboardRemove::Ptr parseJsonAndGetReplyKeyboardRemove(const boost::property_tree::ptree& data) const; + std::string parseReplyKeyboardRemove(const ReplyKeyboardRemove::Ptr& object) const; + + ForceReply::Ptr parseJsonAndGetForceReply(const boost::property_tree::ptree& data) const; + std::string parseForceReply(const ForceReply::Ptr& object) const; + + ChatMember::Ptr parseJsonAndGetChatMember(const boost::property_tree::ptree& data) const; + std::string parseChatMember(const ChatMember::Ptr& object) const; + + ChatPhoto::Ptr parseJsonAndGetChatPhoto(const boost::property_tree::ptree& data) const; + std::string parseChatPhoto(const ChatPhoto::Ptr& object) const; + + ResponseParameters::Ptr parseJsonAndGetResponseParameters(const boost::property_tree::ptree& data) const; + std::string parseResponseParameters(const ResponseParameters::Ptr& object) const; + + GenericReply::Ptr parseJsonAndGetGenericReply(const boost::property_tree::ptree& data) const; + std::string parseGenericReply(const GenericReply::Ptr& object) const; + + InlineQuery::Ptr parseJsonAndGetInlineQuery(const boost::property_tree::ptree& data) const; + std::string parseInlineQuery(const InlineQuery::Ptr& object) const; + + InlineQueryResult::Ptr parseJsonAndGetInlineQueryResult(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResult(const InlineQueryResult::Ptr& object) const; + + InlineQueryResultCachedAudio::Ptr parseJsonAndGetInlineQueryResultCachedAudio(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedAudio(const InlineQueryResultCachedAudio::Ptr& object) const; + + InlineQueryResultCachedDocument::Ptr parseJsonAndGetInlineQueryResultCachedDocument(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedDocument(const InlineQueryResultCachedDocument::Ptr& object) const; + + InlineQueryResultCachedGif::Ptr parseJsonAndGetInlineQueryResultCachedGif(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedGif(const InlineQueryResultCachedGif::Ptr& object) const; + + InlineQueryResultCachedMpeg4Gif::Ptr parseJsonAndGetInlineQueryResultCachedMpeg4Gif(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedMpeg4Gif(const InlineQueryResultCachedMpeg4Gif::Ptr& object) const; + + InlineQueryResultCachedPhoto::Ptr parseJsonAndGetInlineQueryResultCachedPhoto(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedPhoto(const InlineQueryResultCachedPhoto::Ptr& object) const; + + InlineQueryResultCachedSticker::Ptr parseJsonAndGetInlineQueryResultCachedSticker(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedSticker(const InlineQueryResultCachedSticker::Ptr& object) const; + + InlineQueryResultCachedVideo::Ptr parseJsonAndGetInlineQueryResultCachedVideo(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedVideo(const InlineQueryResultCachedVideo::Ptr& object) const; + + InlineQueryResultCachedVoice::Ptr parseJsonAndGetInlineQueryResultCachedVoice(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultCachedVoice(const InlineQueryResultCachedVoice::Ptr& object) const; + + InlineQueryResultArticle::Ptr parseJsonAndGetInlineQueryResultArticle(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultArticle(const InlineQueryResultArticle::Ptr& object) const; + + InlineQueryResultAudio::Ptr parseJsonAndGetInlineQueryResultAudio(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultAudio(const InlineQueryResultAudio::Ptr& object) const; + + InlineQueryResultContact::Ptr parseJsonAndGetInlineQueryResultContact(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultContact(const InlineQueryResultContact::Ptr& object) const; + + InlineQueryResultGame::Ptr parseJsonAndGetInlineQueryResultGame(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultGame(const InlineQueryResultGame::Ptr& object) const; + + InlineQueryResultDocument::Ptr parseJsonAndGetInlineQueryResultDocument(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultDocument(const InlineQueryResultDocument::Ptr& object) const; + + InlineQueryResultLocation::Ptr parseJsonAndGetInlineQueryResultLocation(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultLocation(const InlineQueryResultLocation::Ptr& object) const; + + InlineQueryResultVenue::Ptr parseJsonAndGetInlineQueryResultVenue(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultVenue(const InlineQueryResultVenue::Ptr& object) const; + + InlineQueryResultVoice::Ptr parseJsonAndGetInlineQueryResultVoice(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultVoice(const InlineQueryResultVoice::Ptr& object) const; + + InlineQueryResultPhoto::Ptr parseJsonAndGetInlineQueryResultPhoto(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultPhoto(const InlineQueryResultPhoto::Ptr& object) const; + + InlineQueryResultGif::Ptr parseJsonAndGetInlineQueryResultGif(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultGif(const InlineQueryResultGif::Ptr& object) const; + + InlineQueryResultMpeg4Gif::Ptr parseJsonAndGetInlineQueryResultMpeg4Gif(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultMpeg4Gif(const InlineQueryResultMpeg4Gif::Ptr& object) const; + + InlineQueryResultVideo::Ptr parseJsonAndGetInlineQueryResultVideo(const boost::property_tree::ptree& data) const; + std::string parseInlineQueryResultVideo(const InlineQueryResultVideo::Ptr& object) const; + + ChosenInlineResult::Ptr parseJsonAndGetChosenInlineResult(const boost::property_tree::ptree& data) const; + std::string parseChosenInlineResult(const ChosenInlineResult::Ptr& object) const; + + CallbackQuery::Ptr parseJsonAndGetCallbackQuery(const boost::property_tree::ptree& data) const; + std::string parseCallbackQuery(const CallbackQuery::Ptr& object) const; + + InlineKeyboardMarkup::Ptr parseJsonAndGetInlineKeyboardMarkup(const boost::property_tree::ptree& data) const; + std::string parseInlineKeyboardMarkup(const InlineKeyboardMarkup::Ptr& object) const; + + InlineKeyboardButton::Ptr parseJsonAndGetInlineKeyboardButton(const boost::property_tree::ptree& data) const; + std::string parseInlineKeyboardButton(const InlineKeyboardButton::Ptr& object) const; + + WebhookInfo::Ptr parseJsonAndGetWebhookInfo(const boost::property_tree::ptree& data) const; + std::string parseWebhookInfo(const WebhookInfo::Ptr& object) const; + + InputMessageContent::Ptr parseJsonAndGetInputMessageContent(const boost::property_tree::ptree& data) const; + std::string parseInputMessageContent(const InputMessageContent::Ptr& object) const; + + InputTextMessageContent::Ptr parseJsonAndGetInputTextMessageContent(const boost::property_tree::ptree& data) const; + std::string parseInputTextMessageContent(const InputTextMessageContent::Ptr& object) const; + + InputLocationMessageContent::Ptr parseJsonAndGetInputLocationMessageContent(const boost::property_tree::ptree& data) const; + std::string parseInputLocationMessageContent(const InputLocationMessageContent::Ptr& object) const; + + InputVenueMessageContent::Ptr parseJsonAndGetInputVenueMessageContent(const boost::property_tree::ptree& data) const; + std::string parseInputVenueMessageContent(const InputVenueMessageContent::Ptr& object) const; + + InputContactMessageContent::Ptr parseJsonAndGetInputContactMessageContent(const boost::property_tree::ptree& data) const; + std::string parseInputContactMessageContent(const InputContactMessageContent::Ptr& object) const; + + Invoice::Ptr parseJsonAndGetInvoice(const boost::property_tree::ptree& data) const; + std::string parseInvoice(const Invoice::Ptr& object) const; + + LabeledPrice::Ptr parseJsonAndGetLabeledPrice(const boost::property_tree::ptree& data) const; + std::string parseLabeledPrice(const LabeledPrice::Ptr& object) const; + + OrderInfo::Ptr parseJsonAndGetOrderInfo(const boost::property_tree::ptree& data) const; + std::string parseOrderInfo(const OrderInfo::Ptr& object) const; + + PreCheckoutQuery::Ptr parseJsonAndGetPreCheckoutQuery(const boost::property_tree::ptree& data) const; + std::string parsePreCheckoutQuery(const PreCheckoutQuery::Ptr& object) const; + + ShippingAddress::Ptr parseJsonAndGetShippingAddress(const boost::property_tree::ptree& data) const; + std::string parseShippingAddress(const ShippingAddress::Ptr& object) const; + + ShippingOption::Ptr parseJsonAndGetShippingOption(const boost::property_tree::ptree& data) const; + std::string parseShippingOption(const ShippingOption::Ptr& object) const; + + ShippingQuery::Ptr parseJsonAndGetShippingQuery(const boost::property_tree::ptree& data) const; + std::string parseShippingQuery(const ShippingQuery::Ptr& object) const; + + SuccessfulPayment::Ptr parseJsonAndGetSuccessfulPayment(const boost::property_tree::ptree& data) const; + std::string parseSuccessfulPayment(const SuccessfulPayment::Ptr& object) const; + + inline boost::property_tree::ptree parseJson(const std::string& json) const { + boost::property_tree::ptree tree; + std::istringstream input(json); + boost::property_tree::read_json(input, tree); + return tree; + } + + template + std::shared_ptr tryParseJson(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { + auto treeItem = data.find(keyName); + if (treeItem == data.not_found()) { + return std::shared_ptr(); + } + return (this->*parseFunc)(treeItem->second); + } + + template + std::vector> parseJsonAndGetArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data) const { + std::vector> result; + result.reserve(data.size()); + for (const std::pair& innerTreeItem : data) { + result.push_back((this->*parseFunc)(innerTreeItem.second)); + } + return result; + } + + template + std::vector parseJsonAndGetArray(std::function parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { + std::vector result; + auto treeItem = data.find(keyName); + if (treeItem == data.not_found()) { + return result; + } + result.reserve(treeItem->second.size()); + for (const std::pair& innerTreeItem : treeItem->second) { + result.push_back(parseFunc(innerTreeItem.second)); + } + return result; + } + + template + std::vector> parseJsonAndGetArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { + std::vector> result; + auto treeItem = data.find(keyName); + if (treeItem == data.not_found()) { + return result; + } + result.reserve(treeItem->second.size()); + for (const std::pair& innerTreeItem : treeItem->second) { + result.push_back((this->*parseFunc)(innerTreeItem.second)); + } + return result; + } + + template + std::vector>> parseJsonAndGet2DArray(JsonToTgTypeFunc parseFunc, const boost::property_tree::ptree& data, const std::string& keyName) const { + std::vector>> result; + auto treeItem = data.find(keyName); + if (treeItem == data.not_found()) { + return result; + } + result.reserve(treeItem->second.size()); + for (const std::pair& innerTreeItem : treeItem->second) { + std::vector> innerResult; + for (const std::pair& innerInnerTreeItem : innerTreeItem.second) { + innerResult.push_back((this->*parseFunc)(innerInnerTreeItem.second)); + } + result.push_back(innerResult); + } + return result; + } + + template + std::string parseArray(TgTypeToJsonFunc parseFunc, const std::vector>& objects) const { + if (objects.empty()) + return ""; + std::string result; + result += '['; + for (const std::shared_ptr& item : objects) { + result += (this->*parseFunc)(item); + result += ','; + } + result.erase(result.length() - 1); + result += ']'; + return result; + } + + template + std::string parseArray(std::function parseFunc, const std::vector& objects) const { + if (objects.empty()) + return ""; + std::string result; + result += '['; + for (const T& item : objects) { + result += parseFunc(item); + result += ','; + } + result.erase(result.length() - 1); + result += ']'; + return result; + } + + template + std::string parse2DArray(TgTypeToJsonFunc parseFunc, const std::vector>>& objects) const { + if (objects.empty()) + return ""; + std::string result; + result += '['; + for (const std::vector>& item : objects) { + result += parseArray(parseFunc, item); + result += ','; + } + result.erase(result.length() - 1); + result += ']'; + return result; + } private: - inline void removeLastComma(std::string& input) const { - input.erase(input.length() - 1); - } - - template - inline void appendToJson(std::string& json, const std::string& varName, const std::shared_ptr& value) const { - if (value == nullptr) { - return; - } - json += '"'; - json += varName; - json += R"(":)"; - json += value; - json += ','; - } - - template - inline void appendToJson(std::string& json, const std::string& varName, const T& value) const { - json += '"'; - json += varName; - json += R"(":)"; - json += value; - json += ','; - } - - inline void appendToJson(std::string& json, const std::string& varName, const bool& value) const { - json += '"'; - json += varName; - json += R"(":)"; - json += (value ? "true" : "false"); - json += ','; - } - - void appendToJson(std::string& json, const std::string& varName, const std::string& value) const; + inline void removeLastComma(std::string& input) const { + input.erase(input.length() - 1); + } + + template + inline void appendToJson(std::string& json, const std::string& varName, const std::shared_ptr& value) const { + if (value == nullptr) { + return; + } + json += '"'; + json += varName; + json += R"(":)"; + json += value; + json += ','; + } + + template + inline void appendToJson(std::string& json, const std::string& varName, const T& value) const { + json += '"'; + json += varName; + json += R"(":)"; + json += value; + json += ','; + } + + inline void appendToJson(std::string& json, const std::string& varName, const bool& value) const { + json += '"'; + json += varName; + json += R"(":)"; + json += (value ? "true" : "false"); + json += ','; + } + + void appendToJson(std::string& json, const std::string& varName, const std::string& value) const; }; } diff --git a/include/tgbot/net/BoostHttpOnlySslClient.h b/include/tgbot/net/BoostHttpOnlySslClient.h new file mode 100644 index 0000000..615abdc --- /dev/null +++ b/include/tgbot/net/BoostHttpOnlySslClient.h @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2015 Oleg Morozenkov + * Copyright (c) 2018 JellyBrick + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef TGBOT_BOOSTHTTPCLIENT_H +#define TGBOT_BOOSTHTTPCLIENT_H + +#include + +#include + +#include "tgbot/net/HttpClient.h" +#include "tgbot/net/Url.h" +#include "tgbot/net/HttpReqArg.h" +#include "tgbot/net/HttpParser.h" + +namespace TgBot { + +/** + * @brief This class makes http requests via boost::asio. + * + * @ingroup net + */ +class BoostHttpOnlySslClient : public HttpClient { + +public: + BoostHttpOnlySslClient(); + ~BoostHttpOnlySslClient() override; + + /** + * @brief Sends a request to the url. + * + * If there's no args specified, a GET request will be sent, otherwise a POST request will be sent. + * If at least 1 arg is marked as file, the content type of a request will be multipart/form-data, otherwise it will be application/x-www-form-urlencoded. + */ + std::string makeRequest(const Url& url, const std::vector& args) const override; + +private: + mutable boost::asio::io_service _ioService; + const HttpParser _httpParser; +}; + +} + +#endif //TGBOT_BOOSTHTTPCLIENT_H diff --git a/include/tgbot/net/CurlHttpClient.h b/include/tgbot/net/CurlHttpClient.h new file mode 100644 index 0000000..b0ff6c3 --- /dev/null +++ b/include/tgbot/net/CurlHttpClient.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2018 Egor Pugin + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef TGBOT_CURLHTTPCLIENT_H +#define TGBOT_CURLHTTPCLIENT_H + +#ifdef HAVE_CURL + +#include + +#include + +#include "tgbot/net/HttpClient.h" +#include "tgbot/net/Url.h" +#include "tgbot/net/HttpReqArg.h" +#include "tgbot/net/HttpParser.h" + +namespace TgBot { + +/** + * @brief This class makes http requests via libcurl. + * + * @ingroup net + */ +class CurlHttpClient : public HttpClient { + +public: + CurlHttpClient(); + ~CurlHttpClient() override; + + /** + * @brief Sends a request to the url. + * + * If there's no args specified, a GET request will be sent, otherwise a POST request will be sent. + * If at least 1 arg is marked as file, the content type of a request will be multipart/form-data, otherwise it will be application/x-www-form-urlencoded. + */ + std::string makeRequest(const Url& url, const std::vector& args) const override; + + /** + * @brief Raw curl settings storage for fine tuning. + */ + CURL* curlSettings; + +private: + const HttpParser _httpParser; +}; + +} + +#endif + +#endif //TGBOT_CURLHTTPCLIENT_H diff --git a/include/tgbot/net/HttpClient.h b/include/tgbot/net/HttpClient.h index 4378623..62b1875 100644 --- a/include/tgbot/net/HttpClient.h +++ b/include/tgbot/net/HttpClient.h @@ -1,4 +1,4 @@ -/* + /* * Copyright (c) 2015 Oleg Morozenkov * Copyright (c) 2018 Egor Pugin * @@ -26,14 +26,8 @@ #include -#include -#ifdef HAVE_CURL -#include -#endif - #include "tgbot/net/Url.h" #include "tgbot/net/HttpReqArg.h" -#include "tgbot/net/HttpParser.h" namespace TgBot { @@ -56,66 +50,7 @@ public: virtual std::string makeRequest(const Url& url, const std::vector& args) const = 0; }; -/** - * @brief This class makes http requests via boost::asio. - * - * @ingroup net - */ -class BoostHttpClient : public HttpClient { - -public: - /** - * @brief Returns instance which lives during all application lifetime. - */ - static BoostHttpClient& getInstance(); - - /** - * @brief Sends a request to the url. - * - * If there's no args specified, a GET request will be sent, otherwise a POST request will be sent. - * If at least 1 arg is marked as file, the content type of a request will be multipart/form-data, otherwise it will be application/x-www-form-urlencoded. - */ - std::string makeRequest(const Url& url, const std::vector& args) const override; - -private: - mutable boost::asio::io_service _ioService; -}; - -#ifdef HAVE_CURL - -/** - * @brief This class makes http requests via libcurl. - * - * @ingroup net - */ -class CurlHttpClient : public HttpClient { - -public: - - /** - * @brief Raw curl settings storage for fine tuning. - */ - CURL* curlSettings; - - CurlHttpClient(); - ~CurlHttpClient(); - - /** - * @brief Returns instance which lives during all application lifetime. - */ - static CurlHttpClient& getInstance(); - - /** - * @brief Sends a request to the url. - * - * If there's no args specified, a GET request will be sent, otherwise a POST request will be sent. - * If at least 1 arg is marked as file, the content type of a request will be multipart/form-data, otherwise it will be application/x-www-form-urlencoded. - */ - std::string makeRequest(const Url& url, const std::vector& args) const override; -}; - -#endif - } + #endif //TGBOT_HTTPCLIENT_H diff --git a/include/tgbot/net/HttpParser.h b/include/tgbot/net/HttpParser.h index d40619a..d4900a1 100644 --- a/include/tgbot/net/HttpParser.h +++ b/include/tgbot/net/HttpParser.h @@ -35,33 +35,13 @@ namespace TgBot { class HttpParser { public: - static HttpParser& getInstance(); - - std::string generateRequest(const Url& url, const std::vector& args, bool isKeepAlive = false); - std::string generateMultipartFormData(const std::vector& args, const std::string& bondary); - std::string generateMultipartBoundary(const std::vector& args); - std::string generateWwwFormUrlencoded(const std::vector& args); - std::string generateResponse(const std::string& data, const std::string& mimeType = "text/plain", short unsigned statusCode = 200, const std::string& statusStr = "OK", bool isKeepAlive = false); - - inline std::string parseRequest(const std::string& data, std::unordered_map& headers) { - return parseHttp(true, data, headers); - } - - inline std::string parseRequest(const std::string& data) { - return parseHttp(true, data); - } - - inline std::string parseResponse(const std::string& data, std::unordered_map& headers) { - return parseHttp(false, data, headers); - } - - inline std::string parseResponse(const std::string& data) { - return parseHttp(false, data); - } - -private: - std::string parseHttp(bool isRequest, const std::string& data, std::unordered_map& headers); - std::string parseHttp(bool isRequest, const std::string& data); + std::string generateRequest(const Url& url, const std::vector& args, bool isKeepAlive = false) const; + std::string generateMultipartFormData(const std::vector& args, const std::string& bondary) const; + std::string generateMultipartBoundary(const std::vector& args) const; + std::string generateWwwFormUrlencoded(const std::vector& args) const; + std::string generateResponse(const std::string& data, const std::string& mimeType, unsigned short statusCode, const std::string& statusStr, bool isKeepAlive) const; + std::unordered_map parseHeader(const std::string& data, bool isRequest) const; + std::string extractBody(const std::string& data) const; }; } diff --git a/include/tgbot/net/HttpReqArg.h b/include/tgbot/net/HttpReqArg.h index 7476366..a263224 100644 --- a/include/tgbot/net/HttpReqArg.h +++ b/include/tgbot/net/HttpReqArg.h @@ -24,6 +24,7 @@ #define TGBOT_HTTPPARAMETER_H #include +#include #include #include @@ -39,36 +40,36 @@ namespace TgBot { class HttpReqArg { public: - template - HttpReqArg(const std::string& name, const T& value, bool isFile = false, const std::string& mimeType = "text/plain", const std::string& fileName = "") : - name(name), value(boost::lexical_cast(value)), isFile(isFile), mimeType(mimeType), fileName(fileName) - { - } + template + HttpReqArg(std::string name, const T& value, bool isFile = false, std::string mimeType = "text/plain", std::string fileName = "") : + name(std::move(name)), value(boost::lexical_cast(value)), isFile(isFile), mimeType(std::move(mimeType)), fileName(std::move(fileName)) + { + } - /** - * @brief Name of an argument. - */ - std::string name; + /** + * @brief Name of an argument. + */ + std::string name; - /** - * @brief Value of an argument. - */ - std::string value; + /** + * @brief Value of an argument. + */ + std::string value; - /** - * @brief Should be true if an argument value hold some file contents - */ - bool isFile = false; + /** + * @brief Should be true if an argument value hold some file contents + */ + bool isFile = false; - /** - * @brief Mime type of an argument value. This field makes sense only if isFile is true. - */ - std::string mimeType = "text/plain"; + /** + * @brief Mime type of an argument value. This field makes sense only if isFile is true. + */ + std::string mimeType = "text/plain"; - /** - * @brief Should be set if an argument value hold some file contents - */ - std::string fileName; + /** + * @brief Should be set if an argument value hold some file contents + */ + std::string fileName; }; } diff --git a/include/tgbot/net/HttpServer.h b/include/tgbot/net/HttpServer.h index 34cd9c7..a1c5a49 100644 --- a/include/tgbot/net/HttpServer.h +++ b/include/tgbot/net/HttpServer.h @@ -23,7 +23,9 @@ #ifndef TGBOT_HTTPSERVER_H #define TGBOT_HTTPSERVER_H +#include #include +#include #include @@ -40,62 +42,146 @@ template class HttpServer { protected: - class Connection; + class Connection; public: - typedef std::function)> ServerHandler; - - HttpServer(std::shared_ptr> acceptor, const ServerHandler& handler) : _acceptor(acceptor), _handler(handler) { - } - - /** - * @brief Starts receiving new connections. - */ - void start() { - auto socket(std::make_shared>(_acceptor->get_io_service())); - auto connection(std::make_shared(socket, _handler)); - _acceptor->async_accept(*connection->socket, [this, connection]() { - connection->start(); - start(); - }); - _ioService.run(); - } - - /** - * @brief Stops receiving new connections. - */ - void stop() { - _ioService.stop(); - } + typedef std::function&)> ServerHandler; + + HttpServer(const typename boost::asio::basic_socket_acceptor::endpoint_type& endpoint, ServerHandler handler) + : _ioService(), _acceptor(_ioService, endpoint), _socket(_ioService), _handler(std::move(handler)), _httpParser() + { + } + + /** + * @brief Starts receiving new connections. + */ + void start() { + _startAccept(); + _ioService.run(); + } + + /** + * @brief Stops receiving new connections. + */ + void stop() { + _ioService.stop(); + } protected: - class Connection { - - public: - Connection(std::shared_ptr>& socket, const ServerHandler& handler) : socket(socket), _handler(handler) { - boost::asio::socket_base::keep_alive option(true); - socket.set_option(option); - } - - void start() { - data.reserve(10240); - socket->async_receive(data, [this]() { - std::unordered_map headers; - std::string body = HttpParser::getInstance().parseResponse(data, headers); - socket->async_send(_handler(body, headers)); - }); - } - - std::shared_ptr> socket; - std::string data; - - protected: - const ServerHandler _handler; - }; - - boost::asio::io_service _ioService; - std::shared_ptr> _acceptor; - const ServerHandler _handler; + class Connection : public std::enable_shared_from_this { + + public: + Connection(boost::asio::basic_stream_socket socket, ServerHandler handler, const HttpParser& httpParser) + : _socket(std::move(socket)), _handler(std::move(handler)), _httpParser(httpParser) + { + } + + void start() { + _readHeader(); + } + + protected: + boost::asio::basic_stream_socket _socket; + const ServerHandler _handler; + const HttpParser& _httpParser; + + void _readHeader() { + auto self(this->shared_from_this()); + + auto data(std::make_shared()); + data->prepare(1024); + + boost::asio::async_read_until( + _socket, + *data, + "\r\n\r\n", + [self, data](const boost::system::error_code& e, size_t n) { + if (e) { + std::cout << "error in HttpServer::Connection#_readHeader: " << e << std::endl; + return; + } + + boost::asio::streambuf::const_buffers_type bufs = data->data(); + std::string dataAsString(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + n); + + auto headers(std::make_shared>(self->_httpParser.parseHeader(dataAsString, true))); + + unsigned long long size; + auto contentLengthIter = headers->find("Content-Length"); + if (contentLengthIter != headers->end()) { + size = std::stoull(contentLengthIter->second); + } else { + size = 0; + } + + if (size == 0) { + std::string answer = self->_httpParser.generateResponse("Bad request", "text/plain", 400, "Bad request", false); + boost::asio::async_write( + self->_socket, + boost::asio::buffer(answer), + [](const boost::system::error_code& e, size_t n) { }); + return; + } + + data->consume(n); + self->_readBody(data, size, headers); + }); + } + + void _readBody(std::shared_ptr data, unsigned long long size, std::shared_ptr> headers) { + auto self(this->shared_from_this()); + + data->prepare(size); + + boost::asio::async_read(_socket, + *data, + boost::asio::transfer_exactly(size - data->size()), + [self, data, size, headers](const boost::system::error_code& e, size_t n) { + if (e) { + std::cout << "error in HttpServer::Connection#_readBody: " << e << std::endl; + return; + } + + boost::asio::streambuf::const_buffers_type bufs = data->data(); + std::string dataAsString(boost::asio::buffers_begin(bufs), boost::asio::buffers_begin(bufs) + size); + + std::string answer; + try { + answer = self->_handler(dataAsString, *headers); + } catch (std::exception& e) { + std::cout << "error in HttpServer::Connection#_readBody answer: " << e.what() << std::endl; + answer = self->_httpParser.generateResponse("Internal server error", "text/plain", 500, "Internal server error", false); + } + boost::asio::async_write( + self->_socket, + boost::asio::buffer(answer), + [](const boost::system::error_code& e, size_t n) { }); + + self->_socket.close(); + }); + } + }; + + void _startAccept() { + _acceptor.async_accept(_socket, [this](const boost::system::error_code& e) { + if (e) { + std::cout << "error in HttpServer: " << e << std::endl; + _startAccept(); + return; + } + + auto connection(std::make_shared(std::move(_socket), _handler, _httpParser)); + connection->start(); + + _startAccept(); + }); + } + + boost::asio::io_service _ioService; + boost::asio::basic_socket_acceptor _acceptor; + boost::asio::basic_stream_socket _socket; + const ServerHandler _handler; + const HttpParser _httpParser; }; } diff --git a/include/tgbot/net/TgLongPoll.h b/include/tgbot/net/TgLongPoll.h index a0281f1..643031e 100644 --- a/include/tgbot/net/TgLongPoll.h +++ b/include/tgbot/net/TgLongPoll.h @@ -37,21 +37,21 @@ namespace TgBot { class TgLongPoll { public: - TgLongPoll(const Api* api, const EventHandler* eventHandler, int32_t, int32_t, const std::shared_ptr>&); - TgLongPoll(const Bot& bot, int32_t = 100, int32_t = 60, const std::shared_ptr>& = nullptr); + TgLongPoll(const Api* api, const EventHandler* eventHandler, int32_t, int32_t, const std::shared_ptr>&); + TgLongPoll(const Bot& bot, int32_t = 100, int32_t = 60, const std::shared_ptr>& = nullptr); - /** - * @brief Starts long poll. After new update will come, this method will parse it and send to EventHandler which invokes your listeners. Designed to be executed in a loop. - */ - void start(); + /** + * @brief Starts long poll. After new update will come, this method will parse it and send to EventHandler which invokes your listeners. Designed to be executed in a loop. + */ + void start(); private: - const Api* _api; - const EventHandler* _eventHandler; - int32_t _lastUpdateId = 0; - int32_t _limit; - int32_t _timeout; - std::shared_ptr> _allowupdates; + const Api* _api; + const EventHandler* _eventHandler; + int32_t _lastUpdateId = 0; + int32_t _limit; + int32_t _timeout; + std::shared_ptr> _allowupdates; }; } diff --git a/include/tgbot/net/TgWebhookLocalServer.h b/include/tgbot/net/TgWebhookLocalServer.h index 685979d..d7cb06e 100644 --- a/include/tgbot/net/TgWebhookLocalServer.h +++ b/include/tgbot/net/TgWebhookLocalServer.h @@ -20,8 +20,8 @@ * SOFTWARE. */ -#ifndef TGBOT_TGWEBHOOKTCPSERVER_H -#define TGBOT_TGWEBHOOKTCPSERVER_H +#ifndef TGBOT_TGWEBHOOKLOCALSERVER_H +#define TGBOT_TGWEBHOOKLOCALSERVER_H #ifdef BOOST_ASIO_HAS_LOCAL_SOCKETS @@ -37,19 +37,21 @@ namespace TgBot { class TgWebhookLocalServer : public TgWebhookServer { public: - TgWebhookLocalServer(std::shared_ptr>& acceptor, const std::string& path, EventHandler* eventHandler) = delete; - - TgWebhookLocalServer(const std::string& path, const EventHandler* eventHandler) : - TgWebhookServer(std::make_shared>(_ioService, boost::asio::local::stream_protocol::endpoint(path)), path, eventHandler) - { - } - - TgWebhookLocalServer(const std::string& path, const Bot& bot) : TgWebhookLocalServer(path, &bot.getEventHandler()) { - } + TgWebhookLocalServer(const std::string& unixSocketPath, const std::string& path, const EventHandler& eventHandler) + : TgWebhookServer(boost::asio::local::stream_protocol::endpoint(unixSocketPath), + path, eventHandler) + { + } + + TgWebhookLocalServer(const std::string& unixSocketPath, const Bot& bot) + : TgWebhookServer(boost::asio::local::stream_protocol::endpoint(unixSocketPath), + bot) + { + } }; } #endif //BOOST_ASIO_HAS_LOCAL_SOCKETS -#endif //TGBOT_TGWEBHOOKTCPSERVER_H +#endif //TGBOT_TGWEBHOOKLOCALSERVER_H diff --git a/include/tgbot/net/TgWebhookServer.h b/include/tgbot/net/TgWebhookServer.h index 696d126..953c1a9 100644 --- a/include/tgbot/net/TgWebhookServer.h +++ b/include/tgbot/net/TgWebhookServer.h @@ -23,6 +23,8 @@ #ifndef TGBOT_TGHTTPSERVER_H #define TGBOT_TGHTTPSERVER_H +#include + #include "tgbot/Bot.h" #include "tgbot/EventHandler.h" #include "tgbot/TgTypeParser.h" @@ -34,22 +36,31 @@ template class TgWebhookServer : public HttpServer { public: - TgWebhookServer(std::shared_ptr> acceptor, const typename HttpServer::ServerHandler& handler) = delete; - - TgWebhookServer(std::shared_ptr> acceptor, const std::string& path, const EventHandler* eventHandler) : - HttpServer(acceptor, [eventHandler, &path](const std::string& data, const std::unordered_map& headers) -> std::string { - if (headers.at("method") == "POST" && headers.at("path") == path) { - eventHandler->handleUpdate(TgTypeParser::getInstance().parseJsonAndGetUpdate(TgTypeParser::getInstance().parseJson(data))); - } - return HttpParser::getInstance().generateResponse(""); - }) - { - } - - TgWebhookServer(std::shared_ptr> acceptor, const std::string& path, const Bot& bot) : - TgWebhookServer(acceptor, path, &bot.getEventHandler()) - { - } + TgWebhookServer(const typename boost::asio::basic_socket_acceptor::endpoint_type& endpoint, const typename HttpServer::ServerHandler& handler) = delete; + + TgWebhookServer(const typename boost::asio::basic_socket_acceptor::endpoint_type& endpoint, std::string path, const EventHandler& eventHandler) + : HttpServer(endpoint, + [this](const std::string& _1, const std::unordered_map& _2) { return _handle(_1, _2); }), + _path(std::move(path)), _eventHandler(eventHandler), _tgTypeParser() + { + } + + TgWebhookServer(const typename boost::asio::basic_socket_acceptor::endpoint_type& endpoint, const Bot& bot) + : TgWebhookServer(endpoint, "/" + bot.getToken(), bot.getEventHandler()) + { + } + +private: + std::string _handle(const std::string& data, const std::unordered_map& headers) { + if (headers.at("_method") == "POST" && headers.at("_path") == _path) { + _eventHandler.handleUpdate(_tgTypeParser.parseJsonAndGetUpdate(_tgTypeParser.parseJson(data))); + } + return HttpServer::_httpParser.generateResponse("", "text/plain", 200, "OK", false); + } + + const EventHandler& _eventHandler; + const std::string _path; + const TgTypeParser _tgTypeParser; }; } diff --git a/include/tgbot/net/TgWebhookTcpServer.h b/include/tgbot/net/TgWebhookTcpServer.h index de1f3e7..ad5a5b8 100644 --- a/include/tgbot/net/TgWebhookTcpServer.h +++ b/include/tgbot/net/TgWebhookTcpServer.h @@ -34,15 +34,17 @@ namespace TgBot { class TgWebhookTcpServer : public TgWebhookServer { public: - TgWebhookTcpServer(std::shared_ptr> acceptor, const std::string& path, EventHandler* eventHandler) = delete; - - TgWebhookTcpServer(unsigned short port, const std::string& path, const EventHandler* eventHandler) : - TgWebhookServer(std::shared_ptr>(new boost::asio::ip::tcp::acceptor(_ioService, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port))), path, eventHandler) - { - } - - TgWebhookTcpServer(const std::string& path, const Bot& bot) : TgWebhookTcpServer(path, &bot.getEventHandler()) { - } + TgWebhookTcpServer(unsigned short port, const std::string& path, const EventHandler& eventHandler) + : TgWebhookServer(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port), + path, eventHandler) + { + } + + TgWebhookTcpServer(unsigned short port, const Bot& bot) + : TgWebhookServer(boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port), + bot) + { + } }; } diff --git a/include/tgbot/net/Url.h b/include/tgbot/net/Url.h index c039355..f9226e5 100644 --- a/include/tgbot/net/Url.h +++ b/include/tgbot/net/Url.h @@ -35,32 +35,32 @@ namespace TgBot { class Url { public: - Url(const std::string& url); + Url(const std::string& url); - /** - * @brief Protocol part of an url. Example: https:// - */ - std::string protocol; + /** + * @brief Protocol part of an url. Example: https:// + */ + std::string protocol; - /** - * @brief Host part of an url. Example: www.example.com - */ - std::string host; + /** + * @brief Host part of an url. Example: www.example.com + */ + std::string host; - /** - * @brief Path part of an url including preceding '/' char. Example: /index.html - */ - std::string path; + /** + * @brief Path part of an url including preceding '/' char. Example: /index.html + */ + std::string path; - /** - * @brief Query part of an url without '?' char. Example: a=1&b=2&c=3 - */ - std::string query; + /** + * @brief Query part of an url without '?' char. Example: a=1&b=2&c=3 + */ + std::string query; - /** - * @brief Fragment part of an url without '#' char. Example: section1 - */ - std::string fragment; + /** + * @brief Fragment part of an url without '#' char. Example: section1 + */ + std::string fragment; }; } diff --git a/include/tgbot/tgbot.h b/include/tgbot/tgbot.h index 687783b..0e43f18 100644 --- a/include/tgbot/tgbot.h +++ b/include/tgbot/tgbot.h @@ -23,48 +23,101 @@ #ifndef TGBOT_TGBOT_H #define TGBOT_TGBOT_H -#include "tgbot/Bot.h" #include "tgbot/Api.h" -#include "tgbot/TgException.h" -#include "tgbot/TgTypeParser.h" +#include "tgbot/Bot.h" #include "tgbot/EventBroadcaster.h" #include "tgbot/EventHandler.h" +#include "tgbot/TgException.h" +#include "tgbot/TgTypeParser.h" +#include "tgbot/net/BoostHttpOnlySslClient.h" +#include "tgbot/net/CurlHttpClient.h" +#include "tgbot/net/HttpClient.h" +#include "tgbot/net/HttpParser.h" +#include "tgbot/net/HttpReqArg.h" +#include "tgbot/net/HttpServer.h" +#include "tgbot/net/TgLongPoll.h" +#include "tgbot/net/TgWebhookLocalServer.h" +#include "tgbot/net/TgWebhookServer.h" +#include "tgbot/net/TgWebhookTcpServer.h" +#include "tgbot/net/Url.h" +#include "tgbot/tgbot.h" +#include "tgbot/tools/FileTools.h" +#include "tgbot/tools/StringTools.h" +#include "tgbot/types/Animation.h" #include "tgbot/types/Audio.h" +#include "tgbot/types/CallbackGame.h" +#include "tgbot/types/CallbackQuery.h" +#include "tgbot/types/Chat.h" +#include "tgbot/types/ChatMember.h" +#include "tgbot/types/ChatPhoto.h" +#include "tgbot/types/ChosenInlineResult.h" #include "tgbot/types/Contact.h" #include "tgbot/types/Document.h" +#include "tgbot/types/File.h" #include "tgbot/types/ForceReply.h" +#include "tgbot/types/Game.h" +#include "tgbot/types/GameHighScore.h" #include "tgbot/types/GenericReply.h" +#include "tgbot/types/InlineKeyboardButton.h" +#include "tgbot/types/InlineKeyboardMarkup.h" +#include "tgbot/types/InlineQuery.h" +#include "tgbot/types/InlineQueryResult.h" +#include "tgbot/types/InlineQueryResultArticle.h" +#include "tgbot/types/InlineQueryResultAudio.h" +#include "tgbot/types/InlineQueryResultCachedAudio.h" +#include "tgbot/types/InlineQueryResultCachedDocument.h" +#include "tgbot/types/InlineQueryResultCachedGif.h" +#include "tgbot/types/InlineQueryResultCachedMpeg4Gif.h" +#include "tgbot/types/InlineQueryResultCachedPhoto.h" +#include "tgbot/types/InlineQueryResultCachedSticker.h" +#include "tgbot/types/InlineQueryResultCachedVideo.h" +#include "tgbot/types/InlineQueryResultCachedVoice.h" +#include "tgbot/types/InlineQueryResultContact.h" +#include "tgbot/types/InlineQueryResultDocument.h" +#include "tgbot/types/InlineQueryResultGame.h" +#include "tgbot/types/InlineQueryResultGif.h" +#include "tgbot/types/InlineQueryResultLocation.h" +#include "tgbot/types/InlineQueryResultMpeg4Gif.h" +#include "tgbot/types/InlineQueryResultPhoto.h" +#include "tgbot/types/InlineQueryResultVenue.h" +#include "tgbot/types/InlineQueryResultVideo.h" +#include "tgbot/types/InlineQueryResultVoice.h" +#include "tgbot/types/InputContactMessageContent.h" #include "tgbot/types/InputFile.h" +#include "tgbot/types/InputLocationMessageContent.h" +#include "tgbot/types/InputMedia.h" +#include "tgbot/types/InputMediaPhoto.h" +#include "tgbot/types/InputMediaVideo.h" +#include "tgbot/types/InputMessageContent.h" +#include "tgbot/types/InputTextMessageContent.h" +#include "tgbot/types/InputVenueMessageContent.h" +#include "tgbot/types/Invoice.h" +#include "tgbot/types/KeyboardButton.h" +#include "tgbot/types/LabeledPrice.h" #include "tgbot/types/Location.h" +#include "tgbot/types/MaskPosition.h" #include "tgbot/types/Message.h" +#include "tgbot/types/MessageEntity.h" +#include "tgbot/types/OrderInfo.h" #include "tgbot/types/PhotoSize.h" -#include "tgbot/types/ReplyKeyboardRemove.h" +#include "tgbot/types/PreCheckoutQuery.h" #include "tgbot/types/ReplyKeyboardMarkup.h" +#include "tgbot/types/ReplyKeyboardRemove.h" +#include "tgbot/types/ResponseParameters.h" +#include "tgbot/types/ShippingAddress.h" +#include "tgbot/types/ShippingOption.h" +#include "tgbot/types/ShippingQuery.h" #include "tgbot/types/Sticker.h" +#include "tgbot/types/StickerSet.h" +#include "tgbot/types/SuccessfulPayment.h" #include "tgbot/types/Update.h" #include "tgbot/types/User.h" #include "tgbot/types/UserProfilePhotos.h" +#include "tgbot/types/Venue.h" #include "tgbot/types/Video.h" #include "tgbot/types/VideoNote.h" -#include "tgbot/types/InlineQuery.h" -#include "tgbot/types/InlineQueryResult.h" -#include "tgbot/types/InlineQueryResultArticle.h" -#include "tgbot/types/InlineQueryResultGif.h" -#include "tgbot/types/InlineQueryResultMpeg4Gif.h" -#include "tgbot/types/InlineQueryResultPhoto.h" -#include "tgbot/types/InlineQueryResultVideo.h" -#include "tgbot/types/ChosenInlineResult.h" -#include "tgbot/tools/StringTools.h" -#include "tgbot/tools/FileTools.h" -#include "tgbot/net/HttpClient.h" -#include "tgbot/net/HttpParser.h" -#include "tgbot/net/HttpReqArg.h" -#include "tgbot/net/HttpServer.h" -#include "tgbot/net/TgLongPoll.h" -#include "tgbot/net/TgWebhookLocalServer.h" -#include "tgbot/net/TgWebhookServer.h" -#include "tgbot/net/TgWebhookTcpServer.h" -#include "tgbot/net/Url.h" +#include "tgbot/types/Voice.h" +#include "tgbot/types/WebhookInfo.h" /** * @defgroup general diff --git a/include/tgbot/tools/StringTools.h b/include/tgbot/tools/StringTools.h index 002757a..0f72045 100644 --- a/include/tgbot/tools/StringTools.h +++ b/include/tgbot/tools/StringTools.h @@ -82,9 +82,9 @@ std::string urlDecode(const std::string& value); * @return Array of substrings */ inline std::vector split(const std::string& str, char delimiter) { - std::vector result; - split(str, delimiter, result); - return result; + std::vector result; + split(str, delimiter, result); + return result; } } diff --git a/include/tgbot/types/Animation.h b/include/tgbot/types/Animation.h index ab8dd54..ddd7ca0 100644 --- a/include/tgbot/types/Animation.h +++ b/include/tgbot/types/Animation.h @@ -40,32 +40,32 @@ namespace TgBot { */ class Animation { public: - typedef std::shared_ptr Ptr; + typedef std::shared_ptr Ptr; - /** - * @brief Unique file identifier. - */ - std::string fileId; + /** + * @brief Unique file identifier. + */ + std::string fileId; - /** - * @brief Optional. Animation thumbnail as defined by sender. - */ - PhotoSize::Ptr thumb; + /** + * @brief Optional. Animation thumbnail as defined by sender. + */ + PhotoSize::Ptr thumb; - /** - * @brief Optional. Original animation filename as defined by sender. - */ - std::string fileName; + /** + * @brief Optional. Original animation filename as defined by sender. + */ + std::string fileName; - /** - * @brief Optional. MIME type of the file as defined by sender. - */ - std::string mimeType; + /** + * @brief Optional. MIME type of the file as defined by sender. + */ + std::string mimeType; - /** - * @brief Optional. File size. - */ - int32_t fileSize; + /** + * @brief Optional. File size. + */ + int32_t fileSize; }; } diff --git a/include/tgbot/types/Audio.h b/include/tgbot/types/Audio.h index e640bce..3b8b3e3 100644 --- a/include/tgbot/types/Audio.h +++ b/include/tgbot/types/Audio.h @@ -36,39 +36,39 @@ namespace TgBot { class Audio { public: - typedef std::shared_ptr