Coder Social home page Coder Social logo

modersi / telegrambotapi Goto Github PK

View Code? Open in Web Editor NEW
25.0 9.0 18.0 7.01 MB

Telegram Bot API on C++ and Qt

License: MIT License

CMake 1.23% C++ 98.56% C 0.21%
telegram telegram-bot bot telegram-api telegram-bot-api telegram-api-cxx telegram-bot-api-cxx telegram-bot-cxx telegram-cxx

telegrambotapi's Introduction

Logo

QTelegramBotAPI

QTelegramBotAPI is a library for developing bots for the Telegram messenger.

Description

Bot in Telegram is something like a built-in program that users can interact with by buttons, commands, simple text messages, etc... You can create any bot you want! It can be a simple weather bot or a much more complicated Russian-Polish translator bot.

Getting started

This library was made following the official Telegram Bot API manual, so you can use it as documentation for all bot methods and all data structures that the library provides. Also, every header file contains a detailed self-description, so you don't always need to look in the official documentation.

You can find well-documented examples of the bot's abilities in the Examples directory. Further, we will talk about the most important classes in QTelegramBotAPI that are used to startup and use your bot.

Telegram::BotSettings is a class that represents your bot settings and contains all required data to launch your bot. Used to construct Telegram::Bot, set up encryption, API key, host address, port, and more.

BotSettings can be constructed in 2 ways:

  • Using a file with bot settings. This file should contain JSON-formatted settings of your bot. By default, BotSettings.json file is located in the project root directory but you can specify another directory and file name in arguments.
// Will initialize bot with settings from the file "BotSettings.json" located in the project root directory
auto settings_from_file = Telegram::BotSettings::makeFromFile();
// Will initialize the bot with settings from file "SpecificFileName.json" in "Specific/Directory"
auto settings_from_custom_file = Telegram::BotSettings::makeFromFile(QDir("Specific/File/Directory"), QStringLiteral("SpecificFileName.json"));
BotSettings JSON object key-value pairs :
Key Required Value
bot_token Yes Your bot token
webhook_url Optional Your HTTPS URL for the Telegram to send updates to. Required if you use webhooks, specify your IP address if you use a self-signed certificate or specify null if you want to get updates via getUpdates()
certificate_path Optional Path to your SSL certificate file. Required if you use webhooks withan authority-signed certificate, specify null if you want to get updates via getUpdates() or if you use self-signed certificate
private_key_path Optional Path to your SSL private key file. Required if you use a webhooks, specify null if you want to get updates via getUpdates()
ca_certificates_paths Optional The JSON array of paths to your SSL CA certificates files. Required if you use webhooks with an authority-signed certificate, specify null if you want to get updates via getUpdates()
public_key_path Optional Required only if you use a self-signed certificate, set to null otherwise. Path to your SSL public key. In essence public key it is your self-signed certificate
webhook_ip_addres Optional The fixed IP address that will be used to send webhook requests instead of the IP address resolved through DNS
max_connections Optional Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to 40
allowed_updates Optional The JSON array with update types you want your bot to receive. For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types
drop_pending_updates Optional Set "true" to drop all pending updates
host_addres Optional Local IP address for webhook server to be listening for incoming connections. Defaults to "127.0.0.1"
port Optional Local port for webhook server to be listening for incoming connections. Defaults to 443
payment_token Optional Your payment token
  • By setting its fields. Look BotSettings.h for all fields and their meanings
// Initializes bot settings "from code". Use this way if you need to set particular settings for your SSL configuration
auto settings_from_code = std::make_shared<Telegram::BotSettings>("BOT_TOKEN", "WEBHOOK_URL");
settings_from_code->ssl_configuration = configureSimpleSSL("Your SSL certificate file path", "Private key file path", { "CA certificate file paths" });

See BotStartup example for the details

Telegram::Bot is a class that represents your bot in Telegram. To create an instance of Telegram::Bot you have to pass Telegram::BotSettings object as an argument

auto bot_settings = Telegram::BotSettings::makeFromFile();
Telegram::Bot telegram_bot(bot_settings);

