### Simple Echo Bot Example in C++ Source: https://github.com/reo7sp/tgbot-cpp/blob/master/README.md A basic C++ example demonstrating how to create an echo bot using the tgbot-cpp library. This bot responds to the '/start' command with a greeting and echoes any other messages it receives. It utilizes long polling to stay updated with incoming messages. ```cpp #include #include int main() { TgBot::Bot bot("PLACE YOUR TOKEN HERE"); bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Hi!"); }); bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { printf("User wrote %s\n", message->text.c_str()); if (StringTools::startsWith(message->text, "/start")) { return; } bot.getApi().sendMessage(message->chat->id, "Your message is: " + message->text); }); try { printf("Bot username: %s\n", bot.getApi().getMe()->username.c_str()); TgBot::TgLongPoll longPoll(bot); while (true) { printf("Long poll started\n"); longPoll.start(); } } catch (TgBot::TgException& e) { printf("error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### CMake Library Building and Installation Source: https://github.com/reo7sp/tgbot-cpp/blob/master/CMakeLists.txt Defines the main library target, sets include directories for both build and install targets, links the necessary libraries, and specifies installation rules for the target, headers, and CMake configuration files. ```cmake # building project add_library(${PROJECT_NAME} ${SRC_LIST}) target_include_directories(${PROJECT_NAME} PUBLIC $ $) target_link_libraries(${PROJECT_NAME} ${LIB_LIST}) include(GNUInstallDirs) install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}-targets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install(EXPORT ${PROJECT_NAME}-targets NAMESPACE ${PROJECT_NAME}:: FILE ${PROJECT_NAME}Config.cmake DESTINATION lib/cmake/${PROJECT_NAME}) set_property(TARGET ${PROJECT_NAME} PROPERTY POSITION_INDEPENDENT_CODE ON) # ABI version set_property(TARGET ${PROJECT_NAME} PROPERTY SOVERSION 1) ``` -------------------------------- ### CMake Project Setup and Dependency Configuration Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot-curl-client/CMakeLists.txt This snippet sets up the CMake build environment for the echobot-curl-client. It defines the project name, C++ standard to 14, enables required flags like -Wall, and finds necessary libraries such as Threads, OpenSSL, Boost, and CURL. It also includes conditional logic for CURL. ```cmake cmake_minimum_required(VERSION 3.10.2) project(echobot-curl-client) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(echobot-curl-client src/main.cpp) target_link_libraries(echobot-curl-client /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### CMake Project Setup and Options Source: https://github.com/reo7sp/tgbot-cpp/blob/master/CMakeLists.txt Configures the minimum CMake version, project name, and various build options such as enabling tests, shared/static library building, and documentation generation. It also sets C++ standard requirements and platform-specific compiler flags. ```cmake cmake_minimum_required(VERSION 3.10.2) project(TgBot) if(POLICY CMP0074) cmake_policy(SET CMP0074 NEW) # find_package() uses _ROOT variables endif() # options option(ENABLE_TESTS "Set to ON to enable building of tests" OFF) option(BUILD_SHARED_LIBS "Build tgbot-cpp shared/static library." OFF) option(BUILD_DOCUMENTATION "Build doxygen API documentation." OFF) # sources set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) if(WIN32) set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON) add_definitions(-D_WIN32_WINNT=0x0601) add_definitions(-DWIN32_LEAN_AND_MEAN) add_definitions(-DNOMINMAX) else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") endif() ``` -------------------------------- ### Create C++ Inline Keyboards and Handle Callback Queries Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This C++ code demonstrates how to create and use inline keyboards with callback queries in a Telegram bot. It utilizes the TgBot library to send messages with custom buttons and processes user interactions via callback queries, providing a dynamic user experience. This example also includes setup for long polling. ```cpp #include #include #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); // Create inline keyboard TgBot::InlineKeyboardMarkup::Ptr keyboard(new TgBot::InlineKeyboardMarkup); // First row with two buttons std::vector row0; TgBot::InlineKeyboardButton::Ptr button1(new TgBot::InlineKeyboardButton); button1->text = "Option 1"; button1->callbackData = "option_1"; row0.push_back(button1); TgBot::InlineKeyboardButton::Ptr button2(new TgBot::InlineKeyboardButton); button2->text = "Option 2"; button2->callbackData = "option_2"; row0.push_back(button2); keyboard->inlineKeyboard.push_back(row0); // Second row with URL button std::vector row1; TgBot::InlineKeyboardButton::Ptr urlButton(new TgBot::InlineKeyboardButton); urlButton->text = "Visit Telegram"; urlButton->url = "https://telegram.org"; row1.push_back(urlButton); keyboard->inlineKeyboard.push_back(row1); // Send message with keyboard on /start bot.getEvents().onCommand("start", [&bot, &keyboard](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Choose an option:", nullptr, nullptr, keyboard); }); // Handle callback queries bot.getEvents().onCallbackQuery([&bot, &keyboard](TgBot::CallbackQuery::Ptr query) { std::string response; if (query->data == "option_1") { response = "You selected Option 1"; } else if (query->data == "option_2") { response = "You selected Option 2"; } else { response = "Unknown option"; } // Answer callback query (removes loading state) bot.getApi().answerCallbackQuery(query->id, response); // Send response message bot.getApi().sendMessage(query->message->chat->id, response, nullptr, nullptr, keyboard); }); try { printf("Bot started: %s\n", bot.getApi().getMe()->username.c_str()); bot.getApi().deleteWebhook(); TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### Send Media Files using TGbot C++ Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt Demonstrates how to send photos, documents, audio, video, and animations using the TGbot C++ library. It shows sending from local files and URLs, with examples for each media type. Requires the TGbot library. ```cpp #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); bot.getEvents().onCommand("photo", [&bot](TgBot::Message::Ptr message) { try { // Send photo from file TgBot::InputFile::Ptr photoFile(new TgBot::InputFile); photoFile->data = "path/to/photo.jpg"; bot.getApi().sendPhoto(message->chat->id, photoFile, "Photo caption here"); // Send photo from URL bot.getApi().sendPhoto(message->chat->id, "https://telegram.org/img/t_logo.png", "Telegram logo"); } catch (TgBot::TgException& e) { printf("Error: %s\n", e.what()); } }); bot.getEvents().onCommand("document", [&bot](TgBot::Message::Ptr message) { // Send document/file TgBot::InputFile::Ptr document(new TgBot::InputFile); document->data = "path/to/document.pdf"; document->mimeType = "application/pdf"; bot.getApi().sendDocument(message->chat->id, document, nullptr, "Document caption"); }); bot.getEvents().onCommand("audio", [&bot](TgBot::Message::Ptr message) { // Send audio file TgBot::InputFile::Ptr audio(new TgBot::InputFile); audio->data = "path/to/music.mp3"; bot.getApi().sendAudio(message->chat->id, audio, "Song caption", 180, // duration in seconds "Artist Name", "Song Title"); }); bot.getEvents().onCommand("video", [&bot](TgBot::Message::Ptr message) { // Send video TgBot::InputFile::Ptr video(new TgBot::InputFile); video->data = "path/to/video.mp4"; bot.getApi().sendVideo(message->chat->id, video, false, // supportsStreaming 240, // duration 1920, // width 1080, // height nullptr, // thumbnail "Video caption"); }); bot.getEvents().onCommand("animation", [&bot](TgBot::Message::Ptr message) { // Send GIF/animation TgBot::InputFile::Ptr animation(new TgBot::InputFile); animation->data = "path/to/animation.gif"; bot.getApi().sendAnimation(message->chat->id, animation, nullptr, "Funny animation"); }); // Handle received photos bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { if (!message->photo.empty()) { // Get the largest photo size auto photo = message->photo.back(); // Download the file TgBot::File::Ptr file = bot.getApi().getFile(photo->fileId); std::string fileUrl = "https://api.telegram.org/file/bot" + bot.getToken() + "/" + file->filePath; bot.getApi().sendMessage(message->chat->id, "Photo received! File ID: " + photo->fileId + "\nFile size: " + std::to_string(photo->fileSize) + "\nDownload: " + fileUrl); } }); try { TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### Implement Telegram Bot Long Polling in C++ Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This example shows how to set up and run a Telegram bot using long polling with the tgbot-cpp library. It includes graceful shutdown handling via signal interrupts (Ctrl+C) and configures the long polling parameters for update retrieval. The bot responds to the /start command and echoes any non-command messages. ```cpp #include #include #include // Global flag for graceful shutdown volatile sig_atomic_t shutdown_flag = 0; void signalHandler(int signal) { shutdown_flag = 1; printf("\nShutdown signal received, stopping bot...\n"); } int main() { std::string token = "YOUR_BOT_TOKEN_HERE"; TgBot::Bot bot(token); // Register signal handler for Ctrl+C signal(SIGINT, signalHandler); signal(SIGTERM, signalHandler); bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Bot is running!"); }); bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { if (!TgBot::StringTools::startsWith(message->text, "/")) { bot.getApi().sendMessage(message->chat->id, "Echo: " + message->text); } }); try { printf("Bot username: %s\n", bot.getApi().getMe()->username.c_str()); // Remove webhook if one was set (required for long polling) bot.getApi().deleteWebhook(); // Create long poll instance with custom parameters // Parameters: limit (max updates), timeout (seconds) TgBot::TgLongPoll longPoll(bot, 100, 10); printf("Long polling started. Press Ctrl+C to stop.\n"); while (!shutdown_flag) { longPoll.start(); } printf("Bot stopped gracefully.\n"); } catch (TgBot::TgException& e) { printf("Telegram error: %s\n", e.what()); return 1; } catch (std::exception& e) { printf("Error: %s\n", e.what()); return 1; } return 0; } ``` -------------------------------- ### Create and Manage Reply Keyboards in C++ Telegram Bot Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This C++ snippet shows how to create custom reply keyboards for a Telegram bot using the tgbot-cpp library. It includes examples of adding text buttons, enabling location sharing, and enabling contact sharing. The code also demonstrates how to remove the keyboard and handle user interactions with the bot. ```cpp #include #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { // Create reply keyboard TgBot::ReplyKeyboardMarkup::Ptr keyboard(new TgBot::ReplyKeyboardMarkup); keyboard->resizeKeyboard = true; // Optimize keyboard size keyboard->oneTimeKeyboard = true; // Hide after use // First row std::vector row0; TgBot::KeyboardButton::Ptr button1(new TgBot::KeyboardButton); button1->text = "Help"; row0.push_back(button1); TgBot::KeyboardButton::Ptr button2(new TgBot::KeyboardButton); button2->text = "Settings"; row0.push_back(button2); keyboard->keyboard.push_back(row0); // Second row with location sharing std::vector row1; TgBot::KeyboardButton::Ptr locationButton(new TgBot::KeyboardButton); locationButton->text = "Share Location"; locationButton->requestLocation = true; row1.push_back(locationButton); keyboard->keyboard.push_back(row1); // Third row with contact sharing std::vector row2; TgBot::KeyboardButton::Ptr contactButton(new TgBot::KeyboardButton); contactButton->text = "Share Contact"; contactButton->requestContact = true; row2.push_back(contactButton); keyboard->keyboard.push_back(row2); bot.getApi().sendMessage(message->chat->id, "Choose an action:", nullptr, nullptr, keyboard); }); // Remove keyboard when /remove is sent bot.getEvents().onCommand("remove", [&bot](TgBot::Message::Ptr message) { TgBot::ReplyKeyboardRemove::Ptr removeKeyboard(new TgBot::ReplyKeyboardRemove); removeKeyboard->removeKeyboard = true; bot.getApi().sendMessage(message->chat->id, "Keyboard removed", nullptr, nullptr, removeKeyboard); }); bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { if (TgBot::StringTools::startsWith(message->text, "/")) { return; } if (message->text == "Help") { bot.getApi().sendMessage(message->chat->id, "Help information here"); } else if (message->text == "Settings") { bot.getApi().sendMessage(message->chat->id, "Settings page"); } else if (message->location) { bot.getApi().sendMessage(message->chat->id, "Location received: " + std::to_string(message->location->latitude) + ", " + std::to_string(message->location->longitude)); } else if (message->contact) { bot.getApi().sendMessage(message->chat->id, "Contact received: " + message->contact->firstName); } }); try { TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### C++ Telegram Bot: Edit and Delete Messages Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This C++ code snippet utilizes the tgbot-cpp library to control message editing and deletion within a Telegram bot. It demonstrates sending messages, updating their content, and removing them from chats. Key functions include `editMessageText`, `deleteMessage`, and handling callback queries for interactive updates. Ensure you have the tgbot-cpp library installed and replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token. ```cpp #include #include #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); bot.getEvents().onCommand("countdown", [&bot](TgBot::Message::Ptr message) { try { // Send initial message TgBot::Message::Ptr sentMsg = bot.getApi().sendMessage( message->chat->id, "Countdown: 5"); // Update message every second for (int i = 4; i >= 0; --i) { std::this_thread::sleep_for(std::chrono::seconds(1)); bot.getApi().editMessageText("Countdown: " + std::to_string(i), sentMsg->chat->id, sentMsg->messageId); } std::this_thread::sleep_for(std::chrono::seconds(1)); bot.getApi().editMessageText("Time's up!", sentMsg->chat->id, sentMsg->messageId); } catch (TgBot::TgException& e) { printf("Error: %s\n", e.what()); } }); bot.getEvents().onCommand("delete", [&bot](TgBot::Message::Ptr message) { // Send a message TgBot::Message::Ptr sentMsg = bot.getApi().sendMessage( message->chat->id, "This message will be deleted in 3 seconds..."); // Wait and delete std::this_thread::sleep_for(std::chrono::seconds(3)); bot.getApi().deleteMessage(sentMsg->chat->id, sentMsg->messageId); // Also delete the command message bot.getApi().deleteMessage(message->chat->id, message->messageId); }); bot.getEvents().onCommand("edit", [&bot](TgBot::Message::Ptr message) { TgBot::Message::Ptr sentMsg = bot.getApi().sendMessage( message->chat->id, "Original message"); std::this_thread::sleep_for(std::chrono::seconds(2)); // Edit with new text and formatting bot.getApi().editMessageText("*Edited message* with _formatting_", sentMsg->chat->id, sentMsg->messageId, "", // inline message id "Markdown"); }); // Edit inline keyboard on callback bot.getEvents().onCallbackQuery([&bot](TgBot::CallbackQuery::Ptr query) { if (query->data == "edit_button") { // Create new keyboard TgBot::InlineKeyboardMarkup::Ptr newKeyboard( new TgBot::InlineKeyboardMarkup); std::vector row; TgBot::InlineKeyboardButton::Ptr button( new TgBot::InlineKeyboardButton); button->text = "Edited Button"; button->callbackData = "edited"; row.push_back(button); newKeyboard->inlineKeyboard.push_back(row); // Edit message text and keyboard bot.getApi().editMessageText("Message text updated!", query->message->chat->id, query->message->messageId, "", "", false, newKeyboard); bot.getApi().answerCallbackQuery(query->id, "Keyboard updated!"); } }); try { TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### Initialize tgbot-cpp Bot and Verify Credentials Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt Demonstrates how to initialize the TgBot::Bot object with a token, verify its credentials by fetching bot information, and handle potential exceptions during initialization. It also shows an optional configuration for using a custom API URL, such as for a local bot API server. ```cpp #include int main() { // Initialize bot with your token TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); try { // Verify bot credentials and get bot information TgBot::User::Ptr me = bot.getApi().getMe(); printf("Bot started: @%s\n", me->username.c_str()); printf("Bot ID: %lld\n", me->id); printf("Bot name: %s\n", me->firstName.c_str()); // Custom API URL for local bot API server (optional) // TgBot::Bot bot("TOKEN", httpClient, "http://localhost:8081"); } catch (TgBot::TgException& e) { printf("Error: %s\n", e.what()); return 1; } return 0; } ``` -------------------------------- ### CMake Build Configuration for tgbot-cpp Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/receive-file/CMakeLists.txt This CMakeLists.txt file sets up the build environment for the tgbot-cpp project. It specifies the minimum CMake version, project name, C++ standard (14), required standard compliance, and compiler warning flags. It also configures the use of multithreading with Boost and finds necessary libraries such as Threads, OpenSSL, Boost, and cURL, setting include directories and definitions accordingly. Finally, it defines the executable target 'receive-file' and links it with the project's static library and found dependencies. ```cmake cmake_minimum_required(VERSION 3.10.2) project(receive-file) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(receive-file src/main.cpp) target_link_libraries(receive-file /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### CMake Testing and Documentation Configuration Source: https://github.com/reo7sp/tgbot-cpp/blob/master/CMakeLists.txt Sets up the build system to enable testing if the ENABLE_TESTS option is on, and configures Doxygen for generating API documentation if the BUILD_DOCUMENTATION option is enabled. It defines custom commands for Doxygen execution. ```cmake # tests if (ENABLE_TESTS) message(STATUS "Building of tests is enabled") enable_testing() add_subdirectory(test) endif() #add_subdirectory(samples/echobot-webhook-server) #add_subdirectory(samples/inline-keyboard) #add_subdirectory(samples/reply-keyboard) # Documentation if(BUILD_DOCUMENTATION) find_package(Doxygen REQUIRED) add_custom_target(doc_doxygen ALL COMMAND ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Generating API documentation with Doxygen" VERBATIM) install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/doc/html/ TYPE DOC) endif() if(BUILD_SHARED_LIBS) add_definitions(-DTGBOT_DLL) endif() ``` -------------------------------- ### Configure echobot-webhook-server CMake Project Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot-webhook-server/CMakeLists.txt This CMake script configures the build for the echobot-webhook-server project. It sets C++ standards, compiler flags, and finds required packages such as Threads, OpenSSL, Boost, and CURL. Finally, it adds the executable and links all necessary libraries. ```cmake cmake_minimum_required(VERSION 3.10.2) project(echobot-webhook-server) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(echobot-webhook-server src/main.cpp) target_link_libraries(echobot-webhook-server /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES}) ``` -------------------------------- ### Set up a C++ Webhook Server for Telegram Bots Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This C++ code sets up a webhook server to receive updates from Telegram. It requires the TgBot library and handles SIGINT for graceful shutdown. The server listens on a specified port and can be configured with a webhook URL and token, suitable for production environments. ```cpp #include #include #include #include volatile sig_atomic_t shutdown_flag = 0; void signalHandler(int signal) { shutdown_flag = 1; printf("\nShutdown signal received\n"); } int main() { std::string token = getenv("TOKEN") ? getenv("TOKEN") : "YOUR_TOKEN"; std::string webhookUrl = getenv("WEBHOOK_URL") ? getenv("WEBHOOK_URL") : "https://yourdomain.com:8443/webhook"; printf("Token: %s\n", token.c_str()); printf("Webhook URL: %s\n", webhookUrl.c_str()); TgBot::Bot bot(token); signal(SIGINT, signalHandler); bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Webhook bot is running!"); }); bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { if (!TgBot::StringTools::startsWith(message->text, "/")) { printf("User wrote: %s\n", message->text.c_str()); bot.getApi().sendMessage(message->chat->id, "Your message: " + message->text); } }); try { printf("Bot username: %s\n", bot.getApi().getMe()->username.c_str()); // Set webhook with optional secret token for security bot.getApi().setWebhook(webhookUrl, nullptr, 40, nullptr, "", false, "your_secret_token_here"); // Create webhook server on port 8080 TgBot::TgWebhookTcpServer webhookServer(8080, bot); printf("Webhook server starting on port 8080\n"); webhookServer.start(); // To remove webhook later: // bot.getApi().deleteWebhook(false); } catch (std::exception& e) { printf("Error: %s\n", e.what()); return 1; } return 0; } ``` -------------------------------- ### CMake Build Configuration for echobot Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot/CMakeLists.txt This CMake script sets up the build environment for the echobot. It defines the C++ standard, compiler flags, and includes necessary headers. It also finds and links required libraries such as Threads, OpenSSL, Boost, and CURL, crucial for the bot's functionality. ```cmake cmake_minimum_required(VERSION 3.10.2) project(echobot) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(echobot src/main.cpp) target_link_libraries(echobot /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### Manage Telegram Bot Commands with C++ Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This C++ code snippet demonstrates how to set, retrieve, and handle bot commands using the tgbot-cpp library. It includes creating command objects, interacting with the Telegram API to set commands, and defining event handlers for command execution. Ensure you replace 'YOUR_BOT_TOKEN_HERE' with your actual bot token. ```cpp #include #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); try { // Create bot commands std::vector commands; TgBot::BotCommand::Ptr startCmd(new TgBot::BotCommand); startCmd->command = "start"; startCmd->description = "Start the bot"; commands.push_back(startCmd); TgBot::BotCommand::Ptr helpCmd(new TgBot::BotCommand); helpCmd->command = "help"; helpCmd->description = "Show help information"; commands.push_back(helpCmd); TgBot::BotCommand::Ptr settingsCmd(new TgBot::BotCommand); settingsCmd->command = "settings"; settingsCmd->description = "Bot settings"; commands.push_back(settingsCmd); TgBot::BotCommand::Ptr statsCmd(new TgBot::BotCommand); statsCmd->command = "stats"; statsCmd->description = "Show statistics"; commands.push_back(statsCmd); // Set commands for all users bool result = bot.getApi().setMyCommands(commands); if (result) { printf("Bot commands set successfully!\n"); } // Get current commands std::vector currentCommands = bot.getApi().getMyCommands(); printf("Current bot commands:\n"); for (const auto& cmd : currentCommands) { printf("/%s - %s\n", cmd->command.c_str(), cmd->description.c_str()); } // Delete all commands // bot.getApi().deleteMyCommands(); } catch (TgBot::TgException& e) { printf("Error: %s\n", e.what()); return 1; } // Implement command handlers bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Bot started!"); }); bot.getEvents().onCommand("help", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Available commands:\n" "/start - Start the bot\n" "/help - Show this help\n" "/settings - Configure bot\n" "/stats - View statistics"); }); bot.getEvents().onCommand("settings", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Settings page"); }); bot.getEvents().onCommand("stats", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Bot Statistics:\nUsers: 100\nMessages: 1000"); }); try { TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### Configure Test Executable Build Source: https://github.com/reo7sp/tgbot-cpp/blob/master/test/CMakeLists.txt This snippet configures the CMake build system to create a test executable. It defines the source files, includes a test-specific directory, and links against the main project library. ```cmake set(TEST_SRC_LIST main.cpp tgbot/Api.cpp tgbot/net/Url.cpp tgbot/net/HttpParser.cpp tgbot/tools/StringTools.cpp ) include_directories("${PROJECT_SOURCE_DIR}/test") add_executable(${PROJECT_NAME}_test ${TEST_SRC_LIST}) target_link_libraries(${PROJECT_NAME}_test ${PROJECT_NAME}) add_test(${PROJECT_NAME}_test ${PROJECT_NAME}_test) ``` -------------------------------- ### CMake Build Configuration for C++ Telegram Bot Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/photo/CMakeLists.txt This CMakeLists.txt file sets up the build environment for a C++ Telegram bot executable named 'photo'. It defines the C++ standard, compiler flags, and links against essential libraries such as TgBot, Threads, OpenSSL, Boost, and CURL. It also includes conditional logic for handling the CURL library. ```cmake cmake_minimum_required(VERSION 3.10.2) project(photo) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(photo src/main.cpp) target_link_libraries(photo /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### Compiling Bot Without CMake in C++ Source: https://github.com/reo7sp/tgbot-cpp/blob/master/README.md This command compiles a Telegram bot written in C++ without using CMake. It specifies the C++ standard, include paths, library dependencies, and threading support required for the tgbot-cpp library. ```bash g++ telegram_bot.cpp -o telegram_bot --std=c++14 -I/usr/local/include -lTgBot -lboost_system -lssl -lcrypto -lpthread ``` -------------------------------- ### CMake Build Configuration for echobot-submodule Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot-submodule/CMakeLists.txt This snippet outlines the CMake build configuration for the echobot-submodule project. It sets the C++ standard to 14, enables required flags, and finds essential libraries including Threads, OpenSSL, Boost, and CURL. It also includes the tgbot-cpp subdirectory and links all dependencies to the main executable. ```cmake cmake_minimum_required(VERSION 3.10.2) project(echobot-submodule) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_subdirectory(tgbot-cpp) add_executable(echobot-submodule src/main.cpp) target_link_libraries(echobot-submodule TgBot ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### CMake Build Configuration for tgbot-cpp Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/reply-keyboard/CMakeLists.txt This CMake script sets up the build environment for the tgbot-cpp project. It specifies the C++ standard, compiler flags, and finds necessary external libraries such as Threads, OpenSSL, Boost, and CURL. It then defines the main executable and links all required libraries to it. Dependencies include Boost, OpenSSL, Threads, and optionally CURL. ```cmake cmake_minimum_required(VERSION 3.10.2) project(reply-keyboard) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(reply-keyboard src/main.cpp) target_link_libraries(reply-keyboard /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ``` -------------------------------- ### Handle Telegram Bot Events and Messages in C++ Source: https://context7.com/reo7sp/tgbot-cpp/llms.txt This snippet demonstrates how to register callbacks for various Telegram update types, including commands and general messages, using the tgbot-cpp library. It shows handling specific commands, multiple commands with a single handler, and processing any non-command message by echoing it back to the user. Error handling for unknown commands is also included. ```cpp #include #include int main() { TgBot::Bot bot("YOUR_BOT_TOKEN_HERE"); // Handle /start command bot.getEvents().onCommand("start", [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Hi! Send me any message."); }); // Handle multiple commands with the same handler bot.getEvents().onCommand({"help", "info"}, [&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Available commands:\n/start - Start bot\n/help - Show help"); }); // Handle all non-command messages bot.getEvents().onAnyMessage([&bot](TgBot::Message::Ptr message) { // Skip if it's a command if (TgBot::StringTools::startsWith(message->text, "/")) { return; } printf("User %s wrote: %s\n", message->from->firstName.c_str(), message->text.c_str()); // Echo the message back std::string response = "You wrote: " + message->text; bot.getApi().sendMessage(message->chat->id, response); }); // Handle unknown commands bot.getEvents().onUnknownCommand([&bot](TgBot::Message::Ptr message) { bot.getApi().sendMessage(message->chat->id, "Unknown command. Type /help for available commands."); }); try { printf("Bot started: %s\n", bot.getApi().getMe()->username.c_str()); TgBot::TgLongPoll longPoll(bot); while (true) { longPoll.start(); } } catch (std::exception& e) { printf("Error: %s\n", e.what()); } return 0; } ``` -------------------------------- ### CMake Configuration for C++ Tgbot Project Source: https://github.com/reo7sp/tgbot-cpp/blob/master/samples/echobot-setmycommands/CMakeLists.txt This snippet defines the build configuration for a C++ Telegram bot project using CMake. It sets the C++ standard, compiler flags, and includes directories for necessary libraries like OpenSSL, Boost, and CURL. It specifies the main source file and links all required libraries to the executable. ```cmake cmake_minimum_required(VERSION 3.10.2) project(echobot-setmycommands) set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall") set(Boost_USE_MULTITHREADED ON) find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED) find_package(Boost COMPONENTS system REQUIRED) find_package(CURL) include_directories(/usr/local/include ${OPENSSL_INCLUDE_DIR} ${Boost_INCLUDE_DIR}) if (CURL_FOUND) include_directories(${CURL_INCLUDE_DIRS}) add_definitions(-DHAVE_CURL) endif() add_executable(echobot-setmycommands src/main.cpp) target_link_libraries(echobot-setmycommands /usr/local/lib/libTgBot.a ${CMAKE_THREAD_LIBS_INIT} ${OPENSSL_LIBRARIES} ${Boost_LIBRARIES} ${CURL_LIBRARIES}) ```