-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathTgBotApi.pas
1472 lines (1301 loc) · 40.5 KB
/
TgBotApi.pas
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit TgBotApi;
interface
uses
System.SysUtils, System.Classes, System.Json, REST.Json, System.Net.HttpClient,
REST.JsonReflect, REST.Json.Interceptors, HGM.JSONParams,
System.Generics.Collections, System.Net.Mime;
{$SCOPEDENUMS ON}
type
TTgUpdateSubscribe = class(TCustomAttribute);
TtgException = class(Exception)
private
FCode: Int64;
procedure SetCode(const Value: Int64);
public
property Code: Int64 read FCode write SetCode;
constructor Create(const Code: Int64; const Message: string); reintroduce;
end;
TtgBadRequest = class(TtgException);
TtgObject = class
public
constructor Create; virtual;
function ToString(AutoFree: Boolean = False): string; reintroduce;
end;
TtgMessageNew = class(TtgObject)
private
FChat_id: int64;
FText: string;
FReply_markup: string;
FParse_mode: string;
public
property ChatId: int64 read FChat_id write FChat_id;
property Text: string read FText write FText;
/// <summary>
/// Markdown, HTML, MarkdownV2
/// </summary>
property ParseMode: string read FParse_mode write FParse_mode;
property ReplyMarkup: string read FReply_markup write FReply_markup;
end;
TtgMessageDel = class(TtgObject)
private
FChat_id: int64;
FMessage_id: int64;
public
property ChatId: int64 read FChat_id write FChat_id;
property MessageId: int64 read FMessage_id write FMessage_id;
end;
TtgUser = class(TtgObject)
private
FFirst_name: string;
FId: int64;
FIs_bot: Boolean;
FLast_name: string;
FLanguage_code: string;
FUsername: string;
FCan_join_groups: Boolean;
FCan_read_all_group_messages: Boolean;
FSupports_inline_queries: Boolean;
public
property FirstName: string read FFirst_name;
property LastName: string read FLast_name;
property Username: string read FUsername;
property LanguageCode: string read FLanguage_code;
property IsBot: Boolean read FIs_bot;
property Id: int64 read FId;
property CanJoinGroups: Boolean read FCan_join_groups write FCan_join_groups;
property CanReadAllGroupMessages: Boolean read FCan_read_all_group_messages write FCan_read_all_group_messages;
property SupportsInlineQueries: Boolean read FSupports_inline_queries write FSupports_inline_queries;
end;
TtgChat = class(TtgObject)
private
FFirst_name: string;
FTitle: string;
FId: Int64;
FType: string;
FLast_name: string;
FUsername: string;
public
property Id: Int64 read FId;
property &Type: string read FType;
property Username: string read FUsername;
property FirstName: string read FFirst_name;
property LastName: string read FLast_name;
property Title: string read FTitle;
end;
TtgMessageEntity = class(TtgObject)
private
FLength: Int64;
FType: string;
FOffset: Int64;
public
property Length: Int64 read FLength;
property Offset: Int64 write FOffset;
// mention
property &Type: string read FType;
end;
TtgFile = class(TtgObject)
private
FFile_id: string;
FFile_size: Int64;
FFile_unique_id: string;
FFile_path: string;
public
property FileId: string read FFile_id write FFile_id;
/// <summary>
/// Размер файла в байтах
/// </summary>
property FileSize: Int64 read FFile_size write FFile_size;
property FileUniqueId: string read FFile_unique_id write FFile_unique_id;
/// <summary>
/// Путь к файлу для его загрузки. Не пустой только после вызова getFile
/// </summary>
property FilePath: string read FFile_path write FFile_path;
end;
TtgPhoto = class(TtgFile)
private
FWidth: Int64;
FHeight: Int64;
public
property Height: Int64 read FHeight write FHeight;
property Width: Int64 read FWidth write FWidth;
end;
TtgSticker = class(TtgFile)
private
FEmoji: string;
FHeight: Int64;
FIs_animated: Boolean;
FIs_video: Boolean;
FSet_name: string;
FThumb: TtgPhoto;
FWidth: Int64;
public
property Emoji: string read FEmoji write FEmoji;
property Height: Int64 read FHeight write FHeight;
property IsAnimated: Boolean read FIs_animated write FIs_animated;
property IsVideo: Boolean read FIs_video write FIs_video;
property SetName: string read FSet_name write FSet_name;
property Thumb: TtgPhoto read FThumb write FThumb;
property Width: Int64 read FWidth write FWidth;
destructor Destroy; override;
end;
TtgDocument = class(TtgFile)
private
FFile_name: string;
FThumb: TtgPhoto;
FMime_type: string;
public
property FileName: string read FFile_name write FFile_name;
property MimeType: string read FMime_type write FMime_type;
property Thumb: TtgPhoto read FThumb write FThumb;
destructor Destroy; override;
end;
TtgVideo = class(TtgFile)
private
FDuration: Int64;
FFile_name: string;
FHeight: Int64;
FMime_type: string;
FThumb: TtgPhoto;
FWidth: Int64;
public
property Duration: Int64 read FDuration write FDuration;
property MimeType: string read FMime_type write FMime_type;
property FileName: string read FFile_name write FFile_name;
property Height: Int64 read FHeight write FHeight;
property Thumb: TtgPhoto read FThumb write FThumb;
property Width: Int64 read FWidth write FWidth;
destructor Destroy; override;
end;
TtgAnimation = class(TtgDocument)
private
FDuration: Int64;
FHeight: Int64;
FWidth: Int64;
public
property Duration: Int64 read FDuration write FDuration;
property Height: Int64 read FHeight write FHeight;
property Width: Int64 read FWidth write FWidth;
end;
TtgVoiceChatStarted = class(TtgObject);
TtgVoiceChatEnded = class(TtgObject)
private
FDuration: Int64;
public
property Duration: Int64 read FDuration;
end;
TtgVoiceChatScheduled = class(TtgObject)
private
[JsonReflectAttribute(ctString, rtString, TUnixDateTimeInterceptor)]
FStart_date: TDateTime;
public
property StartDate: TDateTime read FStart_date;
end;
TtgPollOption = class(TtgObject)
private
FText: string;
FVoter_count: Int64;
public
property Text: string read FText write FText;
property VoterCount: Int64 read FVoter_count write FVoter_count;
end;
TtgPoll = class(TtgObject)
private
FAllows_multiple_answers: Boolean;
FId: string;
FIs_anonymous: Boolean;
FIs_closed: Boolean;
FOptions: TArray<TtgPollOption>;
FQuestion: string;
FTotal_voter_count: Int64;
FType: string;
public
property AllowsMultipleAnswers: Boolean read FAllows_multiple_answers write FAllows_multiple_answers;
property Id: string read FId write FId;
property IsAnonymous: Boolean read FIs_anonymous write FIs_anonymous;
property IsClosed: Boolean read FIs_closed write FIs_closed;
property Options: TArray<TtgPollOption> read FOptions write FOptions;
property Question: string read FQuestion write FQuestion;
property TotalVoterCount: Int64 read FTotal_voter_count write FTotal_voter_count;
// regular, quiz
property &Type: string read FType write FType;
destructor Destroy; override;
end;
TtgPollAnswer = class(TtgObject)
private
FUser: TtgUser;
FPoll_id: string;
FOption_ids: TArray<Integer>;
public
property User: TtgUser read FUser;
property PollId: string read FPoll_id;
property OptionIds: TArray<Integer> read FOption_ids;
destructor Destroy; override;
end;
TtgVoice = class(TtgFile)
private
FMime_type: string;
FDuration: Int64;
public
property Duration: Int64 read FDuration write FDuration;
property MimeType: string read FMime_type write FMime_type;
end;
TtgLocation = class(TtgObject)
private
FLive_period: Int64;
FLatitude: Extended;
FLongitude: Extended;
FHeading: Int64;
FHorizontal_accuracy: Extended;
public
property Heading: Int64 read FHeading write FHeading;
property HorizontalAccuracy: Extended read FHorizontal_accuracy write FHorizontal_accuracy;
property Latitude: Extended read FLatitude write FLatitude;
property LivePeriod: Int64 read FLive_period write FLive_period;
property Longitude: Extended read FLongitude write FLongitude;
end;
TtgMessage = class(TtgObject)
private
[JsonReflectAttribute(ctString, rtString, TUnixDateTimeInterceptor)]
FDate: TDateTime;
FMessage_id: Int64;
FFrom: TtgUser;
FChat: TtgChat;
FText: string;
FEntities: TArray<TtgMessageEntity>;
FReply_to_message: TtgMessage;
FNew_chat_participant: TtgUser;
FNew_chat_member: TtgUser;
FNew_chat_members: TArray<TtgUser>;
FPhoto: TArray<TtgPhoto>;
FSender_chat: TtgChat;
FVoice_chat_started: TtgVoiceChatStarted;
FVoice_chat_ended: TtgVoiceChatEnded;
FVoice_chat_scheduled: TtgVoiceChatEnded;
FNew_chat_title: string;
FNew_chat_photo: TArray<TtgPhoto>;
FPoll: TtgPoll;
[JsonReflectAttribute(ctString, rtString, TUnixDateTimeInterceptor)]
FEdit_date: TDateTime;
FAnimation: TtgAnimation;
FVideo: TtgVideo;
FCaption: string;
FVoice: TtgVoice;
[JsonReflectAttribute(ctString, rtString, TUnixDateTimeInterceptor)]
FForward_date: TDateTime;
FForward_from: TTgUser;
FLeft_chat_member: TTgUser;
FLeft_chat_participant: TtgUser;
FLocation: TtgLocation;
FDocument: TtgDocument;
public
property Animation: TtgAnimation read FAnimation;
property Caption: string read FCaption;
property Document: TtgDocument read FDocument;
property Chat: TtgChat read FChat;
property Date: TDateTime read FDate;
property EditDate: TDateTime read FEdit_date;
property Entities: TArray<TtgMessageEntity> read FEntities;
property ForwardDate: TDateTime read FForward_date;
property ForwardFrom: TTgUser read FForward_from;
property From: TtgUser read FFrom;
property LeftChatMember: TTgUser read FLeft_chat_member;
property LeftChatParticipant: TtgUser read FLeft_chat_participant;
property Location: TtgLocation read FLocation;
property MessageId: Int64 read FMessage_id;
property NewChatMember: TtgUser read FNew_chat_member;
property NewChatMembers: TArray<TtgUser> read FNew_chat_members;
property NewChatParticipant: TtgUser read FNew_chat_participant;
property NewChatPhoto: TArray<TtgPhoto> read FNew_chat_photo;
property NewChatTitle: string read FNew_chat_title;
property Photo: TArray<TtgPhoto> read FPhoto;
property Poll: TtgPoll read FPoll;
property ReplyToMessage: TtgMessage read FReply_to_message;
property SenderChat: TtgChat read FSender_chat;
property Text: string read FText;
property Video: TtgVideo read FVideo;
property Voice: TtgVoice read FVoice;
property VoiceChatEnded: TtgVoiceChatEnded read FVoice_chat_ended;
property VoiceChatScheduled: TtgVoiceChatEnded read FVoice_chat_scheduled;
property VoiceChatStarted: TtgVoiceChatStarted read FVoice_chat_started;
destructor Destroy; override;
end;
TtgResponse = class(TtgObject)
private
FOk: Boolean;
FError_code: Int64;
FDescription: string;
public
property Ok: Boolean read FOk;
property ErrorCode: int64 read FError_code;
property Description: string read FDescription;
end;
TtgResponse<T: class, constructor> = class(TtgResponse)
private
FResult: T;
public
property Result: T read FResult;
destructor Destroy; override;
end;
TtgResponseSimple<T> = class(TtgResponse)
private
FResult: T;
public
property Result: T read FResult;
end;
TtgResponseDelete = TtgResponseSimple<Boolean>;
TtgResponseItems<T: class, constructor> = class(TtgResponse)
private
FResult: TArray<T>;
public
property Result: TArray<T> read FResult;
destructor Destroy; override;
end;
TtgUserResponse = TtgResponse<TtgUser>;
TtgMessageResponse = TtgResponse<TtgMessage>;
TtgGetFile = class(TtgObject)
private
FFile_id: string;
public
property FileId: string read FFile_id write FFile_id;
end;
TtgGetFileResponse = class(TtgResponse<TtgFile>);
TtgUpdateNew = class(TtgObject)
private
FOffset: int64;
public
property Offset: int64 read FOffset write FOffset;
end;
TtgCallbackQuery = class(TtgObject)
private
FMessage: TtgMessage;
FFrom: TtgUser;
FChat_instance: int64;
FData: string;
FId: int64;
public
property Message: TtgMessage read FMessage;
property From: TtgUser read FFrom;
property ChatInstance: int64 read FChat_instance;
property Data: string read FData;
property Id: int64 read FId;
destructor Destroy; override;
end;
TtgUpdate = class(TtgObject)
private
FMessage: TtgMessage;
FUpdate_id: int64;
FCallback_query: TtgCallbackQuery;
FEdited_message: TtgMessage;
FPoll_answer: TtgPollAnswer;
public
property Message: TtgMessage read FMessage;
property EditedMessage: TtgMessage read FEdited_message;
property UpdateId: int64 read FUpdate_id;
property CallbackQuery: TtgCallbackQuery read FCallback_query;
property PollAnswer: TtgPollAnswer read FPoll_answer;
destructor Destroy; override;
end;
TtgUpdates = TtgResponseItems<TtgUpdate>;
/// <summary>
/// Title, Command, Url
/// </summary>
TtgKey = record
Text: string;
CallbackData: string;
Url: string;
RequestContact: Boolean;
RequestLocation: Boolean;
class function Create(const Text, CallbackData: string; const Url: string = ''; RequestContact: Boolean = False; RequestLocation: Boolean = False): TtgKey; static;
end;
TtgKeysArray = TArray<TtgKey>;
TtgInlineKeysArray = TArray<TtgKeysArray>;
TtgInlineKeyboardMarkup = class
private
FJSON: TJSONObject;
public
constructor Create; overload;
constructor Create(Keys: TtgInlineKeysArray); overload;
destructor Destroy; override;
function ToString(AutoFree: Boolean = False): string; reintroduce;
end;
TtgReplyKeyboardMarkup = class
private
FJSON: TJSONObject;
public
constructor Create; overload;
constructor Create(Keys: TtgInlineKeysArray); overload;
destructor Destroy; override;
function ToString(AutoFree: Boolean = False): string; reintroduce;
end;
TtgUpdateFunc = reference to function(Update: TtgUpdate): Boolean;
TtgUpdateFuncItem = reference to function(Update: TtgUpdate; const Item: string): Boolean;
TtgUpdateProc = reference to procedure(Update: TtgUpdate);
TtgParamsHistory = class(TJSONParam)
end;
TtgPollType = (Regular, Quiz);
TtgPollTypeHelper = record helper for TtgPollType
function ToString: string;
end;
TtgAttachmentParams = class(TJSONParam)
/// <summary>
/// Unique identifier for the target chat or username of the target channel (in the format @channelusername)
/// </summary>
function ChatId(const Value: string): TtgAttachmentParams; overload;
/// <summary>
/// Unique identifier for the target chat or username of the target channel (in the format @channelusername)
/// </summary>
function ChatId(const Value: Int64): TtgAttachmentParams; overload;
/// <summary>
/// Unique identifier for the target message thread (topic) of the forum; for forum supergroups only
/// </summary>
function MessageThreadId(const Value: Int64): TtgAttachmentParams; overload;
/// <summary>
/// Sends messages silently. Users will receive a notification with no sound.
/// </summary>
function DisableNotification(const Value: Boolean): TtgAttachmentParams; overload;
/// <summary>
/// Protects the contents of the sent messages from forwarding and saving
/// </summary>
function ProtectContent(const Value: Boolean): TtgAttachmentParams; overload;
/// <summary>
/// If the messages are a reply, ID of the original message
/// </summary>
function ReplyToMessageId(const Value: Int64): TtgAttachmentParams; overload;
/// <summary>
/// Pass True if the message should be sent even if the specified replied-to message is not found
/// </summary>
function AllowSendingWithoutReply(const Value: Boolean): TtgAttachmentParams; overload;
end;
TtgPollParams = class(TtgAttachmentParams)
function Question(const Value: string): TtgPollParams;
function Options(const Value: TArray<string>): TtgPollParams;
function IsNotAnonymous(const Value: Boolean = True): TtgPollParams;
function &Type(const Value: TtgPollType): TtgPollParams;
function OpenPeriod(const Value: Word): TtgPollParams; overload;
end;
TtgAudioParams = class(TtgAttachmentParams)
function Audio(const Url: string): TtgAudioParams; overload;
end;
TtgContactParams = class(TtgAttachmentParams)
function PhoneNumber(const Value: string): TtgContactParams; overload;
function FirstName(const Value: string): TtgContactParams; overload;
function LastName(const Value: string): TtgContactParams; overload;
function VCard(const Value: string): TtgContactParams; overload;
end;
TtgUpdateSubscriber = record
ConditionText: TArray<string>;
Func: TtgUpdateFunc;
FuncItem: TtgUpdateFuncItem;
function Executed(u: TtgUpdate): Boolean;
class function Create(Func: TtgUpdateFunc; const ConditionText: TArray<string> = []): TtgUpdateSubscriber; overload; static;
class function Create(Func: TtgUpdateFuncitem; const ConditionText: TArray<string> = []): TtgUpdateSubscriber; overload; static;
end;
TtgCallbackSubscriber = record
PayloadText: TArray<string>;
Func: TtgUpdateFunc;
function Executed(u: TtgUpdate): Boolean;
class function Create(Func: TtgUpdateFunc; const PayloadText: TArray<string> = []): TtgCallbackSubscriber; overload; static;
end;
TOnTextOut = reference to procedure(const Text: string);
TtgClient = class
private
FBaseUrl: string;
FToken: string;
FLastUpdateId: Int64;
FDoPolling: Boolean;
FOnTextOut: TOnTextOut;
FSubscribers: TList<TtgUpdateSubscriber>;
FCallBackSubscribers: TList<TtgCallbackSubscriber>;
FLogging: Boolean;
function ProccessUpdate(u: TtgUpdate): Boolean;
procedure SetLogging(const Value: Boolean);
procedure DoError(Response: TStringStream; StatusCode: Integer);
function GetIsStop: Boolean;
procedure CollectSubscribers;
protected
procedure DoTextOut(const Text: string);
public
constructor Create(const AToken: string);
destructor Destroy; override;
//
function BuildUrl(const Method: string): string;
function BuildDownloadFileUrl(const FilePath: string): string;
//
function Execute<T: class, constructor>(const Method: string; const Json: string = ''): T; overload;
function Execute<T: class, constructor>(const Method: string; const Form: TMultipartFormData): T; overload;
//
function GetMe: TtgUserResponse;
function GetUpdates: TtgUpdates;
function SendMessageToChat(ChatId: Int64; const Text: string; const KeyBoard: string = ''): TtgMessageResponse;
function SendPhotoToChat(ChatId: Int64; const Caption: string; const FileName: string): TtgMessageResponse; overload;
function SendPhotoToChat(ChatId: Int64; const Caption: string; const FileName: string; Stream: TStream): TtgMessageResponse; overload;
function SendVideoToChat(ChatId: Int64; const Caption: string; const FileName: string): TtgMessageResponse; overload;
function SendVideoToChat(ChatId: Int64; const Caption: string; const FileName: string; Stream: TStream): TtgMessageResponse; overload;
function SendPoll(Params: TtgPollParams): TtgMessageResponse;
function SendContact(Params: TtgContactParams): TtgMessageResponse;
function SendAudio(Params: TtgAudioParams): TtgMessageResponse;
procedure DeleteMessage(ChatId: Int64; MessageId: Int64);
//
procedure GetFile(const FileId: string; Stream: TStream);
//
procedure Polling; overload;
procedure Polling(Proc: TtgUpdateProc); overload;
procedure StopPolling;
procedure Hello;
//
procedure Subscribe(Func: TtgUpdateFunc; const Text: TArray<string>); overload;
procedure Subscribe(Func: TtgUpdateFuncItem; const Text: TArray<string>); overload;
procedure Subscribe(Func: TtgUpdateFunc; const Text: string = ''); overload;
procedure Subscribe(Func: TtgUpdateFuncItem; const Text: string = ''); overload;
procedure SubscribeCallBack(Func: TtgUpdateFunc; const Payload: string); overload;
procedure SubscribeCallBack(Func: TtgUpdateFunc; const Payload: TArray<string>); overload;
procedure Unsubscribe(Func: TtgUpdateFunc); overload;
procedure Unsubscribe(Func: TtgUpdateFuncItem); overload;
//
property BaseUrl: string read FBaseUrl write FBaseUrl;
property LastUpdateId: Int64 read FLastUpdateId write FLastUpdateId;
property Token: string read FToken write FToken;
property OnTextOut: TOnTextOut read FOnTextOut write FOnTextOut;
property Logging: Boolean read FLogging write SetLogging;
property IsStop: Boolean read GetIsStop;
end;
TArrayHelp = class
public
class procedure FreeArrayOfObject<T: class>(var Target: TArray<T>); overload; inline; static;
end;
implementation
uses
System.NetConsts, System.Net.URLClient, System.NetEncoding, HGM.ArrayHelpers,
System.Rtti;
class procedure TArrayHelp.FreeArrayOfObject<T>(var Target: TArray<T>);
{$IFNDEF AUTOREFCOUNT}
var
Item: T;
{$ENDIF}
begin
{$IFNDEF AUTOREFCOUNT}
for Item in Target do
if Assigned(Item) then
Item.Free;
SetLength(Target, 0);
{$ENDIF}
end;
{ TtgClient }
procedure TtgClient.Hello;
begin
DoTextOut('Telegram Bot Mini API Inited');
var Me := GetMe;
try
if Assigned(Me.Result) then
DoTextOut('Bot name is ' + Me.Result.FirstName + ' (' + Me.Result.Username + ')');
finally
Me.Free;
end;
end;
function TtgClient.GetMe: TtgUserResponse;
begin
Result := Execute<TtgUserResponse>('getMe');
end;
function TtgClient.SendAudio(Params: TtgAudioParams): TtgMessageResponse;
begin
Result := Execute<TtgMessageResponse>('sendAudio', Params.ToJsonString);
end;
function TtgClient.SendContact(Params: TtgContactParams): TtgMessageResponse;
begin
Result := Execute<TtgMessageResponse>('sendContact', Params.ToJsonString);
end;
function TtgClient.SendMessageToChat(ChatId: Int64; const Text, KeyBoard: string): TtgMessageResponse;
begin
var Message := TtgMessageNew.Create;
Message.ChatId := ChatId;
Message.Text := Text;
if not KeyBoard.IsEmpty then
Message.ReplyMarkup := KeyBoard;
Result := Execute<TtgMessageResponse>('sendMessage', Message.ToString(True));
end;
procedure TtgClient.DoError(Response: TStringStream; StatusCode: Integer);
begin
var ErrorText := 'Unknown error';
var ErrorCode: Int64 := StatusCode;
var RespObj: TtgResponse;
try
RespObj := TJSON.JsonToObject<TtgResponse>(Response.DataString, [joIgnoreEmptyStrings, joIgnoreEmptyArrays]);
except
RespObj := nil;
end;
if Assigned(RespObj) then
try
ErrorText := RespObj.Description;
ErrorCode := RespObj.ErrorCode;
case RespObj.ErrorCode of
400:
raise TtgBadRequest.Create(ErrorCode, ErrorText);
end;
finally
RespObj.Free;
end;
raise TtgException.Create(ErrorCode, ErrorText);
end;
function TtgClient.SendPhotoToChat(ChatId: Int64; const Caption: string; const FileName: string): TtgMessageResponse;
begin
var Stream := TFileStream.Create(FileName, fmShareDenyWrite);
try
Result := SendPhotoToChat(ChatId, Caption, FileName, Stream);
finally
Stream.Free;
end;
end;
function TtgClient.SendPhotoToChat(ChatId: Int64; const Caption: string; const FileName: string; Stream: TStream): TtgMessageResponse;
var
Form: TMultipartFormData;
begin
Form := TMultipartFormData.Create;
try
Form.AddStream('photo', Stream, FileName);
Result := Execute<TtgMessageResponse>(
Format('sendPhoto?chat_id=%d&caption=%s', [ChatId, TURLEncoding.URL.Encode(Caption)]), Form);
finally
Form.Free;
end;
end;
function TtgClient.SendPoll(Params: TtgPollParams): TtgMessageResponse;
begin
Result := Execute<TtgMessageResponse>('sendPoll', Params.ToJsonString);
end;
function TtgClient.SendVideoToChat(ChatId: Int64; const Caption, FileName: string; Stream: TStream): TtgMessageResponse;
var
Form: TMultipartFormData;
begin
Form := TMultipartFormData.Create;
try
Form.AddStream('video', Stream, FileName);
Result := Execute<TtgMessageResponse>(
Format('sendVideo?chat_id=%d&caption=%s', [ChatId, TURLEncoding.URL.Encode(Caption)]), Form);
finally
Form.Free;
end;
end;
function TtgClient.SendVideoToChat(ChatId: Int64; const Caption, FileName: string): TtgMessageResponse;
begin
var Stream := TFileStream.Create(FileName, fmShareDenyWrite);
try
Result := SendVideoToChat(ChatId, Caption, FileName, Stream);
finally
Stream.Free;
end;
end;
procedure TtgClient.SetLogging(const Value: Boolean);
begin
FLogging := Value;
end;
procedure TtgClient.StopPolling;
begin
FDoPolling := False;
end;
procedure TtgClient.Subscribe(Func: TtgUpdateFuncItem; const Text: TArray<string>);
begin
FSubscribers.Add(TtgUpdateSubscriber.Create(Func, Text));
end;
procedure TtgClient.Subscribe(Func: TtgUpdateFunc; const Text: TArray<string>);
begin
FSubscribers.Add(TtgUpdateSubscriber.Create(Func, Text));
end;
procedure TtgClient.Subscribe(Func: TtgUpdateFuncItem; const Text: string);
begin
if Text.IsEmpty then
Subscribe(Func, [])
else
Subscribe(Func, [Text]);
end;
procedure TtgClient.SubscribeCallBack(Func: TtgUpdateFunc; const Payload: TArray<string>);
begin
FCallBackSubscribers.Add(TtgCallbackSubscriber.Create(Func, Payload));
end;
procedure TtgClient.SubscribeCallBack(Func: TtgUpdateFunc; const Payload: string);
begin
FCallBackSubscribers.Add(TtgCallbackSubscriber.Create(Func, [Payload]));
end;
procedure TtgClient.Subscribe(Func: TtgUpdateFunc; const Text: string);
begin
if Text.IsEmpty then
Subscribe(Func, [])
else
Subscribe(Func, [Text]);
end;
procedure TtgClient.DoTextOut(const Text: string);
begin
if Assigned(OnTextOut) then
OnTextOut(Text);
end;
procedure TtgClient.Unsubscribe(Func: TtgUpdateFunc);
begin
for var i := 0 to Pred(FSubscribers.Count) do
if FSubscribers[i].Func = TtgUpdateFunc(Func) then
begin
FSubscribers.Delete(i);
Exit;
end;
end;
procedure TtgClient.Unsubscribe(Func: TtgUpdateFuncItem);
begin
for var i := 0 to Pred(FSubscribers.Count) do
if FSubscribers[i].FuncItem = TtgUpdateFuncItem(Func) then
begin
FSubscribers.Delete(i);
Exit;
end;
end;
function TtgClient.BuildDownloadFileUrl(const FilePath: string): string;
begin
Result := Format('%s/file/bot%s/%s', [FBaseUrl, FToken, FilePath]);
end;
function TtgClient.BuildUrl(const Method: string): string;
begin
Result := Format('%s/bot%s/%s', [FBaseUrl, FToken, Method]);
end;
procedure TtgClient.CollectSubscribers;
{var
Context: TRttiContext; }
begin
//Context.GetType(TTgUpdateSubscribe)
end;
constructor TtgClient.Create(const AToken: string);
begin
inherited Create;
FSubscribers := TList<TtgUpdateSubscriber>.Create;
FCallBackSubscribers := TList<TtgCallbackSubscriber>.Create;
FBaseUrl := 'https://api.telegram.org';
FToken := AToken;
CollectSubscribers;
end;
procedure TtgClient.DeleteMessage(ChatId, MessageId: Int64);
begin
var Msg := TtgMessageDel.Create;
Msg.ChatId := ChatId;
Msg.MessageId := MessageId;
var Resp := Execute<TtgResponseDelete>('deleteMessage', Msg.ToString(True));
Resp.Free;
end;
destructor TtgClient.Destroy;
begin
FSubscribers.Free;
FCallBackSubscribers.Free;
inherited;
end;
function TtgClient.Execute<T>(const Method: string; const Json: string): T;
var
Response: TStringStream;
StatusCode: Integer;
begin
if Method.IsEmpty then
raise TtgException.Create(-1, 'Method is empty');
Result := nil;
var HTTP := THTTPClient.Create;
Response := TStringStream.Create;
try
HTTP.HandleRedirects := True;
HTTP.ContentType := 'application/json';
var Body := TStringStream.Create;
try
Body.WriteString(Json);
Body.Position := 0;
StatusCode := HTTP.Post(BuildUrl(Method), Body, Response).StatusCode;
finally
Body.Free;
end;
if FLogging then
DoTextOut(Response.DataString);
if StatusCode = 200 then
Result := TJSON.JsonToObject<T>(Response.DataString, [joIgnoreEmptyStrings, joIgnoreEmptyArrays])
else
DoError(Response, StatusCode);
if not Assigned(Result) then
raise TtgException.Create(-1, 'Empty object');
finally
HTTP.Free;
Response.Free;
end;
end;
function TtgClient.Execute<T>(const Method: string; const Form: TMultipartFormData): T;
var
Response: TStringStream;
StatusCode: Integer;
begin
if Method.IsEmpty then
raise TtgException.Create(-1, 'Method is empty');
Result := nil;
var HTTP := THTTPClient.Create;
Response := TStringStream.Create;
try
HTTP.HandleRedirects := True;
HTTP.ContentType := 'application/json';
StatusCode := HTTP.Post(BuildUrl(Method), Form, Response).StatusCode;
if FLogging then
DoTextOut(Response.DataString);
if StatusCode = 200 then
Result := TJSON.JsonToObject<T>(Response.DataString, [joIgnoreEmptyStrings, joIgnoreEmptyArrays])
else
DoError(Response, StatusCode);
if not Assigned(Result) then
raise TtgException.Create(-1, 'Empty object');
finally
HTTP.Free;
Response.Free;
end;
end;
procedure TtgClient.GetFile(const FileId: string; Stream: TStream);
var
HTTP: THTTPClient;
begin
var Params := TtgGetFile.Create;
Params.FileId := FileId;
var Value := Execute<TtgGetFileResponse>('getFile', Params.ToString(True));
try
Stream.Size := 0;
HTTP := THTTPClient.Create;
try
HTTP.HandleRedirects := True;
if HTTP.Get(BuildDownloadFileUrl(Value.Result.FilePath), Stream).StatusCode <> 200 then
raise TtgException.Create(-1, 'Download error');
Stream.Position := 0;
finally
HTTP.Free;
end;
finally
Value.Free;
end;
end;
function TtgClient.GetIsStop: Boolean;
begin
Result := not FDoPolling;
end;
function TtgClient.GetUpdates: TtgUpdates;
begin
var Params := TtgUpdateNew.Create;
Params.Offset := FLastUpdateId;
Result := Execute<TtgUpdates>('getUpdates', Params.ToString(True));
if Length(Result.Result) > 0 then
FLastUpdateId := Result.Result[High(Result.Result)].UpdateId + 1;
end;
procedure TtgClient.Polling;
begin
Polling(nil);
end;
function TtgClient.ProccessUpdate(u: TtgUpdate): Boolean;
begin
for var Subscriber in FSubscribers do
if Subscriber.Executed(u) then
Exit(True);
for var Subscriber in FCallBackSubscribers do
if Subscriber.Executed(u) then
Exit(True);
Result := False;
end;
procedure TtgClient.Polling(Proc: TtgUpdateProc);
begin
FDoPolling := True;
while FDoPolling do
begin
var Updates := GetUpdates;
try