我一直在尝试建立一个在特定时间向我发送提醒消息的电报机器人,但似乎基于时间的触发器不起作用:我发送第一条消息后,所有提醒消息都会立即发送给我到机器人。
我希望向机器人发送一条消息,该消息是导致建立基于时间的触发器的外部触发器,并且我将在指定时间后得到提醒。
我的代码中有什么导致我的错误假设?
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);
}
----更新------ 主要问题现已解决。
//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);
}