4
1
mirror of https://github.com/QuasarApp/qTbot.git synced 2025-05-04 09:19:39 +00:00

Merge pull request from QuasarApp/edit_keyboard_functions

added method to edit keyboard
This commit is contained in:
Andrei Yankovich 2023-11-19 22:40:07 +01:00 committed by GitHub
commit 7958f23519
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 654 additions and 472 deletions

@ -12,6 +12,8 @@
#include <qTbot/messages/telegrammsg.h> #include <qTbot/messages/telegrammsg.h>
#include <qTbot/messages/telegramupdate.h> #include <qTbot/messages/telegramupdate.h>
// link to test bot
// @quasarapp_test_bot (https://t.me/quasarapp_test_bot)
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
QCoreApplication::setOrganizationName("QuasarApp"); QCoreApplication::setOrganizationName("QuasarApp");
@ -44,21 +46,31 @@ int main(int argc, char *argv[]) {
if (tmsg->contains(tmsg->Audio)) { if (tmsg->contains(tmsg->Audio)) {
filesStack.push_back(bot.getFile(tmsg->audio()->fileId(), qTbot::iFile::Local)); filesStack.push_back(bot.getFile(tmsg->audio()->fileId(), qTbot::iFile::Local));
} }
bot.sendSpecificMessageWithKeyboard(tmsg->chatId(),
"I see it - я вижу это",
{{{"test_button", [tmsg, &bot](const QString& queryId, const QVariant& msgId){
static int index = 0;
bot.editSpecificMessageWithKeyboard(msgId,
tmsg->chatId(),
"I see it - я вижу это. Presedd count: " + QString::number(index++), true, false,
{{{"test_button", [](auto , auto ){}}, {"test_button 2", [](auto , auto ){}}}},
queryId);
}}}}, {}, false, false, tmsg->messageId());
bot.sendSpecificMessageWithKeyboard(tmsg->chatId(), bot.sendSpecificMessageWithKeyboard(qTbot::TelegramArgs{tmsg->chatId(), "I see it", tmsg->messageId()},
"I see it - я вижу это (интерактивная клавиатура)", {{{"test_button", [tmsg, &bot](const QString& queryId, const QVariant& msgId){
static int index = 0;
auto&& args = qTbot::TelegramArgs{tmsg->chatId(),
"I see it. Presed count: " + QString::number(index++),
tmsg->messageId(),
"",
false,
queryId};
auto&& keyboard = qTbot::KeyboardOnMessage{
{{"test_button", [](auto , auto ){}},
{"test_button 2", [](auto , auto ){}}}};
bot.editSpecificMessageWithKeyboard(msgId,
args,
keyboard
);
}}}});
bot.sendSpecificMessageWithKeyboard(qTbot::TelegramArgs{tmsg->chatId(), "I see it", tmsg->messageId()},
{{{"test_button"}, {{{"test_button"},
{"test_button"},}}, {}, true, true, tmsg->messageId()); {"test_button"},}}, true, true);
} }
} }

@ -10,24 +10,12 @@
namespace qTbot { namespace qTbot {
TelegramEditMessage::TelegramEditMessage(const QVariant &idEditedMessage, TelegramEditMessage::TelegramEditMessage(const QVariant &idEditedMessage,
const QVariant& chatId, const TelegramArgs &args,
const QString& newText, const ExtraJsonObjects &extraObjects):
bool markdown, TelegramSendMsg(args, extraObjects){
bool disableWebPagePreview,
const QString& callBackQueryId,
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects):
TelegramSendMsg(chatId,
newText,
extraObjects,
0,
markdown,
callBackQueryId,
disableWebPagePreview) {
setRequest("editMessageText");
addArg("message_id", idEditedMessage);
setRequest("editMessageText");
addArg("message_id", idEditedMessage);
}
} }
}

@ -18,12 +18,8 @@ class TelegramEditMessage: public TelegramSendMsg
{ {
public: public:
TelegramEditMessage(const QVariant& idEditedMessage, TelegramEditMessage(const QVariant& idEditedMessage,
const QVariant& chatId, const TelegramArgs& args,
const QString& newText, const ExtraJsonObjects& extraObjects = {});
bool markdown = true,
bool disableWebPagePreview = false,
const QString& callBackQueryId = "",
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects = {});
}; };
} }
#endif // TELEGRAMEDITMESSAGE_H #endif // TELEGRAMEDITMESSAGE_H

@ -0,0 +1,19 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#include "telegrameditmessagereplymarkup.h"
namespace qTbot {
TelegramEditMessageReplyMarkup::TelegramEditMessageReplyMarkup(const QVariant& idEditedMessage,
const TelegramArgs& args,
const ExtraJsonObjects &extraObjects):
TelegramEditMessage(idEditedMessage, args, extraObjects)
{
setRequest("editMessageReplyMarkup");
}
}

@ -0,0 +1,26 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#ifndef TELEGRAMEDITMESSAGEREPLYMARKUP_H
#define TELEGRAMEDITMESSAGEREPLYMARKUP_H
#include "telegrameditmessage.h"
namespace qTbot {
/**
* @brief The TelegramEditMessageReplyMarkup class just edit alredy created Markups.
*/
class TelegramEditMessageReplyMarkup: public TelegramEditMessage
{
public:
TelegramEditMessageReplyMarkup(const QVariant& idEditedMessage,
const TelegramArgs &args,
const ExtraJsonObjects& extraObjects = {});
};
}
#endif // TELEGRAMEDITMESSAGEREPLYMARKUP_H

@ -10,6 +10,9 @@
namespace qTbot { namespace qTbot {
TelegramGetUpdate::TelegramGetUpdate(): TelegramSingleRquest("getUpdates"){} TelegramGetUpdate::TelegramGetUpdate(unsigned long long offset): TelegramSingleRquest("getUpdates"){
addArg("offset", offset);
addArg("timeout", 30);
} }
}

@ -20,7 +20,11 @@ namespace qTbot {
class TelegramGetUpdate final: public TelegramSingleRquest class TelegramGetUpdate final: public TelegramSingleRquest
{ {
public: public:
TelegramGetUpdate(); /**
* @brief TelegramGetUpdate send request for updates. You will get response on immediacy or after 60 seconds if bot does not have any updates.
* @param offset - last accepted update id.
*/
TelegramGetUpdate(unsigned long long offset = 0);
}; };
} }
#endif // TELEGRAMGETUPDATE_H #endif // TELEGRAMGETUPDATE_H

@ -0,0 +1,25 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#include "telegramsendcontact.h"
namespace qTbot {
TelegramSendContact::TelegramSendContact(const TelegramArgs &args,
const QString &firstName,
const QString &phone,
const QString &lastName):
TelegramSingleRquest("sendContact", args.toMap(true)) {
addArg("first_name", firstName);
addArg("last_name", lastName);
addArg("phone_number", phone);
}
}

@ -0,0 +1,31 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#ifndef TELEGRAMSENDCONTACT_H
#define TELEGRAMSENDCONTACT_H
#include "qTbot/telegramargs.h"
#include "telegramsinglerquest.h"
namespace qTbot {
/**
* @brief The TelegramSendContact class
*/
class TelegramSendContact: public TelegramSingleRquest
{
public:
TelegramSendContact(const TelegramArgs &args,
const QString &firstName,
const QString &phone,
const QString &lastName);
};
}
#endif // TELEGRAMSENDCONTACT_H

@ -8,15 +8,15 @@
namespace qTbot { namespace qTbot {
TelegramSendDocument::TelegramSendDocument(const QVariant &chatId, TelegramSendDocument::TelegramSendDocument(const TelegramArgs &args,
const QString &text,
const QString& fileName, const QString& fileName,
const QByteArray &data): const QByteArray &data,
TelegramSendFile("sendDocument", chatId, text, fileName, TELEGRAM_DOCUMENT, data) {} const ExtraJsonObjects &extraObjects):
TelegramSendFile("sendDocument", fileName, TELEGRAM_DOCUMENT, data, args, extraObjects) {}
TelegramSendDocument::TelegramSendDocument(const QVariant &chatId, TelegramSendDocument::TelegramSendDocument(const TelegramArgs &args,
const QString &text, const QFileInfo &file,
const QFileInfo &file): const ExtraJsonObjects &extraObjects):
TelegramSendFile("sendDocument", chatId, text, file) {} TelegramSendFile("sendDocument", file, args, extraObjects) {}
} }

