如何用Twilio编写谷歌函数,在实时数据库中发送价值变化短信



我正在编写我的第一个谷歌云函数,我对它没有深入的了解。我正在尝试用Twilio编写一个谷歌云功能。当我的实时数据库中的水值发生变化时,它会向给定的号码发送一条短信,说明这台机器的水值已经改变因此该消息看起来像";水的价值";机器ID";已更改";。我试过这样做,但我没有在YouTube上找到任何合适的文档或视频,完全满足所有要求。我从上周开始对此进行研究,并编写了一些代码。任何人都可以检查我的代码,并告诉我必须做哪些更改才能得到我想要的。这是我到现在为止写的。

exports.testing = functions.https.onRequest((request, response) => {
var db = admin.database();
var ref = db.ref("/07D0921210004");//This 07D0921210004 is the machineID
ref.on("value", function (snapshot) {
var water = snapshot.val().water;
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken); 
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+1501***2661',
to: '+155586***10'
})
.then(message => console.log(message.sid));


},);
});

这是我的数据库结构

{
07D0921210004 
{
Date:"value"
Water:"value"
}
}

当我的实时数据库中的水的值发生变化时。。。

这种触发器被称为后台触发器,对于实时数据库,云函数看起来像:

exports.sendSMS = functions.database.ref('{machineId}')
.onCreate((snapshot, context) => {
// Value of the node
const nodeValue = snapshot.val();
// ....
});

问题中的云函数代码用于HTTPS云函数,该函数通过HTTP请求触发(类似于REST API端点(。因此,当实时数据库中发生事件时,它不会被触发。


因此,您应该按照以下几行调整代码(未经测试(。注意async/await的使用,以考虑create()方法和云功能生命周期管理的异步性

exports.sendSMS = functions.database.ref('{machineId}')
.onCreate(async (snapshot, context) => {

// Value of water
var water = snapshot.val().water;
const accountSid = ...
const authToken = ...
const client = require('twilio')(accountSid, authToken); 

const message = await client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+1501***2661',
to: '+155586***10'
});

console.log(message.sid)
return null;
});

最新更新