r/GoogleAppsScript • u/ipreachenglish • Sep 26 '20
Question Need to prevent GAS web app instances from colliding
I'm using Google Apps Script to create a web app for my Telegram bot. The web app is invoked by the bot via web hook.
My bot has an inline keyboard that you can see in action in GIF 1 below. Tapping the keyboard buttons you enter a code that appears on the screen.
My problem is when I tap the buttons a little faster, callback queries to the web app collide, which results in messed up entry. See GIF 2.
I've been racking my brain trying to figure out a way to prevent instances of the web app from collision, but I've had no luck so far.
I'm posting my code below. Please, help.
The way I see it is that every instance of the script needs more time to complete before the next one kicks in. I've tried using async/await and lockService to the best of my understanding. I've been advised to try and queue the queries, but sadly haven't been able to make it work.
function doPost(e){
var contents = JSON.parse(e.postData.contents);
var query_id = contents.callback_query.id;
var mes_id = contents.callback_query.message.message_id;
var userinput = contents.callback_query.data;
var message_now = contents.callback_query.message.text;
var inline_keyboard = contents.callback_query.message.reply_markup;
var message_upd = message_now + " " + userinput;
var keydata = {
method: "post",
payload: {
method: "editMessageText",
chat_id: String(chat_id),
message_id: mes_id,
text: message_upd ,
parse_mode: "HTML",
reply_markup: JSON.stringify(inline_keyboard)
}
}
UrlFetchApp.fetch('https://api.telegram.org/bot' + token + '/', keydata);
UrlFetchApp.fetch(url + "/answerCallbackQuery?callback_query_id=" + query_id);
}
2
u/siquylee Sep 27 '20
Although Gas supports async and await/promise but everything is synchronous and it’s slow. I think it is not suitable for kind of this task. You might consider all text at once approach. Like you, I have been using Gas for Slack/Viber bot.
1
u/ipreachenglish Sep 27 '20
Yeah, all text at once is a way, definitely, but I was hoping for something else.
2
u/imthenachoman Sep 27 '20
Use LockServices. Make a lock and the next call will wait till the lock is cleared.
But, the better way would probably to handle it on the FE -- in your bot/app. It should track all the calls and handle collisions.