Git Product home page Git Product logo

telegrambotlib-qt's Introduction

Qt Telegram Bot Library

A very easy to use Qt library for Accessing the Telegram Bot Api.


Receiving Updates

The Telegrambot library gives you multiple possibilities to receive messages which was sent to your bot

Message Pulling

The Message pull system connects to Telegram Server and pull for new messages:

  • If a new Message is available, the Telegram Server push a new message directly over this connection to us,
    then the Telegrambot processes this message(s) and send for every message a SIGNAL to the outside world.
  • If the Telegrambot don't receive a message in a given time, the pull system disconnects from the telegram server.
  • This Process repeats endless until the user call stopMessagePulling().

Advantages over Webhook:

  • No administrative Task needed to make it work
  • Client only need the possibility to connect to a remote server
  • No Certificate needed
  • No open Port needed
  • No NAT port forwarding needed (if client is in NAT-Network)

Disadvantages over Webhook:

  • Only one simultaneously connection to telegram to handle messages

Here an example

#include <QCoreApplication>
#include "telegrambot.h"

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);
    
    TelegramBot bot("APIKEY");
    QObject::connect(&bot, &TelegramBot::newMessage, [](TelegramBotMessage message) {
        qDebug("New Message from: %s %s (%s) -> %s", 
               qPrintable(message.from.firstName), 
               qPrintable(message.from.lastName), 
               qPrintable(message.from.username), 
               qPrintable(message.text));
    });
    bot.startMessagePulling();
    
    return a.exec();
}
Message Polling (Webhook)

The Webhook system tells the Telegram Server to call a secure public Web Url to deliver the user message.
To make this possible the public url needs a valid certificate, either a valid public accpeted one or a self signed one.

Here an easy example installation instruction which should work nearly for all kinds of setups (including NAT):

  • First we need a public domain, so let us make one using this awesome nip.io service: telegram.our ip address.nip.io
  • Now we generate an ssl cert for this domain using the following command line (we need the openssl tool for it):
    openssl req -newkey rsa:2048 -sha256 -nodes -keyout telegram.key -x509 -days 365 -out telegram.crt -subj "//C=DE\CN=telegram.[our ip address].nip.io"
  • Put the generated files (telegram.key and telegram.crt) into the working directory of your application.
  • If in Nat, forward external port 8443 to port 8443 on local PC.

Then use the following Qt Code:

#include <QCoreApplication>
#include "telegrambot.h"

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);
    
    TelegramBot bot("APIKEY");
    QObject::connect(&bot, &TelegramBot::newMessage, [](TelegramBotMessage message) {
        qDebug("New Message from: %s %s (%s) -> %s", 
               qPrintable(message.from.firstName), 
               qPrintable(message.from.lastName), 
               qPrintable(message.from.username), 
               qPrintable(message.text));
    });
    bot.setHttpServerWebhook(8443, "telegram.crt", "telegram.key");
    
    return a.exec();
}

Communication

The Tegrambot library gives you also the possibility to communicate with chats.
Here is an example which should explain the basic use cases:

#include <QCoreApplication>
#include "telegrambot.h"

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

    TelegramBot bot("APIKEY");
    QObject::connect(&bot, &TelegramBot::newMessage, [&bot](TelegramBotUpdate update) {
        // only handle Messages
        if(update->type != TelegramBotMessageType::Message) return;
        
        // simplify message access
        TelegramBotMessage& message = *update->message;		
        
        // send message (Format: Normal)
        TelegramBotMessage msgSent;
        bot.sendMessage(message.chat.id,
                        "This is a Testmessage",
                        0,
                        TelegramBot::NoFlag,
                        TelegramKeyboardRequest(),
                        &msgSent);

        // edit text of sent message (Format: Markdown)
        bot.editMessageText(message.chat.id,
                            msgSent.messageId,
                            "This is an edited *Testmessage*",
                            TelegramBot::Markdown);

        // send message (Format: HTML, Keyboard: Inline (2 Rows, 1 Column), Reply to Message: Yes)
        bot.sendMessage(message.chat.id,
                        "Please <b>choose</b>",
                        0,
                        TelegramBot::Html,
                        {
                            // Keyboard
                            {
                                TelegramBot::constructInlineButton("Google", "", "https://www.google.com"),
                            }, {
                                TelegramBot::constructInlineButton("Reply with data", "MYDATA1"),
                            }
                        });

        // send photo (file location: web)
        bot.sendPhoto(message.chat.id,
                      "https://www.kernel.org/theme/images/logos/tux.png",
                      "This is the Linux Tux");

        // send audio (file location: local)
        bot.sendAudio(message.chat.id,
                      "Maktone - Fluke01.mp3",
                      "Listen to this great art :-)",
                      "Maktone",
                      "Fluke01");

        // send video chat note (file location: QByteArray)
        QFile file("testvideo.mp4");
        file.open(QFile::ReadOnly);
        QByteArray content = file.readAll();
        bot.sendVideoNote(msgSent.chat.id, content);

        // send sticker (file location: telegram server)
        bot.sendSticker(message.chat.id, "CXXXXXXXXXXXXXXXXXXXXXXX");
    });
    bot.startMessagePulling();
                    
   return a.exec();
}

This example produces the following Telgram messages:
result


File Handing

The library provides four different opportunities for sending a file to telegram:

  • Web: just provide an web link as string
  • Local file: just provide a local file path as string
  • QBytearray: just call with a QBytearray which contains the data (The library also try to detect its content type!)
  • Telegram Server: just call with an telegram file id as string

Note: file uploades are handled asynyron!
A possible use case for all types are also available in the example above.


Message Routing

In Addition the Library contains a message routing system.
This system allows you to route any kind of message to your own functions (using a QDelegate)

