-
Notifications
You must be signed in to change notification settings - Fork 5
/
brooktelegramaction.pas
122 lines (102 loc) · 2.6 KB
/
brooktelegramaction.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
unit brooktelegramaction;
{$mode objfpc}{$H+}
interface
uses
BrookAction, tgtypes, tgsendertypes, sysutils, classes, fpjson, tgbot
;
type
TWebhookBot = class;
{ TWebhookAction }
TWebhookAction = class(TBrookAction)
private
FBot: TWebhookBot;
protected
{ Use Bot.OnReceiveMessage or Bot.DoReceiveMessageUpdate instead }
procedure BotMessageHandler({%H-}AMessage: TTelegramMessageObj); virtual; deprecated;
public
class function AppDir: String;
constructor Create; override;
destructor Destroy; override;
procedure Post; override;
property Bot: TWebhookBot read FBot;
end;
{ TWebhookBot }
TWebhookBot = class(TTelegramBot)
private
FBrookAction: TWebhookAction;
function DoReceiveUpdate(const aUpdate: String): Boolean; overload;
protected
property BrookAction: TWebhookAction read FBrookAction;
public
constructor Create(const AToken: String; AWebhookAction: TWebhookAction);
end;
implementation
uses
BrookHttpConsts
;
{ TWebhookBot }
function TWebhookBot.DoReceiveUpdate(const aUpdate: String): Boolean;
var
aJSON: TJSONObject;
aUpdateObject: TTelegramUpdateObj;
begin
Result:=False;
if aUpdate.IsEmpty then
begin
ErrorMessage('POST data Content of HTTP request is empty!');
Exit;
end;
try
aJSON:=GetJSON(aUpdate) as TJSONObject;
try
aUpdateObject:=TTelegramUpdateObj.CreateFromJSONObject(aJSON) as TTelegramUpdateObj;
finally
aJSON.Free;
end;
except
on E:Exception do
begin
ErrorMessage('Error while parse json string ('+E.ClassName+': '+E.Message+')');
Exit;
end;
end;
DoReceiveUpdate(aUpdateObject);
Result:=True;
end;
constructor TWebhookBot.Create(const AToken: String;
AWebhookAction: TWebhookAction);
begin
inherited Create(AToken);
FBrookAction:=AWebhookAction;
end;
{ TWebhookAction }
procedure TWebhookAction.BotMessageHandler(AMessage: TTelegramMessageObj);
begin
// nothing
end;
class function TWebhookAction.AppDir: String;
begin
Result:=IncludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0)));
end;
constructor TWebhookAction.Create;
begin
inherited Create;
FBot:=TWebhookBot.Create(EmptyStr, Self);
end;
destructor TWebhookAction.Destroy;
begin
FreeAndNil(FBot);
inherited Destroy;
end;
procedure TWebhookAction.Post;
var
Msg: String;
begin
Msg:=HttpRequest.Content;
if Bot.DoReceiveUpdate(Msg) then
begin
HttpResponse.ContentType:=BROOK_HTTP_CONTENT_TYPE_APP_JSON;
Write(FBot.RequestBody);
end;
end;
end.