Custom Keyboard on Telegram.


What is a custom keyboard on Telegram?

Whenever your bot sends a message, it can pass along a special keyboard with predefined reply options. Telegram apps that receive the message will display your keyboard to the user. Tapping any of the buttons will immediately send the respective command. This way you can drastically simplify user interaction with your bot.

 

Now let's learn how to get the custom keyboards working in a bot on Telegram and also understand how the response of user selection can be handled.

Example 1 - Creating a poll.

Let's say you want to ask the user if he likes icecream or not. To do so you need to just change the 'type' to 'poll' in the above example and remove the options.
The JSON would look like -

{"type":"poll","question":"Do you like ice-cream?"}

 

This JSON has to be sent as String in the HTTP response and the Gupshup platform will handle it.

 

Here is how this will look on Telegram -

 

Once the user selects one of the options then your bot will receive that option value as the message and you can access this message using event.message.

So if you were using the hosted code on the bot builder then the code to implement custom keyboards and handle the response would be -

 if (event.message == "hi"){
      var payload = {"type":"poll","question":"Hello,do you like ice-cream?"};
      context.sendResponse(JSON.stringify(payload));
      return;        
     }

 if (event.message == "Yes"){
       context.sendResponse("Great, I like them too");
     return;
    }

The complete flow would look like -

 

Example 2 - Creating a survey.

Let's say you want to ask a user about the flavour of icecream he/she likes and give multiple options. To do so you can just send the below JSON as String through the HTTP response back to the user -

 {"type":"survey","question":"What is your favourite flavour of icecream?","options":["Vanilla","Chocolate","Butterscotch"]}

 

This JSON has to be sent as String in the HTTP response and the Gupshup platform will handle it.

 

Here is how this will look on Telegram

 

Once the user selects one of the options then your bot will receive that option value as the message and you can access this message using event.message.

So if you were using the hosted code on the Bot Builder then the code to implement custom keyboards and handle the response would be -

if (event.message == "hi"){
        var payload = {"type":"survey","question":"Hello,What is your
                favourite flavour of icecream?","options":
                      ["Vanilla","Chocolate","Butterscotch"]};
        context.sendResponse(JSON.stringify(payload));
        return;        
   }

if (event.message == "Vanilla"){
        context.sendResponse("Ok, getting vanilla ice cream");
        return;
   }

The complete flow would look like -