The following Code Example demonstrate this message routing, by handing the first /start-message a user send to a bot:

#include <QCoreApplication>
#include "telegrambot.h"

int main(int argc, char** argv)
{
    QCoreApplication a(argc, argv);

    TelegramBot bot("APIKEY");
    bot.messageRouterRegister("/start", {[&bot](TelegramBotUpdate update) {
        bot.sendMessage(update->message->chat.id, "Hi, i'am a Test bot");
		return true;
    }}, TelegramBotMessageType::Message);
    
    bot.startMessagePulling();
}

Additional Notes:

  • The example above only handles the /start message all other messages send to the bot are silently ignored.
  • The message Router match field depends on the received message type:
Message Type Fieldname
TelegramBotMessageType::Message Message.text
TelegramBotMessageType::EditedMessage Message.text
TelegramBotMessageType::ChannelPost Message.text
TelegramBotMessageType::EditedChannelPost Message.text
TelegramBotMessageType::InlineQuery InlineQuery.query
TelegramBotMessageType::ChosenInlineResult ChosenInlineResult.query
TelegramBotMessageType::CallbackQuery CallbackQuery.data

Library Dependings

The telegrambotlib-qt depends on QDelegate which are allready included as submodule,
so we have to make sure that the submodules are checked out, too:

git clone --recursive <path>

Or if repo allready exists

git submodule update --init --recursive

Compile Staticly:

Just add the following to your Qt-Project file:

include(telegrambotlib-qt.pri)

Include project syntax:
#include "telegrambot.h"


Compile Dynamicly:

Note: The make install installation pathes, are printed to you during qmake!

qmake telegrambotlib-qt.pro
make
make install

add the following to your pro file:

LIBS += -ltelegrambotlib-qt

Include project syntax:
#include <telegrambotlib-qt/telegrambot.h>


Licence

The telegrambotlib-qt licence is a modified version of the LGPL licence, with a static linking exception.

telegrambotlib-qt's People

Contributors

kusstas avatar spiek 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  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

telegrambotlib-qt's Issues

Sending xls and xlsx files

I'm trying to send xls and xlsx via this lib. The data is correct and successfully saving to the required file itself, but when i'm trying to use sendDocument method i'm getting file of "zip" format for "xlsx" and "x-ole-storage" for good old "xls". Data given in html and pdf formats works fine, so it looks like i am using lib API correctly. Could you tell me please, where the origins of that problem could be? Maybe some additional params should be passed to the function?

QEventLoop: Cannot be used without QApplication

When we run this example in Windows 7:

#include <telegrambotlib-qt/telegrambot.h>
#include <QCoreApplication>


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    TelegramBot bot("340163358:AAEV0eghLuzpkTO7FcylhPeYtaCF8i6YTok");
    bot.messageRouterRegister("/start",
        {[&bot](TelegramBotUpdate update)
        {
           bot.sendMessage(update->message->chat.id, "Hi, I'am a Test bot");
           return true;
        }}
    , TelegramBotMessageType::Message);

    bot.startMessagePulling();




    return a.exec();
}

After SSL connection in console window I get the title message and application hangs.

request_contact and request_location not working

Hi Oswald! Thanks for your library!
There is an issue when you are building reply_markup parameter in hanldeReplyMarkup.
You append request_contact and request_location only in cases they are false, which is a default value.
Consider removing '!' operator in those two checks.

if(flags && TelegramFlags::ReplyKeyboardMarkup) {
    if(!column.requestContact) keyboardContent += QString(",\"request_contact\":%1").arg(column.requestContact ? "true" : "false");
    if(!column.requestLocation) keyboardContent += QString(",\"request_location\":%1").arg(column.requestLocation ? "true" : "false");
} else {
    if(!column.url.isEmpty()) keyboardContent += QString(",\"url\":\"%1\"").arg(column.url);
    if(!column.callbackData.isEmpty()) keyboardContent += QString(",\"callback_data\":\"%1\"").arg(column.callbackData);
    if(!column.switchInlineQuery.isEmpty()) keyboardContent += QString(",\"switch_inline_query\":\"%1\"").arg(column.switchInlineQuery);
    if(!column.switchInlineQueryCurrentChat.isEmpty()) keyboardContent += QString(",\"switch_inline_query_current_chat\":\"%1\"").arg(column.switchInlineQueryCurrentChat);
}

Fixing TelegramBotChat::id

As long as TelegramBotChat id's type is qint32 it cant fit all the information that is being returned by Telegram Bot Api methods which type is equal to long long (C++ style). So it bugs and this kind of bug is very hard to detect. To fix it you just need to replace qint32 so it becomes long long (or qint64).

...
struct TelegramBotChat : public TelegramBotObject {
    long long id;
...
virtual void fromJson(QJsonObject& object) {
        JsonHelperT<long long>::jsonPathGet(object, "id", this->id);
..
}
}

Compiler error on passing lamda to messageRouterRegister method

bot.messageRouterRegister("/start",
        [&bot](TelegramBotUpdate update)
        {
           bot.sendMessage(update->message->chat.id, "Hi, I'am a Test bot");
           return true;
        }
    , TelegramBotMessageType::Message);

Generates error in kit: Desktop Qt 5.10.0 MSVC2017 64bit as follows:

error C2664: 'void TelegramBot::messageRouterRegister(QString,QDelegate<bool (TelegramBotUpdate)>,TelegramBotMessageType)': cannot convert argument 2 from 'main::<lambda_3be0076418be40d7d525cf0ed23bc3b0>' to 'QDelegate<bool (TelegramBotUpdate)>'

2^7 - 1

telegramdatastructs.h:59: warning: result of '2^7' is 5; did you mean '1 << 7' (128)? [-Wxor-used-as-pow]
All = (2^7) - 1

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.