Hey everyone! I’m trying to set up a menu for my Telegram bot using Google Sheets Apps Script. I want users to type ‘menu’ and see a list of buttons they can press to do different things.
I’ve got this code working, but I’m wondering if there’s a better way to do it:
function showOptions(chatId) {
const botUrl = 'https://api.telegram.org/bot' + TOKEN + '/sendMessage';
const menuButtons = {
'inline_keyboard': [
[{'text': 'Settings', 'callback_data': 'settings'}],
[{'text': 'Team', 'callback_data': 'team'}],
[{'text': 'League', 'callback_data': 'league'}],
[{'text': 'Cup', 'callback_data': 'cup'}],
[{'text': 'Partners', 'callback_data': 'partners'}],
[{'text': 'Debug', 'callback_data': 'debug'}]
]
};
const messageData = {
'chat_id': chatId,
'text': 'Choose an option:',
'reply_markup': menuButtons
};
const requestOptions = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(messageData)
};
const result = UrlFetchApp.fetch(botUrl, requestOptions);
Logger.log(result);
}
Does anyone have tips on making this more efficient or adding extra features? Thanks!
Your code is a good starting point, but there’s room for improvement. Consider implementing a persistent keyboard instead of an inline one. This way, the menu stays visible, reducing the need for users to type ‘menu’ repeatedly. You can achieve this by modifying the ‘reply_markup’ parameter:
const menuKeyboard = {
'keyboard': [
['Settings', 'Team'],
['League', 'Cup'],
['Partners', 'Debug']
],
'resize_keyboard': true,
'one_time_keyboard': false
};
Also, to enhance performance, you might want to use the Telegram Bot API’s setWebhook method instead of polling. This approach is more efficient as it only triggers your script when there’s new input from users, reducing unnecessary API calls and script executions.
I’ve worked with Telegram bots and Google Sheets Apps Script before, and your approach looks solid. One improvement you might consider is storing the menu options in a Google Sheet instead of hardcoding them in the script. This change would allow you to update the menu more easily, without needing to modify the code each time.
For instance, you could create a sheet with columns for the button text and callback data, then modify your script to read these values dynamically and construct the inline keyboard accordingly. This not only adds flexibility but also eases maintenance. Additionally, incorporating error handling by using a try-catch block around the UrlFetchApp.fetch() call can help manage API errors more gracefully, making your bot more robust.
If the function is called frequently, consider using a caching mechanism—Google’s CacheService might be a good option—to reduce API calls and improve response times.
hey, ur code is fine. try put the fetch in try-catch to handle errors if the api lags. also, using caching might speed up responses for frequent calls. just a thought, cheers!