forked from ricardoelices/TGBotLazarus
-
Notifications
You must be signed in to change notification settings - Fork 17
/
tgutils.pas
98 lines (81 loc) · 2.3 KB
/
tgutils.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
unit tgutils;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, strutils, tgtypes, tgsendertypes
;
const
mdCode='`';
function MarkdownEscape(const S: String): String;
function MarkdownEscapeV2(const S: String): String;
function CaptionFromChat(aChat: TTelegramChatObj): String;
function CaptionFromUser(AUser: TTelegramUserObj): String;
function BuildLink(const aCaption, aLink: String; aMarkup: TParseMode = pmDefault): String;
{ Like a tg://user?id=123456789 }
function UserLink(aUserID: Int64): String;
implementation
const
MarkdownSpChars: array[0..3] of AnsiChar = ('\', '_', '*', '`');
MarkdownSpCharsV2: array[0..17] of AnsiChar = ('_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|',
'{', '}', '.', '!');
_tguserLink='tg://user?id=%d';
function MarkdownEscape(const S: String): String;
var
a: AnsiChar;
begin
Result:=S;
for a in MarkdownSpChars do
Result:=StringReplace(Result, a, '\'+a, [rfReplaceAll]);
end;
function MarkdownEscapeV2(const S: String): String;
var
a: AnsiChar;
begin
Result:=S;
for a in MarkdownSpCharsV2 do
Result:=StringReplace(Result, a, '\'+a, [rfReplaceAll]);
end;
function CaptionFromChat(aChat: TTelegramChatObj): String;
begin
Result:=EmptyStr;
with aChat do
begin
if First_name<>EmptyStr then
Result+=First_name+' ';
if Last_name<>EmptyStr then
Result+=Last_name+' ';
if Title<>EmptyStr then
Result+=Title+' ';
if Username<>EmptyStr then
Result+='@'+Username;
end;
Result:=Trim(Result);
end;
function CaptionFromUser(AUser: TTelegramUserObj): String;
begin
Result:=EmptyStr;
with AUser do
begin
if First_name<>EmptyStr then
Result+=First_name+' ';
if Last_name<>EmptyStr then
Result+=Last_name+' ';
if Username<>EmptyStr then
Result+='@'+Username;
end;
Result:=Trim(Result);
end;
function BuildLink(const aCaption, aLink: String; aMarkup: TParseMode): String;
begin
case aMarkup of
pmMarkdown: Result:=Format('[%s](%s)', [aCaption, aLink]);
pmHTML: Result:=Format('<a href="%s">%s</a>', [aLink, aCaption]);
else
Result:=aLink;
end;
end;
function UserLink(aUserID: Int64): String;
begin
Result:=Format(_tguserLink, [aUserID]);
end;
end.