It contains all available API methods such as sendMessage(), sendPhoto(), etc..

Each method is asynchronous and uses std::future as a return value to provide asynchronous mechanic.

Methods with more than 4 optional arguments use designated initializers. So, for example, if you want to send a message with a reply keyboard you can write

telegram_bot.sendMessage({.chat_id = some_id, .text = some_text, .reply_markup = some_markup}); 

instead of

telegram_bot.sendMessage(some_id, some_text, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, some_markup); 


Also, it contains all Qt signals related to updates handling. So you can easily connect the needed signal to your function or slot. For example, there is Telegram::Bot::messageReceived(qint32 update_id, Message message) signal that is emitted every time when your bot receives a text message. You can find all available signals and their description in Bot.h file

QObject::connect(&telegram_bot, &Telegram::Bot::messageReceived, [&](qint32 update_id, Telegram::Message message) { 
  telegram_bot.sendMessage(message.chat->id, message.text.value_or("")); 
});

See IncomingMessagesHandling example for the details

Dependecies

QTelegramBotAPI is written using Qt 6.3.0 and OpenSSL 1.1.1j, so if you want to add the QTelegramBotAPI library to your project firstly you should link these libraries to your project.

find_package(Qt6 REQUIRED Core Network)				
target_link_libraries(${PROJECT_NAME} PRIVATE Qt6::Core PRIVATE Qt6::Network)

find_package(OpenSSL REQUIRED)			
target_link_libraries(${PROJECT_NAME} PRIVATE OpenSSL::SSL)

Linking to your project

You can easily link QTelegramBotAPI to your project with CMake by including header files located in TelegramBotAPI/include and linking with TelegramBotAPI.lib

target_include_directories(${PROJECT_NAME} PRIVATE install/path/TelegramBotAPI/include)
target_link_libraries(${PROJECT_NAME} PRIVATE install/path/TelegramBotAPI/TelegramBotAPI.lib)

telegrambotapi's People

Contributors

modersi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegrambotapi's Issues

Build Issue '_is_iterator_v' is not a member of 'std'

Hi! I need so much your library, but can't build it in Qt 6.6.3. In 'QJsonArrayInserter.h', row 33, where we have

/** @brief Creates a new QJsonArray with the contents of the range [first, last) */
        template<typename Iterator>
            requires std::_Is_iterator_v<Iterator>
        static QJsonArray make(Iterator begin, Iterator end);

compiler throws a build issue '_is_iterator_v' is not a member of 'std'. I tried to find this template '_Is_iterator_v' in cppreference.com and cplusplus.com but don't give any results! Also I tried recent gcc compiler (14.0.1) with the same result.
Can you advise how to compile the library in Qt 6.6.3 (and for Ubuntu 22.04 LTS in particular)?
Best regards, Oleksiy.

Telegram::Bot::sendMediaGroup is broken

Error 400 (Bad Request: can't parse InputMedia: media not found)

Simple example:

auto photo_file = std::make_shared<QFile>("D:/1.png");
auto photo_file2 = std::make_shared<QFile>("D:/2.png");

bool bOk1 = photo_file->open(QIODevice::ReadOnly);
bool bOk2 = photo_file2->open(QIODevice::ReadOnly);

Q_ASSERT(bOk1 && bOk2);

_bot->sendMediaGroup(chat_id,
    { InputMediaPhoto(photo_file.get()), InputMediaPhoto(photo_file2.get()) },
    {  }
).get();

QVector< InputMediaPhoto> cannot be used

You cannot actually use any of Telegram::Bot::sendMediaGroup methods, because you cannot create such vectors as QVector<InputMediaPhoto> for example.

One can only create such vectors using initializers:

QVector< InputMediaPhoto> v = { InputMediaPhoto(new QFile()), InputMediaPhoto(new QFile()) };

But you cannot add new items to it:

v.emplace_back(InputMediaPhoto(new QFile()) );

Possible solution: const Type type = Type::PHOTO; must be changed to Type type = Type::PHOTO; in the header.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.