Reputation: 173
I am trying to send buttons to my telegram bot using the telegram bot api. For now, for creating the buttons, I have to hard code the values in the fields but lets say I want to create the inline keyboard buttons dynamically through an array and passing the array index and the array values as parameters. How should i go about it ? This is what I tried so far.
var menu =["Nightclub","Parks","Restaurants","Telecom","Internet"];
var options = {
reply_markup: JSON.stringify({
inline_keyboard: [
[{ text: 'Some button text 1', callback_data: '1' }],
[{ text: 'Some button text 2', callback_data: '2' }],
[{ text: 'Some button text 3', callback_data: '3' }]
]
})
};
Lets say I want to pass the data in the menu array dynamically inside my options. How do i go about it ?
Upvotes: 1
Views: 8084
Reputation: 145
You can try too using a simple for loop:
var keyboard = [];
var menu = ['Nightclub', 'Parks', 'Restaurants', 'Telecom', 'Internet'];
for (var i = 0; i < menu.length; i++) {
keyboard.push([{'text': menu[i], 'callback_data': (i + 1)}]);
}
{
'reply_markup': JSON.stringify({
inline_keyboard: keyboard
})
}
/* The result will be:
{
'reply_markup': JSON.stringify({
inline_keyboard: [
[{'text': 'Nightclub', 'callback_data': '1'}],
[{'text': 'Parks', 'callback_data': '2'}],
[{'text': 'Restaurants', 'callback_data': '3'}],
[{'text': 'Telecom', 'callback_data': '4'}],
[{'text': 'Internet', 'callback_data': '5'}]
]
*/
Upvotes: 5
Reputation: 23565
If I understood you well.
We gonna use here the Array.map function to create one array using menu array.
var menu = ["Nightclub", "Parks", "Restaurants", "Telecom", "Internet"];
var options = {
reply_markup: JSON.stringify({
inline_keyboard: menu.map((x, xi) => ([{
text: x,
callback_data: String(xi + 1),
}])),
}),
};
Gonna result to :
{
reply_markup: JSON.stringify({
inline_keyboard: [
[{
text: 'Nightclub',
callback_data: '1'
}],
[{
text: 'Parks',
callback_data: '2'
}],
[{
text: 'Restaurants',
callback_data: '3'
}],
[{
text: 'Telecom',
callback_data: '4'
}],
[{
text: 'Internet',
callback_data: '5'
}],
],
}),
}
Upvotes: 5