Telegram

This part of the sample includes a GET request to the REST API of the Telegram Messenger (required TwinCAT version: 3.1.4024.10). With the help of the so-called "Telegram-Bot", a TwinCAT user can send messages to a specific telegram chat.

Telegram 1:
Scheme Telegram

The first step of establishing a connection is the creation of the “Telegram-Bot”. To do this, the user needs a Telegram account from which they can contact the BotFather. The BotFather is a generally available account for the creation of new bots.

Telegram 2:
Telegram BotFather

The BotFather returns an API token that must be used when sending requests from TwinCAT to the Telegram API. With access to this token, a HTTP client can control every function that the bot delivers. A description of the BOT API can be found here: https://core.telegram.org/bots/api

The requests are basically structured according to the following scheme:

https://api.telegram.org/bot<token>/METHOD_NAME

Sending messages from a TwinCAT PLC to a Telegram Bot can proceed as shown in the following figure. In this sample, a message from the Telegram browser version to the bot is used to request the Chat ID. To do this, a message is first written to the bot's chat via the browser or the Telegram app.

Telegram 3:
Telegram Chat

The ChatID can then be determined using the getUpdates method. For example, Postman is used here as an HTTP client:

Telegram 4:

Using this Chat ID, the sendMessage method used in the sample can then be used to send chat messages from the TwinCAT program.

PROGRAM MAIN
VAR
    // trigger command execution for Telegram samples
    bGetTelegram                    : BOOL;

    fbHttpClientTelegram            : FB_IotHttpClient :=(sHostName:='api.telegram.org',
                                    bKeepAlive:=FALSE, tConnectionTimeout:=T#10S);

    fbHttpGetTelegram               : FB_TestHTTP_Get_Telegram;
    sMessage                        : STRING(500);
END_VAR
//init client parameters at startup
IF NOT fbHttpClientTelegram.bConfigured THEN
    fbHttpClientTelegram.stTLS.sCA:='C:\TwinCAT\3.1\Config\Certificates\TelegramRoot.cer';
    fbHttpClientTelegram.nHostPort:=443;
    fbHttpClientTelegram.stTLS.bNoServerCertCheck:=FALSE;
END_IF

IF fbHttpClientTelegram.bConfigured THEN
    fbHttpGetTelegram(bSend:=bGetTelegram, fbClient:=fbHttpClientTelegram, sMessage:=sMessage);
END_IF

fbHttpClientTelegram.Execute();