Для отправки сообщей в телеграм вам понадобиться токен бота и чат ID что бы бот знал в какой чат ему слать сообщения.
Не буду углубляться откуда взять токен бота, и как получить id чата , многие и так уже с этим имели дело, а если и нет то эта информация легко гуглится.
Далее представляю вашему внимаю код модуля, который следует сохранить в файл с названием Telegram.txt , предварительно заполнив в этом файле константы TG_TOKEN и TG_CHAT_ID.
function UrlEncode(const Str: string): string;
var
i, c: Integer;
b1, b2, b3: Byte;
begin
Result := '';
for i := 1 to Length(Str) do
begin
c := Ord(Str[i]);
if c < $80 then
begin
if ((c >= 48) and (c <= 57)) or ((c >= 65) and (c <= 90)) or ((c >= 97) and (c <= 122)) then
Result := Result + Char(c)
else if c = 32 then
Result := Result + '+'
else
Result := Result + '%' + IntToHex(c,2);
end
else if c < $800 then
begin
b1 := $C0 or (c shr 6);
b2 := $80 or (c and $3F);
Result := Result + '%' + IntToHex(b1,2) + '%' + IntToHex(b2,2);
end
else
begin
b1 := $E0 or (c shr 12);
b2 := $80 or ((c shr 6) and $3F);
b3 := $80 or (c and $3F);
Result := Result + '%' + IntToHex(b1,2) + '%' + IntToHex(b2,2) + '%' + IntToHex(b3,2);
end;
end;
end;
function HttpGet(const url: string): string;
var
hInternet, hUrl: Cardinal;
Buffer: array[0..4095] of AnsiChar;
BytesRead: Cardinal;
Response: string;
i: Integer;
begin
Result := '';
hInternet := InternetOpenA('AdrenalineBot', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
if hInternet = 0 then Exit;
try
hUrl := InternetOpenUrlA(hInternet, PAnsiChar(AnsiString(url)), nil, 0, INTERNET_FLAG_RELOAD, 0);
if hUrl = 0 then Exit;
try
Response := '';
while InternetReadFile(hUrl, @Buffer, SizeOf(Buffer) - 1, BytesRead) and (BytesRead > 0) do
begin
for i := 0 to BytesRead - 1 do
Response := Response + Char(Buffer[i]);
end;
Result := Response;
finally
InternetCloseHandle(hUrl);
end;
finally
InternetCloseHandle(hInternet);
end;
end;
function SendTelegramMessage(const Text: string): Boolean;
var
Response: string;
begin
Result := False;
Response := HttpGet('https://api.telegram.org/bot' + TG_TOKEN + '/sendMessage?chat_id=' + TG_CHAT_ID + '&text=' + UrlEncode(Text));
if (Response <> '') and (Pos('"ok":true', Response) > 0) then
Result := True;
end;
procedure PrintTG(const Text: string);
begin
if SendTelegramMessage(Text) then
Engine.Msg('[Telegram]',Text,32768) // зеленый
else
Engine.Msg('[Telegram]',Text,255); // красный при ошибке
end;
begin
end.
Модуль должен лежать в той же папке что и скрипт который его будет использовать. Вот простейший пример такого скрипта :
procedure ChatScaner;
begin
if (ChatMessage.Unread) and (ChatMessage.ChatType = mtPrivate) then
PrintTG('[' + ChatMessage.Sender + '] ' + ChatMessage.text);
delay(2000);
end;