我有一个函数和一些辅助函数,应该可以访问Slack消息历史记录并返回与特定数字字符串匹配的第一条消息。
我已经在计算机的Node.js环境中对代码进行了广泛的测试,以验证其是否有效。但是,我无法使其在Twilio Function的运行时环境中工作;我不断收到错误消息“函数声明中缺少名称。”,该函数将无法正确链接或完全像一个函数一样工作。
我在做什么错了?
exports.handler = function(context, event, callback) {
if(event.event){
if(event.event.channel == context.CHANNEL_ID){
if(event.event.subtype){
console.log("bot posting");
if(event.event.thread_ts){
console.log("bot posting in thread");
console.log(event);
}
else{
console.log("bot posting in channel");
console.log(event);
}
}
else{
console.log("staff posting");
if(event.event.thread_ts){
console.log("staff posting in thread");
console.log(event);
}
else{
console.log("staff posting in channel");
console.log(event);
}
}
}
}
else{
console.log("incoming sms message");
console.log(typeof event.From);
}
returnTS("6049248010").then(function (ts) {
console.log(ts);
});
callback(null);
};
var getSlackHistory = async function (ts) {
try {
var response;
if (typeof ts === 'undefined') {
response = await got('https://slack.com/api/channels.history?'
+ 'token=' + context.TWILIO_TOKEN
+ '&channel=' + context.TWILIO_CHANNEL_ID);
}
else {
response = await got('https://slack.com/api/channels.history?'
+ 'token=' + context.TWILIO_TOKEN
+ '&channel=' + context.TWILIO_CHANNEL_ID
+ '&latest=' + ts);
}
return await JSON.parse(response.body);
}
catch (error) { console.log("failure"); }
}
var getAllSlackHistory = async function () {
var message_history = [];
try {
var response = await getSlackHistory();
// console.log(response.messages[response.messages.length - 1].ts);
for (var i = 0; i < response.messages.length; i++) {
message_history.push(response.messages[i]);
}
while (response.has_more) {
response = await getSlackHistory(response.messages[response.messages.length - 1].ts);
for (var i = 0; i < response.messages.length; i++) {
message_history.push(response.messages[i]);
}
}
return await message_history;
}
catch (error) {
console.log(error);
}
}
var returnTS = async function (numberString) {
try {
var message_history = await getAllSlackHistory();
//console.log(message_history.length);
// console.log(numberString);
for (var i = 0; i < message_history.length; i++) {
// console.log(message_history[i].text);
// console.log(message_history[i].text.includes(numberString));
if (message_history[i].text.includes(numberString))
// console.log(message_history[i].ts);
return message_history[i].ts;
}
}
catch (error) {
console.log(error);
}
}
答案 0 :(得分:1)
这里是Twilio开发人员的传播者。
正如您在评论中所说,这与异步操作和Twilio函数的回调有关。
当前,函数的最后几行是:
returnTS("6049248010").then(function (ts) {
console.log(ts);
});
callback(null);
};
returnTS
是一个异步函数,在这种情况下返回一个promise。一旦您调用callback
函数(或5秒钟后),Twilio函数将停止所有操作,因此在这种情况下,仅应在异步函数完成后才调用callback
。如果您将呼叫移至promise回调中的callback
,那么事情应该会按预期进行。请尝试以下操作:
returnTS("6049248010").then(function (ts) {
console.log(ts);
callback(null);
});
};