I have been trying to set up a Telegram Bot that sends me reminder message at specific time, but it seems that the time-based trigger is not working: the reminder messages are all send to me immediately upon I send the first message to the bot.
I expected sending a message to the bot to be the external trigger that results in building the time-based triggers, and that I would get the reminders after the specified time.
What in my code has lead to my faulty assumption?
var delay_ms = [1000, 80000000, 170000000];
var message_list = ["text_correct_1", "text_correct_2", "text_correct_3"];
var initial_state = 0;
function doPost(e) {
var estringa = JSON.parse(e.postData.contents);
if (initial_state == 0) {
createTimeDrivenTriggers();
initial_state = 1;
}
}
function createTimeDrivenTriggers() {
for (var i = 0; i < delay_ms.length; i++){
ScriptApp.newTrigger(delay_reply(i))
.timeBased()
.after(delay_ms[i])
.create();
}
}
function delay_reply(i) {
var notification = {
"method": "sendMessage",
"chat_id": CHATID,
"text": message_list[i],
}
var data = {
"method": "post",
"payload": notification
}
UrlFetchApp.fetch("https://api.telegram.org/botKEY/", data);
}
----UPDATE------ Main issues now fixed.
//Reference: https://stackoverflow.com/questions/51723459/google-scripts-trigger-and-function-in-different-sheets as suggested by tehhowch
var delay_ms = [100000,200000];//temporal sepeartion need to be large since time trigger in Google App Script is not precise
var message_list = ["text_correct_1", "text_correct_2"];
PropertiesService.getScriptProperties().setProperty("initial_state_prop", 0);
function doPost(e) {
var initial_state= PropertiesService.getScriptProperties().getProperty("initial_state_prop");
var initial_state_int=parseInt(initial_state);
if (initial_state_int == 0) {
createTimeDrivenTriggers();
PropertiesService.getScriptProperties().setProperty("initial_state_prop", 1);
}
}
function createTimeDrivenTriggers() {
for (var i = delay_ms.length-1; i >=0; i++){ //reverse loop in order to get the current trigger right
var TriggerID= ScriptApp.newTrigger("reply") //call string of function
.timeBased()
.after(delay_ms[i])
.create()
.getUniqueId();
PropertiesService.getScriptProperties().setProperty(TriggerID, delay_ms.length-i-1);//
}
}
function reply(){
var e = arguments[0];//call current event
var temp = PropertiesService.getScriptProperties().getProperty(e.triggerUid);
var temp_int = parseInt(temp); //change string to int
var notification = {
"method": "sendMessage",
"chat_id": CHATID,
"text": message_list[temp_int],
}
var data = {
"method": "post",
"payload": notification
}
UrlFetchApp.fetch("https://api.telegram.org/botKEY/", data);
}