Telegram offers two kinds of APIs, one is Bot API which allows to create programs that use Bots and HTTPs as protocol. Telegram API and TDLib allows to build customized Telegram clients and is much more powerful than Bot API.
sgcWebSockets supports TDLib through tdjson library, which means that you can build your own telegram client. TDLib takes care of all network implementation details, encryption and local data storage. TDLib supports all Telegram features.
TDLib (Telegram Database Library) Advantages
Cross-platform: can be used on Windows, Android, iOS, MacOS, Linux...
Easy to use: uses json messages to communicate between application and telegram.
High-performance: In the Telegram Bot API, each TDLib instance handles more than 24000 bots.
Consistent: TDLib guarantees that all updates will be delivered in the right order.
Reliable: TDLib remains stable on slow and unreliable internet connections.
Secure: All local data is encrypted using a user-provided encryption key.
Fully Asynchronous: Requests to TDLib don't block each other. Responses will be sent when they are available.
Windows
TDLib requires other third-parties libraries: OpenSSL and ZLib. These libraries must be deployed with tdjson library.
* Windows versions requires VCRuntime which can be download from microsoft: https://www.microsoft.com/en-us/download/details.aspx?id=52685, If after installing, the problem persist, try to copy the following dll in the same folder where your application is: VCRUNTIME140.dll and VCRUNTIME140_1.dll.
Copy the following libraries in the same directory where is your application:
Windows 32 | Windows 64 |
tdjson.dll | tdjson.dll |
libcrypto-1_1.dll | libcrypto-1_1-x64.dll |
libssl-1_1.dll | libssl-1_1-x64.dll |
zlib1.dll | zlib1.dll |
OSX64
Deploy the library libtdjson.dylib to your device and you can set where is the library using SetTDJsonPath, example:
if you deploy to "Contents\MacOS\", you must set the path in TPath.GetDirectoryName(ParamStr(0)) folder.
OSXARM64
Deploy the library libtdjson.dylib to your device and you can set where is the library using SetTDJsonPath, example:
if you deploy to "Contents\MacOS\", you must set the path in TPath.GetDirectoryName(ParamStr(0)) folder.
Linux64
Deploy the library libtdjson.so to your device and set the library path calling the method SetTDJsonPath.
Android
Deploy the library libtdjsonandroid.so to your device. Example: if you deploy an Android64 library, set RemotePath in Project/Deployment to "library\lib\arm64-v8a\". If is Android32, set RemotePath to "library\lib\armeabi-v7a\"
iOS64
Copy the library libtdjson.a to these directories:
C:\Program Files (x86)\Embarcadero\Studio\<IDE Version>\lib\iosDevice64\debug
C:\Program Files (x86)\Embarcadero\Studio\<IDE Version>\lib\iosDevice64\release
In order to obtain an API id and develop your own application using the Telegram API you need to do the following:
Sign up for Telegram using any application.
Log in to your Telegram core: https://my.telegram.org.
Go to API development tools and fill out the form.
You will get basic addresses as well as the api_id and api_hash parameters required for user authorization.
For the moment each number can only have one api_id connected to it.
These values must be set in Telegram.API property of Telegram component. In order to authenticate, you can authenticate as an user or as a bot, there are 2 properties which you can set to login to Telegram:
PhoneNumber: if you login as an user, you must set your phone number (with international code), example: +34699123456
BotToken: if you login as a bot, set your token in this property (as provided by telegram).
DatabaseDirectory: allows to specify where is the tdlib database. Leave empty and will take the default configuration.
The following parameters can be configured:
ApplicationVersion: application version, example: 1.0
DeviceModel: device model, example: desktop
LanguageCode: user language code, example: en.
SystemVersion: verison of operating system, example: windows.
Optionally, you can configure the path where is located tdjson library using SetTDJsonPath method. Just pass the path before start a new telegram session.
Once you have configured Telegram Component, you can set Active property to true and program will attempts to connect to Telegram.
Sample Code
oTelegram := TsgcTDLib_Telegram.Create(nil);
oTelegram.Telegram.API.ApiHash := 'your api hash';
oTelegram.Telegram.API.ApiId := 'your api id';
oTelegram.PhoneNumber := 'your phone number';
oTelegram.ApplicationVersion := '1.0';
oTelegram.DeviceModel := 'Desktop';
oTelegram.LanguageCode := 'en';
oTelegram.SystemVersion := 'Windows';
oTelegram.Active := true;
There are two events which can be called by library in order to get an Authentication Code (delivered in Telegram Application, not SMS) or to provide a password.
OnAuthenticationCode
This event is called when Telegram sends an Authorization Code to Telegram Application and user must copy this code and set in Code argument of this event.
procedure OnAuthenticationCode(Sender: TObject; var Code: string);
begin
Code := InputBox('Telegram Code', 'Introduce code', '');
end;
In Android, inputbox doesn't locks the thread, so instead of return the value introduced by user in Code parameter, use the method SetAuthenticationCode to set the code value.
procedure OnAuthenticationCode(Sender: TObject; var Code:string);
begin
InputBox('Telegram', 'Introduce Telegram Code', '',
procedure(const AResult: TModalResult; const AValue: string)
begin
sgcTelegram.SetAuthenticationCode(AValue);
end
);
end;
OnAuthenticationPassword
This event is called when Telegram requires that user set a password.
Once authorization has started, you can check the status of authorization OnAuthorizationStatus event, this event is called every time there is a change in status of authorization. Some values of Status are:
Once connection has started, you can check the status of connection OnConnectionStatus event, this event is called every time there is a change in status of connection. Some values of Status are:
TsgcTDLib_Telegram API Component support the most following methods.
Method | Parameters | Description |
SendTextMessage |
aChatId: Id of Chat which message will be sent aText: Text of Message. InlineKeyboard: Optional Buttons (only bots). |
Sends a Text Message to a Chat |
SendRichTextMessage |
aChatId: Id of Chat which message will be sent aText: Text of Message. InlineKeyboard: Optional Buttons (only bots). |
Sends a Rich Text Message to a Chat. Markdown syntax:
|
SendDocumentMessage | aChatId: Id of Chat which message will be sent aFilePath: full file path of document aInlineKeyboard: Optional Buttons (only bots). | Sends a Document to a Chat. |
SendPhotoMessage |
aChatId: Id of Chat which message will be sent aFilePath: full file path of photo Width: witdh of photo. Height: width of photo. InlineKeyboard: Optional Buttons (only bots). |
Sends a Photo to a Chat. |
SendVideoMessage |
aChatId: Id of Chat which message will be sent aFilePath: full file path of video aWidth: witdh of video. Height: width of video. aDuration: duration of video in seconds. aInlineKeyboard: Optional Buttons (only bots). |
Sends a Video to a Chat. |
SendInvoiceMessage |
aChatId: Id of Chat which message will be sent aInvoice: Text of Message. aInlineKeyboard: Optional Buttons (only bots). |
Sends an Invoice (only available when is a Bot and in Private Channels). |
EditTextMessage |
aChatId: Id of Chat which message will be sent aMessageId: Id of Message to modify Text: Text of Message. InlineKeyboard: Optional Buttons (only bots). ShowKeyboard: Optional Buttons (only bots). |
Edits the text of a message (or a text of a game message) |
AddChatMember | aChatId: Id of Chat which message will be sent aUserId: Identifier of the user. aForwardLimit: The number of earlier messages from the chat to be forwarded to the new member; up to 100. Ignored for supergroups and channels. | Adds a new member to a chat. Members can't be added to private or secret chats. Members will not be added until the chat state has been synchronized with the server. |
AddChatMembers | aChatId: Id of Chat which message will be sent aUserIds: Identifiers of the users to be added to the chat. | Adds multiple new members to a chat. Currently this option is only available for supergroups and channels. This option can't be used to join a chat. Members can't be added to a channel if it has more than 200 members. Members will not be added until the chat state has been synchronized with the server. |
GetChatMember | aChatId: Chat Identifier. aUserId: User Identifier. | Returns information about a single member of a chat. |
GetBasicGroupFullInfo | aGroupId: Basic Group Identifier | Returns full information about a basic group by its identifier. |
GetSupergroupMembers |
aSuperGroupId: Identifier of the supergroup or channel. aSupergroupMembersFilter: The type of users to return. By default null aOffset: Number of users to skip. aLimit: The maximum number of users be returned; up to 200. |
Returns information about members or banned users in a supergroup or channel. |
JoinChatByInviteLink | aLink: Invite link to import; | Uses an invite link to add the current user to the chat if possible. The new member will not be added until the chat state has been synchronized with the server. |
CreateNewSecretChat | aUserId: Identifier of the user. | Creates a new secret chat. |
CreateNewBasicGroupChat | aUserIds: Identifiers of the users to be added to the chat. aTitle: Title of the new basic group | Creates a new basic group |
CreateNewSupergroupChat |
aTitle: Title of the new SuperGroup aIsChannel: True, if a channel chat should be created. aDescription: Chat Description. |
Creates a new supergroup or channel. |
CreatePrivateChat |
aUserId: Identifier of the user. aForce: If true, the chat will be created without network request. In this case all information about the chat except its type, title and photo can be incorrect |
Returns an existing chat corresponding to a given user |
GetChats | aOffsetOrder: Chat order to return chats from aOffsetChatId: Chat identifier to return chats from aLimit: The maximum number of chats to be returned. | Returns an ordered list of chats. Chats are sorted by the pair (order, chat_id) in decreasing order (cannot be used is logged as Bot) |
GetChat | aChatId: Chat identifier | Returns information about a chat by its identifier |
GetChatHistory |
aChatId: Chat identifier aFromMessageId: Identifier of the message starting from which history must be fetched; use 0 to get results from the last message. aOffset: Specify 0 to get results from exactly the from_message_id or a negative offset up to 99 to get additionally some newer messages. aLimit:The maximum number of messages to be returned |
Returns messages in a chat. The messages are returned in a reverse chronological order |
GetUser | aUserId: User Identifier | Returns information about a user by their identifier. |
AddProxyHTTP |
aServer: Server name of proxy. aPort: Number of proxy port. aUserName: Username for logging in; may be empty. aPassword: Password for logging in; may be empty. aHTTPOnly: Pass true, if the proxy supports only HTTP requests and doesn't support transparent TCP connections via HTTP CONNECT method. |
Adds a HTTP proxy server for network requests. Can be called before authorization. |
AddProxyMTProto |
aServer: Server name of proxy. aPort: Number of proxy port. aSecret: The proxy's secret in hexadecimal encoding. |
Adds a MTProto proxy server for network requests. Can be called before authorization. |
AddProxySocks5 |
aServer: Server name of proxy. aPort: Number of proxy port. aUserName: Username for logging in; may be empty. aPassword: Password for logging in; may be empty. |
Adds a Socks5 proxy server for network requests. Can be called before authorization. |
EnableProxy | aId: ID of proxy | Enables a proxy. Only one proxy can be enabled at a time. Can be called before authorization. |
DisableProxy | Disables the currently enabled proxy. Can be called before authorization. | |
RemoveProxy | aId: ID of proxy | Removes a proxy server. Can be called before authorization. |
GetProxies | Returns list of proxies that are currently set up. Can be called before authorization. | |
getChatSponsoredMessage | aChatId: ID of the chat | Returns sponsored message to be shown in a chat; for channel chats only. Returns a 404 error if there is no sponsored message in the chat. |
ViewMessage |
aSponsorChatId: ID of the sponsor Chat aMessageId: ID of the message |
Informs TDLib that messages are being viewed by the user. Many useful activities depend on whether the messages are currently being viewed or not |
Logout | Logouts from Telegram. | |
TDLibSend | aRequest: JSON Request. | Send any Request in JSON protocol. |
Example How to send a Text Message
oTelegram := TsgcTDLib_Telegram.Create(nil);
oTelegram.Telegram.API.ApiHash := 'your api hash';
oTelegram.Telegram.API.ApiId := 'your api id';
oTelegram.PhoneNumber := 'your phone number';
oTelegram.Active := true;
...
oTelegram.SendTextMessage('1234', 'My First Message from sgcWebSockets');
Example How to send a method not implemented
You can Send Any JSON message using TDLibSend method, example: join a telegram chat.
oTelegram := TsgcTDLib_Telegram.Create(nil);
oTelegram.Telegram.API.ApiHash := 'your api hash';
oTelegram.Telegram.API.ApiId := 'your api id';
oTelegram.PhoneNumber := 'your phone number';
oTelegram.Active := true;
...
oTelegram.TDLibSend('{"@type": "joinChat", "chat_id": "1234"}');
Check the following url to know all JSON methods: Telegram JSON API.
OnBeforeReadEvent
This event is called when JSON message is received by Telegram API component and is still not processed. Set Handled property to True if you process this event manually or don't want that event is processed by component. You can use this event to log all messages too.
OnMessageText
This event is called when a New Message Text has been received, read MessageText parameter to access to message text properties.
OnMessageDocument
This event is called when a New Document Message is received. Access to MessageDocument to get access to Document properties.
OnMessagePhoto
This event is called when a New Photo Message is received. Access to MessagePhoto to get access to Photo properties.
OnVideoPhoto
This event is called when a New Video Message is received. Access to MessageVideo to get access to Video properties.
OnMessageSponsored
This event is called when a New Sponsored Message has been received (after calling the method getChatSponsoredMessage)
OnNewChat
This event is called when a new chat is received.
OnNewCallbackQuery
This event is called when a new incoming callback query is received; for bots only.
OnEvent
This event is called when a new Event is received by API Component. Can be used to process some events not implemented by API Component.
OnException
This event is called if there is any exception when processing Telegram API Data.
MyId: returns the User Identifier of current user.
Check the following code sample which shows how connect to Telegram API, ask user to introduce a Code (if required by Telegram API), send a message when connection is ready and Log Text Messages received.
oTelegram := TsgcTDLib_Telegram.Create(nil);
oTelegram.Telegram.API.ApiHash := 'your api hash';
oTelegram.Telegram.API.ApiId := 'your api id';
oTelegram.PhoneNumber := 'your phone number';
oTelegram.ApplicationVersion := '1.0';
oTelegram.DeviceModel := 'Desktop';
oTelegram.LanguageCode := 'en';
oTelegram.SystemVersion := 'Windows';
oTelegram.Active := true;
procedure OnAuthenticationCode(Sender: TObject; var Code: string);
begin
Code := InputBox('Telegram Code', 'Introduce code', '');
end;
procedure OnMessageText(Sender: TObject; MessageText: TsgcTelegramMessageText);
begin
Log('Message Received: ' + MessageText.Text);
end;
procedure OnConnectionStatus(Sender: TObject; const Status: string);
begin
if Status = 'connectionStateReady' then
oTelegram.SendTextMessage('1234', 'Hello Telegram!');
end;