1

I'm using JavaScript to send a message to Telegram using the Telegram Bot API

const url = `https://api.telegram.org/bot<bot_token>/sendMessage?chat_id=${chat_id}&text=${message}`
const data = await fetch(url).then(resp => resp.json()) 

I want to send an inline keyboard so I tried

const message='{"reply_markup":{{\"inline_keyboard\": [[{ \text" : " Press here", "callback_data" : "TEST" }]]}}}'

But I got to Telegram

{"reply_markup":{{"inline_keyboard": [[{  ext" : " Press here", "callback_data" : "TEST" }]]}}}

How can I fix that to get the keyboard ?

0stone0
  • 34,288
  • 4
  • 39
  • 64
vtable
  • 302
  • 2
  • 15

1 Answers1

1

You shouldn't create the keyboard using strings, use JSON.stringify() to convert it to a url-acceptable format.

Consider the example below, a function called sendMessage that accepts a required chat_id and a required message.
Optionally, pass a keyboard as Javascript object that is added to the url as reply_markup

const keyboard = {
  "inline_keyboard": [
    [
      { text: "Press here", callback_data: "TEST" }
    ]
  ]
};

sendMessage(1234, 'hoi', keyboard);

function sendMessage(chat_id, message, keyboard = null) {
    const bot_token = '859163.........';
    let url = `https://api.telegram.org/bot${bot_token}/sendMessage?chat_id=${chat_id}&text=${message}`;
    if (keyboard) {
        url += '&reply_markup=' + JSON.stringify(keyboard);
    }
    fetch(url).then(resp => resp.json()).then(j => console.log(j));
}

Result:

enter image description here

0stone0
  • 34,288
  • 4
  • 39
  • 64