Salesforce Telegram Integration - Code
In the previous article we saw a demo video of the 2-way integration between Salesforce and Telegram and a simple use case. In this article I will quickly show the configurations and Apex code to send messages from Salesforce to Telegram. In the next article we will discuss 2 different ways of achieving the other way round i.e processing messages from Telegram to Salesforce. So lets start!
Bot Creation in Telegram
- Open the Telegram App and Search for BotFather
- Enter command /start and /newbot
- After a series of straightforward question and answers you should be able a create a Bot and generate an access token. One such conversation is shown below:
Send Message to Telegram
Once the access token is generated, sending message from Salesforce is a simple Apex callout as shown below:
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
payload = 'text=' + message +'&chat_id='+receiver_chatid;
req.setEndpoint(''+*access_token*+'/sendMessage');
- message is the text you want to send to the Telegram Contact
- receiver_chatid is numeric id (usually 7 digits) of the contact. In the use case we saw in the previous article we get this id when a Telegram user sends message to the Bot
Make sure you create a Remote Site Setting for the URL https://api.telegram.org
Receive Messages from Telegram using Webhook
In order to send the messages (that the Bot receives from users) to Salesforce need to register a Salesforce APEX service as webhook to Telegram bot. The same can be done by making a simple GET call to the below URL.
https://api.telegram.org/bot{bot_token}/setWebhook?url={salesforce_apex_service_url_to_send_message_to}
- bot_token is the token you got from BotFather when you created your Bot
- salesforce_apex_service_url_to_send_message_to Apex REST service available via community or public site with GET and POST method (must be HTTPS). Additionally have a shared key transferred in the URL and compare the same in the service so that only your Bot can utilize the API.
Following will be the response if the webhook registration is successful.
{
"ok":true,
"result":
{
"url":"",
"has_custom_certificate":false,
"pending_update_count":0,
"max_connections":40
}
}