Google App Script - Telegram Bot - Custom Keyboard

2019-08-17 23:56发布

问题:

I want to create a custom keyboard.

I have this GAS code:

function sendText(chatId,text){

 var payload = { "method": "sendMessage", "chat_id": String(chatId),"text": text, "parse_mode": "HTML" }

 var data = {
  "method": "post",
  "payload": payload,
  "reply_markup": JSON.stringify({
    "keyboard": [
      [ 
        "A",
        "B"
      ],
      [
        "C",
        "D"
      ]
    ], 
    "resize_keyboard":true
  })
 }

UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);

}

it works great as echo bot but I am not able to create a custom keyboard. It just doesn't work and I have no idea why. I searched the solution online but I found nothing. Help me, please :)

回答1:

With the help of @Sean and @Kos i have resolved my problem and here is the working code. I also have added the inline_keyboard type.

function sendText(chatId,text,keyBoard){

   keyBoard = keyBoard || 0;

  if(keyBoard.inline_keyboard || keyBoard.keyboard){
     var data = {
      method: "post",
      payload: {
         method: "sendMessage",
         chat_id: String(chatId),
         text: text,
         parse_mode: "HTML",
         reply_markup: JSON.stringify(keyBoard)
       }
     }
    }else{
      var data = {
        method: "post",
        payload: {
          method: "sendMessage",
          chat_id: String(chatId),
          text: text,
          parse_mode: "HTML"
        }
      }
    }

   UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', data);

 }

the keyBoard format must be as follow:

   {
     keyboard: [
       [ 
         "A",
         "B"
       ],
       [
         "C",
         "D"
       ]
     ],
     resize_keyboard:true,
     one_time_keyboard:true
   }

   {
     inline_keyboard: [
       [
         {text:'Sandwich',callback_data:'sandwich'},
         {text:'A juicy steak',callback_data:'steak'}
       ],
       [
         {text:'Sandwich2',callback_data:'sandwich2'},
         {text:'A juicy steak2',callback_data:'steak2'}
       ]
     ]
   } 


回答2:

Show, please, how do you then work with the callback_data in app script?



回答3:

You use the wrong format for keyboard field, see the following example: