forked from semuka/QtTelegramBot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqttelegrambot.cpp
581 lines (507 loc) · 24.7 KB
/
qttelegrambot.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
#include <QThread>
#include <QCoreApplication>
#include "qttelegrambot.h"
using namespace Telegram;
Bot::Bot(const QString &token, bool updates, quint32 updateInterval, quint32 pollingTimeout, QObject *parent) :
QObject(parent),
m_net(new Networking(token)),
m_internalUpdateTimer(new QTimer(this)),
m_updateInterval(updateInterval),
m_updateOffset(0),
m_pollingTimeout(pollingTimeout)
{
QLoggingCategory::setFilterRules("qt.network.ssl.warning=false");
//Register classes to use in signal/slot
qRegisterMetaType<Message>("Message");
qRegisterMetaType<User>("User");
connect(m_net, SIGNAL(requestFinished(QNetworkReply*)),
this, SLOT(requestFinished(QNetworkReply*)));
if (updates) {
m_internalUpdateTimer->setSingleShot(true);
connect(m_internalUpdateTimer, &QTimer::timeout, this, &Bot::internalGetUpdates);
internalGetUpdates();
}
}
Bot::~Bot()
{
m_internalUpdateTimer->stop();
delete m_internalUpdateTimer;
m_internalUpdateTimer = 0;
if(_pendingReplies.size()) {
qWarning() << __PRETTY_FUNCTION__ << "got replies pending" << _pendingReplies.size();
while(_pendingReplies.size()) {
QCoreApplication::instance()->processEvents(QEventLoop::AllEvents, 1000);
QThread::msleep(100);
}
qDebug() << __PRETTY_FUNCTION__ << "processed all replies pending" << _pendingReplies.size();
}
disconnect(m_net, SIGNAL(requestFinished(QNetworkReply*)),
this, SLOT(requestFinished(QNetworkReply*)));
delete m_net;
}
void Bot::requestFinished(QNetworkReply *reply)
{
if(!reply)
qWarning() << __PRETTY_FUNCTION__ << "null reply!";
else {
// search in map
auto it = _pendingReplies.find(reply);
if (it != _pendingReplies.end()) {
auto &fn = (*it).second;
fn(reply);
_pendingReplies.erase(reply);
} else {
qWarning() <<__PRETTY_FUNCTION__ << "couldnt find reply in pendingrepies map!" << reply;
}
reply->deleteLater();
}
}
bool Bot::asyncGetMe()
{
auto reply = m_net->asyncRequest(ENDPOINT_GET_ME,ParameterList(), Networking::GET);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return;
}
QByteArray arr = reply->readAll();
QJsonObject json = jsonObjectFromByteArray(arr);
User ret;
ret.id = json.value("id").toInt();
ret.firstname = json.value("first_name").toString();
ret.lastname = json.value("last_name").toString();
ret.username = json.value("username").toString();
if (ret.id == 0 || ret.firstname.isEmpty()) {
qCritical("%s", qPrintable("Got invalid user in " + QString(ENDPOINT_GET_ME)));
emit getMe(User());
}else
emit getMe(ret);
}
));
return true;
}
bool Bot::sendMessage(QVariant chatId, const QString &text, bool markdown, bool disableWebPagePreview, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
if (markdown) params.insert("parse_mode", HttpParameter("Markdown"));
if (disableWebPagePreview) params.insert("disable_web_page_preview", HttpParameter(disableWebPagePreview));
return this->_sendPayload(chatId, text, params, replyToMessageId, replyMarkup, "text", ENDPOINT_SEND_MESSAGE);
}
bool Bot::forwardMessage(QVariant chatId, quint32 fromChatId, quint32 messageId)
{
if (chatId.type() != QVariant::String && chatId.type() != QVariant::Int) {
qCritical("Please provide a QString or int as chatId");
return false;
}
ParameterList params;
params.insert("chat_id", HttpParameter(chatId));
params.insert("from_chat_id", HttpParameter(fromChatId));
params.insert("message_id", HttpParameter(messageId));
auto reply = m_net->asyncRequest(ENDPOINT_FORWARD_MESSAGE, params, Networking::POST);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
bool Bot::sendPhoto(QVariant chatId, QFile *file, QString caption, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
if (!caption.isEmpty()) params.insert("caption", HttpParameter(caption));
return this->_sendPayload(chatId, file, params, replyToMessageId, replyMarkup, "photo", ENDPOINT_SEND_PHOTO);
}
bool Bot::sendPhoto(QVariant chatId, const QString &fileId, QString caption, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
if (!caption.isEmpty()) params.insert("caption", HttpParameter(caption));
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "photo", ENDPOINT_SEND_PHOTO);
}
bool Bot::sendAudio(QVariant chatId, QFile *file, qint64 duration, QString performer, QString title, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
if (duration >= 0) params.insert("duration", HttpParameter(duration));
if (!performer.isEmpty()) params.insert("performer", HttpParameter(performer));
if (!title.isEmpty()) params.insert("title", HttpParameter(title));
return this->_sendPayload(chatId, file, params, replyToMessageId, replyMarkup, "audio", ENDPOINT_SEND_AUDIO);
}
bool Bot::sendAudio(QVariant chatId, QString fileId, qint64 duration, QString performer, QString title, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
if (duration >= 0) params.insert("duration", HttpParameter(duration));
if (!performer.isEmpty()) params.insert("performer", HttpParameter(performer));
if (!title.isEmpty()) params.insert("title", HttpParameter(title));
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "audio", ENDPOINT_SEND_AUDIO);
}
bool Bot::sendDocument(QVariant chatId, QFile *file, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
return this->_sendPayload(chatId, file, ParameterList(), replyToMessageId, replyMarkup, "document", ENDPOINT_SEND_DOCUMENT);
}
bool Bot::sendDocument(QVariant chatId, const QString &fileId, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "document", ENDPOINT_SEND_DOCUMENT);
}
bool Bot::sendSticker(QVariant chatId, QFile *file, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
return this->_sendPayload(chatId, file, ParameterList(), replyToMessageId, replyMarkup, "sticker", ENDPOINT_SEND_STICKER);
}
bool Bot::sendSticker(QVariant chatId, const QString &fileId, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "sticker", ENDPOINT_SEND_STICKER);
}
bool Bot::sendVideo(QVariant chatId, QFile *file, qint64 duration, QString caption, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
params.insert("duration", HttpParameter(duration));
params.insert("caption", HttpParameter(caption));
return this->_sendPayload(chatId, file, params, replyToMessageId, replyMarkup, "video", ENDPOINT_SEND_VIDEO);
}
bool Bot::sendVideo(QVariant chatId, const QString &fileId, qint64 duration, QString caption, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
params.insert("duration", HttpParameter(duration));
params.insert("caption", HttpParameter(caption));
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "video", ENDPOINT_SEND_VIDEO);
}
bool Bot::sendVoice(QVariant chatId, QFile *file, qint64 duration, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
params.insert("duration", HttpParameter(duration));
return this->_sendPayload(chatId, file, params, replyToMessageId, replyMarkup, "voice", ENDPOINT_SEND_VOICE);
}
bool Bot::sendVoice(QVariant chatId, const QString &fileId, qint64 duration, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
ParameterList params;
params.insert("duration", HttpParameter(duration));
return this->_sendPayload(chatId, fileId, params, replyToMessageId, replyMarkup, "voice", ENDPOINT_SEND_VOICE);
}
bool Bot::sendLocation(QVariant chatId, float latitude, float longitude, qint32 replyToMessageId, const GenericReply &replyMarkup)
{
Q_UNUSED(replyMarkup); // TODO
if (chatId.type() != QVariant::String && chatId.type() != QVariant::Int) {
qCritical("Please provide a QString or int as chatId");
return false;
}
ParameterList params;
params.insert("chat_id", HttpParameter(chatId));
params.insert("latitude", HttpParameter(latitude));
params.insert("longitude", HttpParameter(longitude));
if (replyToMessageId >= 0) params.insert("reply_to_message_id", HttpParameter(replyToMessageId));
auto reply = m_net->asyncRequest(ENDPOINT_SEND_LOCATION, params, Networking::POST);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
bool Bot::sendChatAction(QVariant chatId, Bot::ChatAction action)
{
if (chatId.type() != QVariant::String && chatId.type() != QVariant::Int) {
qCritical("Please provide a QString or int as chatId");
return false;
}
ParameterList params;
params.insert("chat_id", HttpParameter(chatId));
switch (action) {
case Typing:
params.insert("action", HttpParameter("typing"));
break;
case UploadingPhoto:
params.insert("action", HttpParameter("upload_photo"));
break;
case RecordingVideo:
params.insert("action", HttpParameter("record_video"));
break;
case UploadingVideo:
params.insert("action", HttpParameter("upload_video"));
break;
case RecordingAudio:
params.insert("action", HttpParameter("record_audio"));
break;
case UploadingAudio:
params.insert("action", HttpParameter("upload_audio"));
break;
case UploadingDocument:
params.insert("action", HttpParameter("upload_document"));
break;
case FindingLocation:
params.insert("action", HttpParameter("find_location"));
break;
default:
return false;
}
auto reply = m_net->asyncRequest(ENDPOINT_SEND_CHAT_ACTION, params, Networking::POST);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
bool Bot::answerCallbackQuery(QVariant callback_query_id, const QString &text, bool show_alert, QString url, quint32 cache_time)
{
ParameterList params;
params.insert("callback_query_id", HttpParameter(callback_query_id));
if (!text.isEmpty()) params.insert("text", HttpParameter(text));
if (show_alert) params.insert("show_alert", HttpParameter(show_alert));
if (!url.isEmpty()) params.insert("url", HttpParameter(url));
if (cache_time) params.insert("cache_time", HttpParameter(cache_time));
auto reply = m_net->asyncRequest(ENDPOINT_ANSWER_CALLBACK_QUERY, params, Networking::POST);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
/*
UserProfilePhotos Bot::getUserProfilePhotos(quint32 userId, qint16 offset, qint8 limit)
{
ParameterList params;
params.insert("user_id", HttpParameter(userId));
if (offset > -1) params.insert("offset", HttpParameter(offset));
if (limit > -1) params.insert("limit", HttpParameter(limit));
QJsonObject json = this->jsonObjectFromByteArray(m_net->request(ENDPOINT_GET_USER_PROFILE_PHOTOS, params, Networking::GET));
UserProfilePhotos ret;
QList<PhotoSize> photo;
foreach (QJsonValue val, json.value("photos").toArray()) {
photo = QList<PhotoSize>();
foreach (QJsonValue p, val.toArray()) {
PhotoSize ps;
ps.fileId = p.toObject().value("file_id").toString();
ps.width = p.toObject().value("width").toInt();
ps.height = p.toObject().value("height").toInt();
if (p.toObject().contains("file_size")) ps.fileSize = p.toObject().value("file_size").toInt();
photo.append(ps);
}
ret.append(photo);
}
return ret;
}
*/
bool Bot::setWebhook(const QString &url, QFile *certificate)
{
ParameterList params;
params.insert("url", HttpParameter(url));
QMimeDatabase db;
bool openedFile = false;
if (!certificate->isOpen()) {
if (!certificate->open(QFile::ReadOnly)) {
qCritical("Could not open file %s [%s]", qPrintable(certificate->fileName()), qPrintable(certificate->errorString()));
return false;
}
openedFile = true;
}
QByteArray data = certificate->readAll();
if (openedFile) certificate->close();
params.insert("certificate", HttpParameter(data, true, db.mimeTypeForData(data).name(), certificate->fileName()));
auto reply = m_net->asyncRequest(ENDPOINT_SET_WEBHOOK, params, Networking::UPLOAD);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
bool Bot::asyncGetFile(const QString &fileId)
{
ParameterList params;
params.insert("file_id", HttpParameter(fileId));
auto reply = m_net->asyncRequest(ENDPOINT_GET_FILE, params, Networking::GET);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
QJsonObject json = jsonObjectFromByteArray(arr);
file(File(json.value("file_id").toString(), json.value("file_size").toInt(-1), json.value("file_path").toString()));
}
));
return true;
}
bool Bot::_sendPayload(QVariant chatId, QFile *filePayload, ParameterList params, qint32 replyToMessageId, const GenericReply &replyMarkup, QString payloadField, QString endpoint)
{
if (chatId.type() != QVariant::String && chatId.type() != QVariant::Int) {
qCritical("Please provide a QString or int as chatId");
return false;
}
params.insert("chat_id", HttpParameter(chatId));
QMimeDatabase db;
bool openedFile = false;
if (!filePayload->isOpen()) {
if (!filePayload->open(QFile::ReadOnly)) {
qCritical("Could not open file %s [%s]", qPrintable(filePayload->fileName()), qPrintable(filePayload->errorString()));
return false;
}
openedFile = true;
}
QByteArray data = filePayload->readAll();
if (openedFile) filePayload->close();
params.insert(payloadField, HttpParameter(data, true, db.mimeTypeForData(data).name(), filePayload->fileName()));
if (replyToMessageId >= 0) params.insert("reply_to_message_id", HttpParameter(replyToMessageId));
if (replyMarkup.isValid()) params.insert("reply_markup", HttpParameter(replyMarkup.serialize()));
auto reply = m_net->asyncRequest(endpoint, params, Networking::UPLOAD);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
bool Bot::_sendPayload(const QVariant &chatId, const QString &textPayload, ParameterList ¶ms, qint32 replyToMessageId, const GenericReply &replyMarkup, QString payloadField, QString endpoint)
{
if (chatId.type() != QVariant::String && chatId.type() != QVariant::Int) {
qCritical("Please provide a QString or int as chatId");
return false;
}
params.insert("chat_id", HttpParameter(chatId));
params.insert(payloadField, HttpParameter(textPayload));
if (replyToMessageId >= 0) params.insert("reply_to_message_id", HttpParameter(replyToMessageId));
if (replyMarkup.isValid()) params.insert("reply_markup", HttpParameter(replyMarkup.serialize()));
auto reply = m_net->asyncRequest(endpoint, params, Networking::POST);
if (!reply) return false;
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
return; // todo emit signal here?
}
QByteArray arr = reply->readAll();
bool success = responseOk(arr);
if (!success)
qWarning() << "_sendPayload no success" << reply;
// emit getMe(ret); todo emit a signal here
}
));
return true;
}
QJsonObject Bot::jsonObjectFromByteArray(QByteArray json)
{
QJsonDocument d = QJsonDocument::fromJson(json);
QJsonObject obj = d.object();
if (obj.isEmpty()) {
qCritical("Got an empty response object");
return obj;
}
if (obj.value("ok").toBool() != true) {
qWarning("Result is not Ok");
return obj;
}
return obj.value("result").toObject();
}
QJsonArray Bot::jsonArrayFromByteArray(QByteArray json)
{
QJsonDocument d = QJsonDocument::fromJson(json);
QJsonObject obj = d.object();
if (obj.isEmpty()) {
qCritical("Got an empty response object");
return QJsonArray();
}
if (obj.value("ok").toBool() != true) {
qWarning("Result is not Ok");
return QJsonArray();
}
return obj.value("result").toArray();
}
bool Bot::responseOk(QByteArray json)
{
QJsonDocument d = QJsonDocument::fromJson(json);
QJsonObject obj = d.object();
return (!obj.isEmpty() && obj.value("ok").toBool() == true);
}
void Bot::internalGetUpdates()
{
ParameterList params;
params.insert("offset", HttpParameter(m_updateOffset));
params.insert("limit", HttpParameter(50));
params.insert("timeout", HttpParameter(m_pollingTimeout));
auto reply = m_net->asyncRequest(ENDPOINT_GET_UPDATES, params, Networking::GET);
if (!reply) {
qWarning() << __PRETTY_FUNCTION__ << "request failed";
if (m_internalUpdateTimer)
m_internalUpdateTimer->start(m_updateInterval);
return;
}
_pendingReplies.insert(std::make_pair(reply,
[this](QNetworkReply *reply) {
if (reply->error() != QNetworkReply::NoError) {
qCritical("%s", qPrintable(QString("[%1] %2").arg(reply->error()).arg(reply->errorString())));
if (m_internalUpdateTimer)
m_internalUpdateTimer->start(m_updateInterval);
return;
}
QByteArray arr = reply->readAll();
QJsonArray json = this->jsonArrayFromByteArray(arr);
foreach (QJsonValue value, json) {
Update u(Update(value.toObject()));
m_updateOffset = (u.id >= m_updateOffset ? u.id + 1 : m_updateOffset);
emit message(u.message);
emit update(u);
}
if (m_internalUpdateTimer)
m_internalUpdateTimer->start(m_updateInterval);
}
));
}