@ -19,14 +19,14 @@ namespace qTbot {
class TelegramSendDocument: public TelegramSendFile class TelegramSendDocument: public TelegramSendFile
{ {
public: public:
TelegramSendDocument(const QVariant &chatId, TelegramSendDocument(const TelegramArgs &args,
const QString &text,
const QString &fileName, const QString &fileName,
const QByteArray& data); const QByteArray& data,
const ExtraJsonObjects& extraObjects = {});
TelegramSendDocument(const QVariant &chatId, TelegramSendDocument(const TelegramArgs &args,
const QString &text, const QFileInfo &file,
const QFileInfo &file); const ExtraJsonObjects& extraObjects = {});
}; };
} }

@ -12,23 +12,14 @@ namespace qTbot {
qTbot::TelegramSendFile::TelegramSendFile(const QString &request, qTbot::TelegramSendFile::TelegramSendFile(const QString &request,
const QVariant &chatId,
const QString &text,
const QString &fileName, const QString &fileName,
const QString &fileType, const QString &fileType,
const QByteArray &data, const QByteArray& data,
unsigned long long replyToMessageId, const TelegramArgs &args,
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects const ExtraJsonObjects& extraObjects
): ):
TelegramSingleRquest(request) { TelegramSingleRquest(request, args.toMap(true)) {
addArg("chat_id", chatId);
if (text.size())
addArg("caption", text);
if (replyToMessageId > 0) {
addArg("reply_to_message_id", replyToMessageId);
}
for (auto it = extraObjects.begin(); it != extraObjects.end(); it = std::next(it)) { for (auto it = extraObjects.begin(); it != extraObjects.end(); it = std::next(it)) {
addArg(it.key(), QJsonDocument(*it.value()).toJson(QJsonDocument::Compact)); addArg(it.key(), QJsonDocument(*it.value()).toJson(QJsonDocument::Compact));
@ -38,21 +29,10 @@ qTbot::TelegramSendFile::TelegramSendFile(const QString &request,
} }
qTbot::TelegramSendFile::TelegramSendFile(const QString &request, qTbot::TelegramSendFile::TelegramSendFile(const QString &request,
const QVariant &chatId,
const QString &text,
const QFileInfo &file, const QFileInfo &file,
unsigned long long replyToMessageId, const TelegramArgs &args,
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects): const QHash<QString, QSharedPointer<QJsonObject> > &extraObjects):
TelegramSingleRquest(request) { TelegramSingleRquest(request, args.toMap(true)) {
addArg("chat_id", chatId);
if (text.size())
addArg("text", text);
if (replyToMessageId > 0) {
addArg("reply_to_message_id", replyToMessageId);
}
QFile readFile(file.absoluteFilePath()); QFile readFile(file.absoluteFilePath());
if (!readFile.open(QIODevice::ReadOnly)) { if (!readFile.open(QIODevice::ReadOnly)) {

@ -10,6 +10,8 @@
#include "qfileinfo.h" #include "qfileinfo.h"
#include "requests/telegramsinglerquest.h" #include "requests/telegramsinglerquest.h"
#include <qTbot/telegramargs.h>
#define TELEGRAM_PHOTO "photo" #define TELEGRAM_PHOTO "photo"
#define TELEGRAM_DOCUMENT "document" #define TELEGRAM_DOCUMENT "document"
@ -23,20 +25,16 @@ class TelegramSendFile: public TelegramSingleRquest
public: public:
TelegramSendFile(const QString &request, TelegramSendFile(const QString &request,
const QVariant &chatId,
const QString &text,
const QString &fileName, const QString &fileName,
const QString &fileType, const QString &fileType,
const QByteArray& data, const QByteArray& data,
unsigned long long replyToMessageId = 0, const TelegramArgs &args,
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects = {}); const QHash<QString, QSharedPointer<QJsonObject> > &extraObjects = {});
TelegramSendFile(const QString &request, TelegramSendFile(const QString &request,
const QVariant &chatId,
const QString &text,
const QFileInfo &file, const QFileInfo &file,
unsigned long long replyToMessageId = 0, const TelegramArgs &args,
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects = {}); const QHash<QString, QSharedPointer<QJsonObject> > &extraObjects = {});
RequestMethod method() const override; RequestMethod method() const override;

@ -6,25 +6,21 @@
//# //#
#include "telegramsendlocation.h" #include "telegramsendlocation.h"
#include <QJsonDocument>
namespace qTbot { namespace qTbot {
TelegramSendLocation::TelegramSendLocation(const QVariant &chatId, TelegramSendLocation::TelegramSendLocation(const TelegramArgs &args,
const QString &text,
float latitude, float latitude,
float longitude, float longitude,
unsigned long long replyToMessageId const ExtraJsonObjects &extraObjects):
): TelegramSingleRquest("sendLocation", args.toMap(true)) {
TelegramSingleRquest("sendLocation") {
addArg("chat_id", chatId);
if (text.size())
addArg("caption", text);
addArg("latitude", latitude); addArg("latitude", latitude);
addArg("longitude", longitude); addArg("longitude", longitude);
if (replyToMessageId) { for (auto it = extraObjects.begin(); it != extraObjects.end(); it = std::next(it)) {
addArg("reply_to_message_id", replyToMessageId); addArg(it.key(), QJsonDocument(*it.value()).toJson(QJsonDocument::Compact));
} }
} }

@ -8,6 +8,7 @@
#ifndef TELEGRAMSENDLOCATION_H #ifndef TELEGRAMSENDLOCATION_H
#define TELEGRAMSENDLOCATION_H #define TELEGRAMSENDLOCATION_H
#include "qTbot/telegramargs.h"
#include "requests/telegramsinglerquest.h" #include "requests/telegramsinglerquest.h"
namespace qTbot { namespace qTbot {
@ -17,11 +18,10 @@ namespace qTbot {
class TelegramSendLocation: public TelegramSingleRquest class TelegramSendLocation: public TelegramSingleRquest
{ {
public: public:
TelegramSendLocation(const QVariant &chatId, TelegramSendLocation(const TelegramArgs &args,
const QString &text,
float latitude, float latitude,
float longitude, float longitude,
unsigned long long replyToMessageId); const ExtraJsonObjects& extraObjects = {});
}; };
} }
#endif // TELEGRAMSENDLOCATION_H #endif // TELEGRAMSENDLOCATION_H

@ -11,38 +11,13 @@
#include <QJsonObject> #include <QJsonObject>
namespace qTbot { namespace qTbot {
TelegramSendMsg::TelegramSendMsg(const QVariant &chatId, TelegramSendMsg::TelegramSendMsg(const TelegramArgs& generalArgs,
const QString &text, const QHash<QString, QSharedPointer<QJsonObject> > &extraObjects)
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects,
unsigned long long replyToMessageId,
bool markdown,
const QString &callBackQueryId,
bool disableWebPagePreview)
: :
TelegramSingleRquest("sendMessage") TelegramSingleRquest("sendMessage")
{ {
QMap<QString, QVariant> args {{"chat_id", chatId}}; QMap<QString, QVariant>&& args = generalArgs.toMap();
if (text.size()) {
args["text"] = text;
}
if (replyToMessageId) {
args["reply_to_message_id"] = replyToMessageId;
}
if (markdown) {
args["parse_mode"] = "Markdown";
}
if (disableWebPagePreview) {
args["disable_web_page_preview"] = disableWebPagePreview;
}
if (callBackQueryId.size()) {
args["callback_query_id"] = callBackQueryId;
}
for (auto it = extraObjects.begin(); it != extraObjects.end(); it = std::next(it)) { for (auto it = extraObjects.begin(); it != extraObjects.end(); it = std::next(it)) {
args[it.key()] = QJsonDocument(*it.value()).toJson(QJsonDocument::Compact); args[it.key()] = QJsonDocument(*it.value()).toJson(QJsonDocument::Compact);

@ -8,6 +8,7 @@
#ifndef TELEGRAMSENDMSG_H #ifndef TELEGRAMSENDMSG_H
#define TELEGRAMSENDMSG_H #define TELEGRAMSENDMSG_H
#include "qTbot/telegramargs.h"
#include "telegramsinglerquest.h" #include "telegramsinglerquest.h"
namespace qTbot { namespace qTbot {
@ -17,14 +18,14 @@ namespace qTbot {
class TelegramSendMsg: public TelegramSingleRquest class TelegramSendMsg: public TelegramSingleRquest
{ {
public: public:
TelegramSendMsg(const QVariant& chatId,
const QString& text, /**
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects = {}, * @brief TelegramSendMsg This object sents msg to telegram server.
unsigned long long replyToMessageId = 0, * @param args this is generatl arguments of request (include target chat id).
bool markdown = true, * @param extraObjects additional objects of the telegram messages (json).
const QString& callBackQueryId = "", */
bool disableWebPagePreview = false TelegramSendMsg(const TelegramArgs& args,
); const ExtraJsonObjects& extraObjects = {});
}; };
} }
#endif // TELEGRAMSENDMSG_H #endif // TELEGRAMSENDMSG_H

@ -11,24 +11,15 @@
namespace qTbot { namespace qTbot {
TelegramSendPhoto::TelegramSendPhoto(const QVariant &chatId, TelegramSendPhoto::TelegramSendPhoto(const TelegramArgs &args,
const QString &text,
const QString &fileName, const QString &fileName,
const QByteArray &data, const QByteArray &data,
unsigned long long replyToMessageId, const ExtraJsonObjects &extraObjects):
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects TelegramSendFile("sendPhoto", fileName, TELEGRAM_PHOTO, data, args, extraObjects) {}
):
TelegramSendFile("sendPhoto", chatId, text, fileName, TELEGRAM_PHOTO, data, replyToMessageId, extraObjects) {
} TelegramSendPhoto::TelegramSendPhoto(const TelegramArgs &args,
TelegramSendPhoto::TelegramSendPhoto(const QVariant &chatId,
const QString &text,
const QFileInfo &file, const QFileInfo &file,
unsigned long long replyToMessageId, const ExtraJsonObjects &extraObjects):
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects): TelegramSendFile("sendPhoto", file, args, extraObjects){}
TelegramSendFile("sendPhoto", chatId, text, file, replyToMessageId, extraObjects) {
}
} }

@ -19,19 +19,15 @@ namespace qTbot {
class TelegramSendPhoto: public TelegramSendFile class TelegramSendPhoto: public TelegramSendFile
{ {
public: public:
TelegramSendPhoto(const QVariant &chatId, TelegramSendPhoto(const TelegramArgs &args,
const QString &text,
const QString &fileName, const QString &fileName,
const QByteArray& data, const QByteArray& data,
unsigned long long replyToMessageId = 0, const ExtraJsonObjects& extraObjects = {}
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects = {}
); );
TelegramSendPhoto(const QVariant &chatId, TelegramSendPhoto(const TelegramArgs &args,
const QString &text,
const QFileInfo &file, const QFileInfo &file,
unsigned long long replyToMessageId = 0, const ExtraJsonObjects& extraObjects = {}
const QMap<QString, QSharedPointer<QJsonObject>>& extraObjects = {}
); );
}; };

@ -17,7 +17,8 @@ namespace qTbot {
TelegramSingleRquest::TelegramSingleRquest(const QString& request, TelegramSingleRquest::TelegramSingleRquest(const QString& request,
const QMap<QString, QVariant>& args) { const QMap<QString, QVariant>& args) {
setRequest(request); setRequest(request);
setArgs(args);} setArgs(args);
}
TelegramSingleRquest::TelegramSingleRquest(const QString &request) { TelegramSingleRquest::TelegramSingleRquest(const QString &request) {
setRequest(request); setRequest(request);

@ -126,7 +126,7 @@ public:
* @brief setProcessed This method sets new list of processed mesages. * @brief setProcessed This method sets new list of processed mesages.
* @param newProcessed list of processed messagees. * @param newProcessed list of processed messagees.
*/ */
void setProcessed(const QSet<unsigned long long> &newProcessed); virtual void setProcessed(const QSet<unsigned long long> &newProcessed);
protected: protected:

@ -20,6 +20,11 @@
namespace qTbot { namespace qTbot {
/**
* @brief ExtraJsonObjects hash map of the extra objects of the message.
*/
typedef QHash<QString, QSharedPointer<QJsonObject>> ExtraJsonObjects;
/** /**
* @brief The iRequest class Is main interface for all custom requests. * @brief The iRequest class Is main interface for all custom requests.
* @see IBot::sendRequest * @see IBot::sendRequest

@ -10,6 +10,7 @@
#include "file.h" #include "file.h"
#include "requests/telegrammdownloadfile.h" #include "requests/telegrammdownloadfile.h"
#include "qdir.h" #include "qdir.h"
#include "requests/telegramsendcontact.h"
#include "requests/telegramsenddocument.h" #include "requests/telegramsenddocument.h"
#include "virtualfile.h" #include "virtualfile.h"
#include <QNetworkAccessManager> #include <QNetworkAccessManager>
@ -21,6 +22,7 @@
#include <requests/telegrameditmessage.h> #include <requests/telegrameditmessage.h>
#include <requests/telegramsendlocation.h> #include <requests/telegramsendlocation.h>
#include <requests/telegramsendphoto.h> #include <requests/telegramsendphoto.h>
#include <requests/telegrameditmessagereplymarkup.h>
#include <QNetworkReply> #include <QNetworkReply>
#include <QSharedPointer> #include <QSharedPointer>
@ -65,57 +67,27 @@ bool ITelegramBot::login(const QByteArray &token) {
} }
bool ITelegramBot::sendMessage(const QVariant &chatId, const QString &text) { bool ITelegramBot::sendMessage(const QVariant &chatId, const QString &text) {
return sendSpecificMessage(chatId.toLongLong(), text); return sendSpecificMessage(TelegramArgs{chatId, text});
} }
bool ITelegramBot::sendSpecificMessage(const QVariant & chatId, bool ITelegramBot::sendSpecificMessage(const TelegramArgs& args,
const QString &text, const ExtraJsonObjects &extraObjects) {
const QMap<QString, QSharedPointer<QJsonObject>> &extraObjects,
const QString &callBackQueryId,
unsigned long long replyToMessageId,
bool markdown,
bool disableWebPagePreview) {
if (!chatId.isValid() || chatId.isNull()) if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (text.isEmpty()) { if (args.text.isEmpty()) {
return false; return false;
} }
auto msg = QSharedPointer<TelegramSendMsg>::create(chatId, auto msg = QSharedPointer<TelegramSendMsg>::create(args, extraObjects);
text,
extraObjects,
replyToMessageId,
markdown,
callBackQueryId,
disableWebPagePreview);
return bool(sendRequest(msg)); return sendMessageRequest(msg, args.msgIdCB);
} }
bool ITelegramBot::sendSpecificMessageWithKeyboard(const QVariant &chatId, bool ITelegramBot::sendSpecificMessageWithKeyboard(const TelegramArgs& args,
const QString &text, const KeyboardOnMessage &keyboard) {
const QList<QList<QString>> &keyboard, return sendSpecificMessage(args, prepareInlineKeyBoard(keyboard));
const QString &callBackQueryId,
bool onTimeKeyboard,
bool autoResizeKeyboard,
unsigned long long replyToMessageId,
bool markdown,
bool disableWebPagePreview) {
if (!chatId.isValid() || chatId.isNull())
return false;
auto msg = QSharedPointer<TelegramSendMsg>::create(chatId,
text,
prepareKeyboard(autoResizeKeyboard, onTimeKeyboard, keyboard),
replyToMessageId,
markdown,
callBackQueryId,
disableWebPagePreview);
return bool(sendRequest(msg));
} }
bool ITelegramBot::deleteMessage(const QVariant &chatId, const QVariant &messageId) { bool ITelegramBot::deleteMessage(const QVariant &chatId, const QVariant &messageId) {
@ -128,42 +100,34 @@ bool ITelegramBot::deleteMessage(const QVariant &chatId, const QVariant &message
auto msg = QSharedPointer<TelegramDeleteMessage>::create(chatId, auto msg = QSharedPointer<TelegramDeleteMessage>::create(chatId,
messageId); messageId);
return bool(sendRequest(msg)); return sendMessageRequest(msg);
} }
bool ITelegramBot::editSpecificMessageWithKeyboard(const QVariant & messageId, bool ITelegramBot::editSpecificMessageWithKeyboard(const QVariant &messageId,
const QVariant &chatId, const TelegramArgs& args,
const QString &newText, const QList<QList<QString> > &keyboard,
bool markdown,
bool disableWebPagePreview,
const QList<QList<QString>> &keyboard,
const QString &callBackQueryId,
bool onTimeKeyboard, bool onTimeKeyboard,
bool autoResizeKeyboard) { bool autoResizeKeyboard) {
if (!chatId.isValid() || chatId.isNull()) if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (!messageId.isValid() || messageId.isNull()) if (!messageId.isValid() || messageId.isNull())
return false; return false;
auto msg = QSharedPointer<TelegramEditMessage>::create(messageId, auto msg = QSharedPointer<TelegramEditMessage>::create(messageId,
chatId, args,
newText,
markdown,
disableWebPagePreview,
callBackQueryId,
prepareKeyboard(autoResizeKeyboard, prepareKeyboard(autoResizeKeyboard,
onTimeKeyboard, onTimeKeyboard,
keyboard)); keyboard));
return bool(sendRequest(msg)); return sendMessageRequest(msg, args.msgIdCB);
} }
QMap<QString, QSharedPointer<QJsonObject>> ExtraJsonObjects
qTbot::ITelegramBot::prepareInlineKeyBoard(const QList<QMap<QString, std::function<void (const QString &, const QVariant &)> > > &keyboard) qTbot::ITelegramBot::prepareInlineKeyBoard(const KeyboardOnMessage &keyboard)
{ {
QMap<QString, QSharedPointer<QJsonObject>> extraObjects; ExtraJsonObjects extraObjects;
auto&& keyboardJson = QSharedPointer<QJsonObject>::create(); auto&& keyboardJson = QSharedPointer<QJsonObject>::create();
QJsonArray keyboardArray; QJsonArray keyboardArray;
@ -185,11 +149,11 @@ qTbot::ITelegramBot::prepareInlineKeyBoard(const QList<QMap<QString, std::functi
return extraObjects; return extraObjects;
} }
QMap<QString, QSharedPointer<QJsonObject>> ExtraJsonObjects
qTbot::ITelegramBot::prepareKeyboard(bool autoResizeKeyboard, qTbot::ITelegramBot::prepareKeyboard(bool autoResizeKeyboard,
bool onTimeKeyboard, bool onTimeKeyboard,
const QList<QList<QString>> &keyboard) { const QList<QList<QString>> &keyboard) {
QMap<QString, QSharedPointer<QJsonObject>> extraObjects; ExtraJsonObjects extraObjects;
auto&& keyboardJson = QSharedPointer<QJsonObject>::create(); auto&& keyboardJson = QSharedPointer<QJsonObject>::create();
QJsonArray keyboardArray; QJsonArray keyboardArray;
@ -213,84 +177,76 @@ qTbot::ITelegramBot::prepareKeyboard(bool autoResizeKeyboard,
return extraObjects; return extraObjects;
} }
bool ITelegramBot::editSpecificMessageWithKeyboard(const QVariant &messageId, bool ITelegramBot::editSpecificMessageWithKeyboard(const QVariant& messageId,
const QVariant &chatId, const TelegramArgs& args,
const QString &text,
bool markdown,
bool disableWebPagePreview,
const KeyboardOnMessage &keyboard,
const QString &callBackQueryId) {
if (!chatId.isValid() || chatId.isNull()) const KeyboardOnMessage &keyboard ) {
if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (!messageId.isValid() || messageId.isNull()) if (!messageId.isValid() || messageId.isNull())
return false; return false;
auto msg = QSharedPointer<TelegramEditMessage>::create(messageId, auto msg = QSharedPointer<TelegramEditMessage>::create(messageId,
chatId, args,
text,
markdown,
disableWebPagePreview,
callBackQueryId,
prepareInlineKeyBoard(keyboard)); prepareInlineKeyBoard(keyboard));
return bool(sendRequest(msg)); return sendMessageRequest(msg);
} }
bool ITelegramBot::editSpecificMessage(const QVariant &messageId, bool ITelegramBot::editMessageKeyboard(const QVariant &messageId,
const QVariant &chatId, const QVariant &chatId,
const QString& newText, const KeyboardOnMessage &keyboard,
const QString &callBackQueryId, const QString &callBackQueryId) {
bool markdown,
bool disableWebPagePreview) {
if (!chatId.isValid() || chatId.isNull()) if (!chatId.isValid() || chatId.isNull())
return false; return false;
if (!messageId.isValid() || messageId.isNull()) if (!messageId.isValid() || messageId.isNull())
return false; return false;
if (newText.isEmpty()) auto msg = QSharedPointer<TelegramEditMessageReplyMarkup>::create(messageId,
TelegramArgs(chatId, "", 0, "html", false, callBackQueryId),
prepareInlineKeyBoard(keyboard));
return sendMessageRequest(msg);
}
bool ITelegramBot::editSpecificMessage(const QVariant &messageId,
const TelegramArgs& args) {
if (!args.chatId.isValid() || args.chatId.isNull())
return false;
if (!messageId.isValid() || messageId.isNull())
return false;
if (args.text.isEmpty())
return false; return false;
auto msg = QSharedPointer<TelegramEditMessage>::create(messageId, auto msg = QSharedPointer<TelegramEditMessage>::create(messageId,
chatId, args
newText,
markdown,
disableWebPagePreview,
callBackQueryId
); );
return bool(sendRequest(msg)); return sendMessageRequest(msg);
} }
bool ITelegramBot::sendSpecificMessageWithKeyboard(const QVariant &chatId, bool ITelegramBot::sendSpecificMessageWithKeyboard(const TelegramArgs& args,
const QString &text, const QList<QList<QString> > &keyboard,
const KeyboardOnMessage &keyboard, bool onTimeKeyboard,
const QString &callBackQueryId, bool autoResizeKeyboard) {
unsigned long long replyToMessageId,
bool markdown,
bool disableWebPagePreview) {
if (!chatId.isValid() || chatId.isNull()) if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (text.isEmpty()) { if (args.text.isEmpty()) {
return false; return false;
} }
auto msg = QSharedPointer<TelegramSendMsg>::create(chatId, return sendSpecificMessage(args, prepareKeyboard(autoResizeKeyboard, onTimeKeyboard, keyboard));
text,
prepareInlineKeyBoard(keyboard),
replyToMessageId,
markdown,
callBackQueryId,
disableWebPagePreview);
return bool(sendRequest(msg));
} }
QSharedPointer<iFile> ITelegramBot::getFile(const QString &fileId, iFile::Type fileType) { QSharedPointer<iFile> ITelegramBot::getFile(const QString &fileId, iFile::Type fileType) {
@ -376,57 +332,28 @@ QSharedPointer<QNetworkReply> ITelegramBot::getFileMeta(const QString &fileId, c
} }
bool ITelegramBot::sendFile(const QFileInfo &file, const QVariant &chatId) { bool ITelegramBot::sendFile(const QFileInfo &file, const QVariant &chatId) {
return sendFileWithDescription(file, chatId, ""); return sendFileMessage({chatId}, file);
} }
bool ITelegramBot::sendFile(const QByteArray &file, const QString &fileName, const QVariant &chatId) { bool ITelegramBot::sendFile(const QByteArray &file, const QString &fileName, const QVariant &chatId) {
return sendFileWithDescription(file, fileName, chatId, ""); return sendFileMessage({chatId}, file, fileName);
} }
bool ITelegramBot::sendPhoto(const QFileInfo &photo, bool ITelegramBot::sendFileMessage(const TelegramArgs &args, const QFileInfo &file) {
const QVariant &chatId, if (!args.chatId.isValid() || args.chatId.isNull())
const QString &description,
unsigned long long replyToMessageId,
const KeyboardOnMessage &keyboard) {
if (!chatId.isValid() || chatId.isNull())
return false; return false;
if (!photo.isReadable()) { if (!file.isReadable()) {
return false; return false;
} }
return sendFileWithPrivate(QSharedPointer<TelegramSendPhoto>::create( return sendMessageRequest(
chatId, description, photo, replyToMessageId, prepareInlineKeyBoard(keyboard))); QSharedPointer<TelegramSendPhoto>::create(args,
file), args.msgIdCB);
} }
bool ITelegramBot::sendPhoto(const QByteArray &photo, bool ITelegramBot::sendFileMessage(const TelegramArgs &args, const QByteArray &file, const QString &fileName) {
const QString &fileName, if (!args.chatId.isValid() || args.chatId.isNull())
const QVariant &chatId,
const QString &description,
unsigned long long replyToMessageId,
const KeyboardOnMessage &keyboard) {
if (!chatId.isValid() || chatId.isNull())
return false;
if (!fileName.size()) {
return false;
}
if (!photo.size()) {
return false;
}
return sendFileWithPrivate(QSharedPointer<TelegramSendPhoto>::create(
chatId, description, fileName, photo, replyToMessageId, prepareInlineKeyBoard(keyboard)));
}
bool ITelegramBot::sendFileWithDescription(const QByteArray &file,
const QString &fileName,
const QVariant &chatId,
const QString &description) {
if (!chatId.isValid() || chatId.isNull())
return false; return false;
if (!fileName.size()) { if (!fileName.size()) {
@ -437,20 +364,48 @@ bool ITelegramBot::sendFileWithDescription(const QByteArray &file,
return false; return false;
} }
return sendFileWithPrivate(QSharedPointer<TelegramSendDocument>::create(chatId, description, fileName, file)); return sendMessageRequest(QSharedPointer<TelegramSendDocument>::create(args, fileName, file), args.msgIdCB);
} }
bool ITelegramBot::sendFileWithDescription(const QFileInfo &file, bool ITelegramBot::sendPhoto(const TelegramArgs &args,
const QVariant &chatId, const QFileInfo &photo,
const QString &description) { const KeyboardOnMessage &keyboard) {
if (!chatId.isValid() || chatId.isNull()) if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (!file.isReadable()) { if (!photo.isReadable()) {
return false; return false;
} }
return sendFileWithPrivate(QSharedPointer<TelegramSendDocument>::create(chatId, description, file)); return sendMessageRequest(
QSharedPointer<TelegramSendPhoto>::create(args,
photo,
prepareInlineKeyBoard(keyboard)), args.msgIdCB);
}
bool ITelegramBot::sendPhoto(const TelegramArgs &args,
const QByteArray &photo,
const QString &fileName,
const KeyboardOnMessage &keyboard) {
if (!args.chatId.isValid() || args.chatId.isNull()) {
return false;
}
if (!fileName.size()) {
return false;
}
if (!photo.size()) {
return false;
}
return sendMessageRequest(
QSharedPointer<TelegramSendPhoto>::create(args,
fileName,
photo,
prepareInlineKeyBoard(keyboard)),
args.msgIdCB);
} }
bool ITelegramBot::sendFileById(const QString &fileID, const QVariant &chatId) { bool ITelegramBot::sendFileById(const QString &fileID, const QVariant &chatId) {
@ -463,21 +418,35 @@ bool ITelegramBot::sendFileById(const QString &fileID, const QVariant &chatId) {
} }
bool ITelegramBot::sendLocation(const QVariant &chatId, bool ITelegramBot::sendLocation(const TelegramArgs &args,
const QString &text,
float latitude, float latitude,
float longitude, float longitude,
unsigned long long replyToMessageId) { const KeyboardOnMessage &keyboard) {
if (!chatId.isValid() || chatId.isNull())
if (!args.chatId.isValid() || args.chatId.isNull())
return false; return false;
if (!(longitude && latitude)) { if (!(longitude && latitude)) {
return false; return false;
} }
auto&& request = QSharedPointer<TelegramSendLocation>::create(chatId, text, latitude, longitude, replyToMessageId); return sendMessageRequest(QSharedPointer<TelegramSendLocation>::create(args,
latitude,
longitude,
prepareInlineKeyBoard(keyboard)));
}
return bool(sendRequest(request)); bool ITelegramBot::sendContact(const TelegramArgs &args,
const QString &phone,
const QString &firstName,
const QString &secondName) {
if (!args.chatId.isValid() || args.chatId.isNull())
return false;
return sendMessageRequest(QSharedPointer<TelegramSendContact>::create(args,
firstName,
phone,
secondName));
} }
int ITelegramBot::getFileSizeByUniqueId(const QString &id) const { int ITelegramBot::getFileSizeByUniqueId(const QString &id) const {
@ -514,6 +483,36 @@ void ITelegramBot::handleIncomeNewUpdate(const QSharedPointer<iUpdate> & update)
} }
} }
bool ITelegramBot::sendMessageRequest(const QSharedPointer<iRequest> &rquest,
const std::function<void (int)> &msgIdCB) {
auto&& reply = IBot::sendRequest(rquest);
if (reply) {
connect(reply.get(), &QNetworkReply::finished, this,
[ reply, msgIdCB, this]() {
if (reply->error() == QNetworkReply::NoError) {
QByteArray&& responseData = reply->readAll();
QJsonDocument json = QJsonDocument::fromJson(responseData);
const QJsonObject&& obj = json.object();
if (obj.contains("result")) {
unsigned long long chatId = obj["result"]["chat"]["id"].toInteger();
int messageID = obj["result"]["message_id"].toInt();
if (msgIdCB) {
msgIdCB(messageID);
}
if (chatId) {
_lastMessageId[chatId] = messageID;
}
}
}
});
}
return bool(reply);
}
void ITelegramBot::handleLogin() { void ITelegramBot::handleLogin() {
if (_loginReplay) { if (_loginReplay) {
@ -562,10 +561,6 @@ void ITelegramBot::handleFileHeader(const QWeakPointer<QNetworkReply> &sender,
} }
} }
bool ITelegramBot::sendFileWithPrivate(const QSharedPointer<TelegramSendFile> &file) {
return bool(sendRequest(file));
}
QString ITelegramBot::findFileInlocatStorage(const QString &fileId) const { QString ITelegramBot::findFileInlocatStorage(const QString &fileId) const {
QDir defaultFileDir(defaultFileStorageLocation()); QDir defaultFileDir(defaultFileStorageLocation());
@ -596,6 +591,10 @@ const QString &ITelegramBot::username() const {
return _username; return _username;
} }
int ITelegramBot::gelLastMessageId(unsigned long long &chatId) const {
return _lastMessageId.value(chatId, 0);
}
unsigned long long ITelegramBot::id() const { unsigned long long ITelegramBot::id() const {
return _id; return _id;
} }

@ -11,6 +11,7 @@
#define ITELEGRAMBOT_H #define ITELEGRAMBOT_H
#include "ibot.h" #include "ibot.h"
#include "qTbot/telegramargs.h"
#include <QObject> #include <QObject>
class QNetworkAccessManager; class QNetworkAccessManager;
@ -22,9 +23,10 @@ class ITelegramMessage;
class TelegramFile; class TelegramFile;
class TelegramUpdateAnswer; class TelegramUpdateAnswer;
class TelegramSendFile; class TelegramSendFile;
class TelegramSingleRquest;
typedef std::function<void(const QString& buttonKey, const QVariant& msgID)> ButtonCB; typedef std::function<void(const QString& buttonKey, const QVariant& msgID)> ButtonCB;
typedef QList<QMap<QString, ButtonCB >> KeyboardOnMessage; typedef QList<QHash<QString, ButtonCB >> KeyboardOnMessage;
/** /**
* @brief The ITelegramBot class This is base implementation of the all telegramm bots. * @brief The ITelegramBot class This is base implementation of the all telegramm bots.
@ -44,89 +46,50 @@ public:
* @brief Sends a specific message to a chat. * @brief Sends a specific message to a chat.
* *
* This function sends a specific message to a chat. You can include text and additional objects as needed to customize the message's content and behavior. * This function sends a specific message to a chat. You can include text and additional objects as needed to customize the message's content and behavior.
* * @param args - This is structure with general arguments of the tellegram message.
* @param chatId The unique identifier of the chat to send the message to. * Use This structure for sets target and another arguments.
* @param text The text content of the message to be sent.
* @param extraObjects A map containing additional objects associated with the message (optional). * @param extraObjects A map containing additional objects associated with the message (optional).
* @param callBackQueryId The unique identifier for callback queries triggered by the message (optional).
* @param replyToMessageId The unique identifier of the message to reply to, if any (optional).
* @param markdown Set to true to enable Markdown formatting for the text (optional).
* @param disableWebPagePreview Set to true to disable web page previews for links in the message (optional).
* *
* @return Returns true if the message was sent successfully, false otherwise. * @return Returns true if the message was sent successfully, false otherwise.
* *
* @note The extraObjects parameter is a map where each key represents the object's name, and the associated value is a shared pointer to a JSON object (optional). * @note The extraObjects parameter is a map where each key represents the object's name, and the associated value is a shared pointer to a JSON object (optional).
* @note The callBackQueryId parameter is used to handle callback queries when applicable (optional).
* @note By default, the message will be sent with Markdown formatting enabled (optional).
* @note By default, web page previews for links in the message are not disabled (optional).
*/ */
bool sendSpecificMessage(const QVariant &chatId, bool sendSpecificMessage(const TelegramArgs& args,
const QString& text, const qTbot::ExtraJsonObjects &extraObjects = {});
const QMap<QString, QSharedPointer<QJsonObject> > &extraObjects = {},
const QString &callBackQueryId = {},
unsigned long long replyToMessageId = 0,
bool markdown = true,
bool disableWebPagePreview = false);
/** /**
* @brief Sends a specific message with a custom keyboard to a chat. * @brief Sends a specific message with a custom keyboard to a chat.
*
* This function sends a specific message to a chat with a custom keyboard. The message can contain text and additional settings to customize its behavior. * This function sends a specific message to a chat with a custom keyboard. The message can contain text and additional settings to customize its behavior.
* * @param args - This is structure with general arguments of the tellegram message.
* @param chatId The unique identifier of the chat to send the message to. * Use This structure for sets target and another arguments.
* @param text The text content of the message to be sent.
* @param keyboard A list of maps where each map represents a button with a callback function. * @param keyboard A list of maps where each map represents a button with a callback function.
* @param callBackQueryId The unique identifier for callback queries triggered by the message (optional).
* @param replyToMessageId The unique identifier of the message to reply to, if any (optional).
* @param markdown Set to true to enable Markdown formatting for the text (optional).
* @param disableWebPagePreview Set to true to disable web page previews for links in the message (optional).
*
* @return Returns true if the message was sent successfully, false otherwise. * @return Returns true if the message was sent successfully, false otherwise.
* *
* @note The keyboard parameter should be a list of maps where each map represents a button. The button's label is the map key, and the associated callback function is the map value. * @note The keyboard parameter should be a list of maps where each map represents a button.
* @note The callBackQueryId parameter is used to handle callback queries when buttons are pressed (optional). * The button's label is the map key, and the associated callback function is the map value.
* @note By default, the message will be sent with Markdown formatting enabled (optional).
* @note By default, web page previews for links in the message are not disabled (optional).
*/ */
bool sendSpecificMessageWithKeyboard(const QVariant &chatId, bool sendSpecificMessageWithKeyboard(const TelegramArgs& args,
const QString& text, const KeyboardOnMessage &keyboard);
const KeyboardOnMessage &keyboard,
const QString &callBackQueryId = "",
unsigned long long replyToMessageId = 0,
bool markdown = true,
bool disableWebPagePreview = false);
/** /**
* @brief Sends a specific message with a custom keyboard to a chat. * @brief Sends a specific message with a custom keyboard to a chat.
* *
* This function sends a specific message to a chat with a custom keyboard. The message can contain text and additional settings to customize its behavior. * This function sends a specific message to a chat with a custom keyboard.
* * The message can contain text and additional settings to customize its behavior.
* @param chatId The unique identifier of the chat to send the message to. * @param args - This is structure with general arguments of the tellegram message.
* @param text The text content of the message to be sent. * Use This structure for sets target and another arguments.
* @param keyboard A list of lists containing the keyboard buttons to display. * @param keyboard A list of lists containing the keyboard buttons to display.
* @param callBackQueryId The unique identifier for callback queries triggered by the message.
* @param onTimeKeyboard Set to true to display the keyboard only once. * @param onTimeKeyboard Set to true to display the keyboard only once.
* @param autoResizeKeyboard Set to true to automatically resize the keyboard. * @param autoResizeKeyboard Set to true to automatically resize the keyboard.
* @param replyToMessageId The unique identifier of the message to reply to, if any.
* @param markdown Set to true to enable Markdown formatting for the text.
* @param disableWebPagePreview Set to true to disable web page previews for links in the message.
* *
* @return Returns true if the message was sent successfully, false otherwise. * @return Returns true if the message was sent successfully, false otherwise.
* *
* @note The keyboard parameter should be a list of lists of strings representing keyboard buttons.
* @note The callBackQueryId parameter is used to handle callback queries when buttons are pressed.
* @note By default, the message will be sent with Markdown formatting enabled.
* @note By default, web page previews for links in the message are not disabled. * @note By default, web page previews for links in the message are not disabled.
*/ */
bool sendSpecificMessageWithKeyboard(const QVariant &chatId, bool sendSpecificMessageWithKeyboard(const TelegramArgs& args,
const QString& text,
const QList<QList<QString> > &keyboard, const QList<QList<QString> > &keyboard,
const QString &callBackQueryId = "",
bool onTimeKeyboard = false, bool onTimeKeyboard = false,
bool autoResizeKeyboard = true, bool autoResizeKeyboard = true);
unsigned long long replyToMessageId = 0,
bool markdown = true,
bool disableWebPagePreview = false);
bool deleteMessage(const QVariant& chatId, const QVariant& messageId) override; bool deleteMessage(const QVariant& chatId, const QVariant& messageId) override;
@ -134,44 +97,49 @@ public:
* @brief Edits a specific message with a custom keyboard in a chat. * @brief Edits a specific message with a custom keyboard in a chat.
* *
* This function allows you to edit a specific message in a chat with a custom keyboard. You can update the message's text and customize its behavior as needed. * This function allows you to edit a specific message in a chat with a custom keyboard. You can update the message's text and customize its behavior as needed.
* * @param args - This is structure with general arguments of the tellegram message.
* Use This structure for sets target and another arguments.
* @param messageId The unique identifier of the message to edit. * @param messageId The unique identifier of the message to edit.
* @param chatId The unique identifier of the chat containing the message.
* @param newText The new text content for the message.
* @param markdown Set to true to enable Markdown formatting for the new text (optional).
* @param disableWebPagePreview Set to true to disable web page previews for links in the new text (optional).
* @param keyboard A list of lists containing the new keyboard buttons to display (optional). * @param keyboard A list of lists containing the new keyboard buttons to display (optional).
* @param callBackQueryId The unique identifier for callback queries triggered by the edited message (optional).
* @param onTimeKeyboard Set to true to display the keyboard only once (optional). * @param onTimeKeyboard Set to true to display the keyboard only once (optional).
* @param autoResizeKeyboard Set to true to automatically resize the keyboard (optional). * @param autoResizeKeyboard Set to true to automatically resize the keyboard (optional).
* *
* @return Returns true if the message was successfully edited, false otherwise. * @return Returns true if the message was successfully edited, false otherwise.
* *
* @note The keyboard parameter should be a list of lists of strings representing keyboard buttons (optional).
* @note The callBackQueryId parameter is used to handle callback queries when buttons are pressed (optional).
* @note By default, the new text will be displayed with Markdown formatting enabled (optional).
* @note By default, web page previews for links in the new text are not disabled (optional). * @note By default, web page previews for links in the new text are not disabled (optional).
*/ */
bool editSpecificMessageWithKeyboard(const QVariant &messageId, bool editSpecificMessageWithKeyboard(const QVariant &messageId,
const QVariant &chatId, const TelegramArgs& args,
const QString &newText,
bool markdown = true,
bool disableWebPagePreview = false,
const QList<QList<QString> > &keyboard = {}, const QList<QList<QString> > &keyboard = {},
const QString &callBackQueryId = "",
bool onTimeKeyboard = false, bool onTimeKeyboard = false,
bool autoResizeKeyboard = false); bool autoResizeKeyboard = false);
/** /**
* @brief Edits a specific message with a custom keyboard in a chat. * @brief Edits a specific message with a custom keyboard in a chat.
* *
* This function allows you to edit a specific message in a chat with a custom keyboard. You can update the message's text and customize its behavior as needed. * This function allows you to edit a specific message in a chat with a custom keyboard. You can update the message's text and customize its behavior as needed.
* *
* @param messageId The unique identifier of the message to edit. * @param messageId The unique identifier of the message to edit.
* @param args - This is structure with general arguments of the tellegram message.
* Use This structure for sets target and another arguments.
* @param keyboard A list of maps where each map represents a button with a callback function (optional).
*
* @return Returns true if the message was successfully edited, false otherwise.
*
* @note By default, web page previews for links in the new text are not disabled (optional).
*/
bool editSpecificMessageWithKeyboard(const QVariant& messageId,
const TelegramArgs& args,
const KeyboardOnMessage &keyboard = {});
/**
* @brief Edits a keyboard of message in a chat.
*
* This function allows you to edit a keyboard of specific message.
*
* @param messageId The unique identifier of the message to edit.
* @param chatId The unique identifier of the chat containing the message. * @param chatId The unique identifier of the chat containing the message.
* @param text The new text content for the message.
* @param markdown Set to true to enable Markdown formatting for the new text (optional).
* @param disableWebPagePreview Set to true to disable web page previews for links in the new text (optional).
* @param keyboard A list of maps where each map represents a button with a callback function (optional). * @param keyboard A list of maps where each map represents a button with a callback function (optional).
* @param callBackQueryId The unique identifier for callback queries triggered by the edited message (optional). * @param callBackQueryId The unique identifier for callback queries triggered by the edited message (optional).
* *
@ -179,16 +147,12 @@ public:
* *
* @note The keyboard parameter should be a list of maps where each map represents a button. The button's label is the map key, and the associated callback function is the map value (optional). * @note The keyboard parameter should be a list of maps where each map represents a button. The button's label is the map key, and the associated callback function is the map value (optional).
* @note The callBackQueryId parameter is used to handle callback queries when buttons are pressed (optional). * @note The callBackQueryId parameter is used to handle callback queries when buttons are pressed (optional).
* @note By default, the new text will be displayed with Markdown formatting enabled (optional).
* @note By default, web page previews for links in the new text are not disabled (optional). * @note By default, web page previews for links in the new text are not disabled (optional).
*/ */
bool editSpecificMessageWithKeyboard(const QVariant& messageId, bool editMessageKeyboard(const QVariant& messageId,
const QVariant &chatId, const QVariant &chatId,
const QString &text, const KeyboardOnMessage &keyboard = {},
bool markdown = true, const QString &callBackQueryId = "");
bool disableWebPagePreview = false,
const KeyboardOnMessage &keyboard = {},
const QString &callBackQueryId = "");
/** /**
* @brief Edits a specific message in a chat. * @brief Edits a specific message in a chat.
@ -196,24 +160,14 @@ public:
* This function allows you to edit a specific message in a chat. You can update the message's text and customize its behavior as needed. * This function allows you to edit a specific message in a chat. You can update the message's text and customize its behavior as needed.
* *
* @param messageId The unique identifier of the message to edit. * @param messageId The unique identifier of the message to edit.
* @param chatId The unique identifier of the chat containing the message. * @param args - This is structure with general arguments of the tellegram message.
* @param newText The new text content for the message. * Use This structure for sets target and another arguments.
* @param callBackQueryId The unique identifier for callback queries triggered by the edited message (optional).
* @param markdown Set to true to enable Markdown formatting for the new text (optional).
* @param disableWebPagePreview Set to true to disable web page previews for links in the new text (optional).
*
* @return Returns true if the message was successfully edited, false otherwise. * @return Returns true if the message was successfully edited, false otherwise.
* *
* @note The callBackQueryId parameter is used to handle callback queries when applicable (optional).
* @note By default, the new text will be displayed with Markdown formatting enabled (optional).
* @note By default, web page previews for links in the new text are not disabled (optional). * @note By default, web page previews for links in the new text are not disabled (optional).
*/ */
bool editSpecificMessage(const QVariant &messageId, bool editSpecificMessage(const QVariant &messageId,
const QVariant &chatId, const TelegramArgs& args);
const QString &newText,
const QString &callBackQueryId = {},
bool markdown = true,
bool disableWebPagePreview = false);
[[nodiscard("do not forget to save shared pointer of file handler, because it's will not save inner bot object.")]] [[nodiscard("do not forget to save shared pointer of file handler, because it's will not save inner bot object.")]]
QSharedPointer<iFile> getFile(const QString& fileId, iFile::Type fileType = iFile::Type::Ram) override; QSharedPointer<iFile> getFile(const QString& fileId, iFile::Type fileType = iFile::Type::Ram) override;
@ -231,59 +185,49 @@ public:
bool sendFile( const QByteArray& file, const QString& fileName, const QVariant& chatId) override; bool sendFile( const QByteArray& file, const QString& fileName, const QVariant& chatId) override;
/**
* @brief sendFileMessage This method sents a message with file.
* @param file This is path to sents file.
* @param args This is general arguments of the message, include a chatID.
* @return true if the message sents successful else false
*/
bool sendFileMessage( const TelegramArgs& args, const QFileInfo& file);
/**
* @brief sendFileMessage This method sents a message with file.
* @param file This is data that will be sents as a file with name @a fileName.
* @param fileName This is name of the file.
* @param args This is general arguments of the message, include a chatID.
* @return true if the message sents successful else false
*/
bool sendFileMessage( const TelegramArgs& args, const QByteArray& file, const QString& fileName);
/** /**
* @brief sendPhoto This method will send image into chat with @a chatId * @brief sendPhoto This method will send image into chat with @a chatId
* @param args - This is structure with general arguments of the tellegram message.
* Use This structure for sets target and another arguments.
* @param photo this is photo path. * @param photo this is photo path.
* @param chatId target chat
* @param replyToMessageId The unique identifier of the message to reply to, if any.
* @param keyboard A list of maps where each map represents a button with a callback function (optional). * @param keyboard A list of maps where each map represents a button with a callback function (optional).
* @return true if photo will snt successful * @return true if photo will snt successful
*/ */
bool sendPhoto(const QFileInfo& photo, bool sendPhoto(const TelegramArgs& args,
const QVariant& chatId, const QFileInfo& photo,
const QString &description,
unsigned long long replyToMessageId = 0,
const KeyboardOnMessage &keyboard = {}); const KeyboardOnMessage &keyboard = {});
/** /**
* @brief sendPhoto This method will send image into chat with @a chatId * @brief sendPhoto This method will send image into chat with @a chatId
* @param photo this is photo data. * @param photo this is photo data.
* @param chatId target chat * @param args - This is structure with general arguments of the tellegram message.
* Use This structure for sets target and another arguments.
* @param fileName This is dispalyed name of photo. * @param fileName This is dispalyed name of photo.
* @param replyToMessageId The unique identifier of the message to reply to, if any.
* @param keyboard A list of maps where each map represents a button with a callback function (optional). * @param keyboard A list of maps where each map represents a button with a callback function (optional).
* @return true if photo will snt successful * @return true if photo will snt successful
*/ */
bool sendPhoto(const QByteArray& photo, bool sendPhoto(const TelegramArgs &args,
const QByteArray& photo,
const QString& fileName, const QString& fileName,
const QVariant& chatId,
const QString &description,
unsigned long long replyToMessageId = 0,
const KeyboardOnMessage &keyboard = {}); const KeyboardOnMessage &keyboard = {});
/**
* @brief sendFileWithDescription This method sents a byte array as a file into @a chatId with additional text @a description.
* @param file This is a file source
* @param fileName This is a dispalyed name of file.
* @param chatId This is distanation id chat.
* @param description additional text for message.
* @return true if the message sents successful else false.
*/
bool sendFileWithDescription(const QByteArray& file,
const QString& fileName,
const QVariant& chatId,
const QString& description);
/**
* @brief sendFileWithDescription This method sents a byte array as a file into @a chatId with additional text @a description.
* @param file This is a file source
* @param chatId This is distanation id chat.
* @param description additional text for message.
* @return true if the message sents successful else false.
*/
bool sendFileWithDescription( const QFileInfo& file,
const QVariant& chatId,
const QString& description);
/** /**
* @brief sendFileById This is specific method of the telegram bot. sents file by id. * @brief sendFileById This is specific method of the telegram bot. sents file by id.
* @param fileID This is file id. * @param fileID This is file id.
@ -294,27 +238,38 @@ public:
/** /**
* @brief sendLocation This method sents locatin to user. * @brief sendLocation This method sents locatin to user.
* @param chatId This is distanation id chat. * @param args - This is structure with general arguments of the tellegram message.
* Use This structure for sets target and another arguments.
* @param latitude * @param latitude
* @param longitude * @param longitude
* @param replyToMessageId The unique identifier of the message to reply to, skip if you want to sent new independet message. * @param keyboard A list of maps where each map represents a button with a callback function (optional).
* @return true if locations sent successful else false * @return true if locations sent successful else false
*/ */
bool sendLocation(const QVariant& chatId, bool sendLocation(const TelegramArgs &args,
const QString& text,
float latitude, float latitude,
float longitude, float longitude,
unsigned long long replyToMessageId = 0); const KeyboardOnMessage &keyboard = {});
/**
* @brief sendContact This method sents a contact data.
* @param args base arguments of message.
* @param firstName This is first name of contact.
* @param phone This is phone number of contact.
* @param secondName This is second name of user.
* @return true if contact sent successful
*/
bool sendContact(const TelegramArgs &args,
const QString& phone,
const QString& firstName,
const QString& secondName = "");
// to do // to do
// * forwardMessage implementations // * forwardMessage implementations
// * copyMessage implementations // * copyMessage implementations
// * sendPhoto implementations
// * sendAudio implementations // * sendAudio implementations
// * sendVideo implementations // * sendVideo implementations
// * sendVoice implementations // * sendVoice implementations
// * sendLocation implementations
// * sendContact implementations // * sendContact implementations
// * sendPoll implementations // * sendPoll implementations
// * sendDice implementations // * sendDice implementations
@ -361,6 +316,13 @@ public:
*/ */
const QString& username() const; const QString& username() const;
/**
* @brief gelLastMessageId this method returns last sendet message id.
* @param chatId chat id, when you want to get last message id.
* @return message id.
*/
int gelLastMessageId(unsigned long long &chatId) const;
protected: protected:
/** /**
@ -399,6 +361,15 @@ protected:
void handleIncomeNewUpdate(const QSharedPointer<iUpdate> &) override; void handleIncomeNewUpdate(const QSharedPointer<iUpdate> &) override;
/**
* @brief sendMessageRequest This method invoke when bot will be sent eny messages into chat.
* @param rquest This is a message request.
* @param msgIdCB call back function for the get a sent message id
* @return true if the message sent successful else false.
*/
virtual bool sendMessageRequest(const QSharedPointer<iRequest> &rquest,
const std::function<void(int msgId)>& msgIdCB = {});
private slots: private slots:
void handleLogin(); void handleLogin();
void handleLoginErr(QNetworkReply::NetworkError err); void handleLoginErr(QNetworkReply::NetworkError err);
@ -407,23 +378,23 @@ private slots:
private: private:
bool sendFileWithPrivate(const QSharedPointer<TelegramSendFile>& file);
QString findFileInlocatStorage(const QString& fileId) const; QString findFileInlocatStorage(const QString& fileId) const;
QMap<QString, QSharedPointer<QJsonObject>> QHash<QString, QSharedPointer<QJsonObject> >
prepareInlineKeyBoard(const QList<QMap<QString, std::function<void (const QString &, const QVariant &)> > > &keyboard); prepareInlineKeyBoard(const KeyboardOnMessage &keyboard);
QMap<QString, QSharedPointer<QJsonObject>> ExtraJsonObjects prepareKeyboard(bool autoResizeKeyboard,
prepareKeyboard(bool autoResizeKeyboard, bool onTimeKeyboard, const QList<QList<QString> > &keyboard); bool onTimeKeyboard,
const QList<QList<QString> > &keyboard);
unsigned long long _id = 0; unsigned long long _id = 0;
QString _username; QString _username;
QSharedPointer<QNetworkReply> _loginReplay; QSharedPointer<QNetworkReply> _loginReplay;
QMap<QString, std::function<void(const QString&, const QVariant&)>> _handleButtons; QMap<QString, std::function<void(const QString&, const QVariant&)>> _handleButtons;
QHash<unsigned long long, int> _lastMessageId;
QHash<QString, QSharedPointer<TelegramFile>> _filesMetaInfo; QHash<QString, QSharedPointer<TelegramFile>> _filesMetaInfo;
}; };
} }
#endif // ITELEGRAMBOT_H #endif // ITELEGRAMBOT_H

@ -6,6 +6,7 @@
//# //#
#include "telegramlocation.h" #include "telegramlocation.h"
#include "qpoint.h"
namespace qTbot { namespace qTbot {
@ -25,7 +26,11 @@ double TelegramLocation::latitude() const {
} }
double TelegramLocation::longitude() const { double TelegramLocation::longitude() const {
return rawJson()["latitude"].toDouble(); return rawJson()["longitude"].toDouble();
} }
QPointF TelegramLocation::toQPoint() const {
return QPointF(latitude(), longitude());
}
} }

@ -38,6 +38,12 @@ public:
* @return float value of longitude * @return float value of longitude
*/ */
double longitude() const; double longitude() const;
/**
* @brief toQPoint This method convert location data to general qt class.
* @return location as a qt point
*/
QPointF toQPoint() const;
}; };
} }
#endif // TELEGRAMLOCATION_H #endif // TELEGRAMLOCATION_H

@ -0,0 +1,59 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#include "telegramargs.h"
namespace qTbot {
TelegramArgs::TelegramArgs(const QVariant &id,
const QString &text,
unsigned long long replyToMessageId,
const QString &parseMode,
bool disableWebPagePreview,
const QString &callBackQueryId, const std::function<void (int)> &msgIdCB)
{
this->chatId = id;
this->text = text;
this->callBackQueryId = callBackQueryId;
this->disableWebPagePreview = disableWebPagePreview;
this->replyToMessageId = replyToMessageId;
this->parseMode = parseMode;
this->msgIdCB = msgIdCB;
}
QMap<QString, QVariant> TelegramArgs::toMap(bool textAsCaption) const {
QMap<QString, QVariant> args {{"chat_id", chatId}};
if (text.size()) {
if (textAsCaption) {
args["caption"] = text;
} else {
args["text"] = text;
}
}
if (replyToMessageId) {
args["reply_to_message_id"] = replyToMessageId;
}
if (parseMode.size()) {
args["parse_mode"] = parseMode;
}
if (disableWebPagePreview) {
args["disable_web_page_preview"] = disableWebPagePreview;
}
if (callBackQueryId.size()) {
args["callback_query_id"] = callBackQueryId;
}
return args;
}
}

@ -0,0 +1,80 @@
//#
//# Copyright (C) 2023-2023 QuasarApp.
//# Distributed under the GPLv3 software license, see the accompanying
//# Everyone is permitted to copy and distribute verbatim copies
//# of this license document, but changing it is not allowed.
//#
#ifndef TELEGRAMARGS_H
#define TELEGRAMARGS_H
#include <QVariant>
#include "global.h"
namespace qTbot {
/**
* @brief The TelegramArgs class is base structure for the all tellegram message arguments.
*/
struct QTBOT_EXPORT TelegramArgs
{
TelegramArgs(const QVariant& id,
const QString& text = "",
unsigned long long replyToMessageId = 0,
const QString& parseMode = "html",
bool disableWebPagePreview = false,
const QString& callBackQueryId = "",
const std::function<void(int msgId)>& msgIdCB = {}
);
/**
* @brief Text of the message.
* Default: "".
*/
QString text = "";
/**
* @brief Chat ID where the message will be sent.
* Default: {}.
*/
QVariant chatId = {};
/**
* @brief Callback query ID.
* Default: "".
*/
QString callBackQueryId = {};
/**
* @brief ID of the message to which a reply will be given.
* Default: 0.
*/
unsigned long long replyToMessageId = 0;
/**
* @brief Parse mode of the message.
* Default: "html".
*/
QString parseMode = "html";
/**
* @brief Disable web page preview when sending links.
* Default: false.
*/
bool disableWebPagePreview = false;
/**
* @brief toMap convert all arguments to the map.
* @param textAsCaption This option force to replace text key to caption. Used on some requests as a sendDocument
* @return list of arguments.
*/
QMap<QString, QVariant> toMap(bool textAsCaption = false) const;
/**
* @brief msgIdCB This is id message call bak function. Will be inwoked when request finished successful.
*/
std::function<void(int msgId)> msgIdCB = {};
};
}
#endif // TELEGRAMARGS_H

@ -39,7 +39,7 @@ void TelegramRestBot::startUpdates() {
if (delta >= _updateDelay) { if (delta >= _updateDelay) {
auto&& replay = sendRequest(QSharedPointer<TelegramGetUpdate>::create()); auto&& replay = sendRequest(QSharedPointer<TelegramGetUpdate>::create(_lanstUpdateid + 1));
connect(replay.get(), &QNetworkReply::finished, connect(replay.get(), &QNetworkReply::finished,
this, std::bind(&TelegramRestBot::handleReceiveUpdates, this, replay.toWeakRef()), this, std::bind(&TelegramRestBot::handleReceiveUpdates, this, replay.toWeakRef()),
@ -50,9 +50,9 @@ void TelegramRestBot::startUpdates() {
Qt::DirectConnection); Qt::DirectConnection);
return; return;
} else {
QTimer::singleShot( _updateDelay - delta, this, [this](){startUpdates();});
} }
QTimer::singleShot( _updateDelay - delta, this, [this](){startUpdates();});
} }
int TelegramRestBot::updateDelay() const { int TelegramRestBot::updateDelay() const {
@ -63,6 +63,15 @@ void TelegramRestBot::setUpdateDelay(int newUpdateDelay) {
_updateDelay = newUpdateDelay; _updateDelay = newUpdateDelay;
} }
void TelegramRestBot::setProcessed(const QSet<unsigned long long> &newProcessed) {
auto&& it = std::min_element(newProcessed.begin(), newProcessed.end());
if (it != newProcessed.end()) {
_lanstUpdateid = *it;
}
IBot::setProcessed(newProcessed);
}
void TelegramRestBot::handleReceiveUpdates(const QWeakPointer<QNetworkReply> &replay) { void TelegramRestBot::handleReceiveUpdates(const QWeakPointer<QNetworkReply> &replay) {
if (auto&& sharedReplay = replay.lock()) { if (auto&& sharedReplay = replay.lock()) {
@ -75,6 +84,9 @@ void TelegramRestBot::handleReceiveUpdates(const QWeakPointer<QNetworkReply> &re
for (const auto& ref: resultArray) { for (const auto& ref: resultArray) {
auto&& update = IBot::makeMesasge<TelegramUpdate>(ref.toObject()); auto&& update = IBot::makeMesasge<TelegramUpdate>(ref.toObject());
incomeNewUpdate(update); incomeNewUpdate(update);
if (_lanstUpdateid < update->updateId()) {
_lanstUpdateid = update->updateId();
};
} }
} }
} }

@ -41,6 +41,7 @@ public:
*/ */
void setUpdateDelay(int newUpdateDelay); void setUpdateDelay(int newUpdateDelay);
void setProcessed(const QSet<unsigned long long> &newProcessed) override;
private slots: private slots:
void handleReceiveUpdates(const QWeakPointer<QNetworkReply>& replay); void handleReceiveUpdates(const QWeakPointer<QNetworkReply>& replay);
void handleReceiveUpdatesErr(QNetworkReply::NetworkError err); void handleReceiveUpdatesErr(QNetworkReply::NetworkError err);
@ -49,6 +50,8 @@ private:
void startUpdates(); void startUpdates();
long long _lanstUpdateTime = 0; long long _lanstUpdateTime = 0;
unsigned long long _lanstUpdateid = 0;
int _updateDelay = 1000; int _updateDelay = 1000;
}; };