您可以尝试这样的操作,将 Twilio Assets 上的映射作为私有资产托管,但如果您将其托管在外部服务器上,您也可以通过 HTTP 请求小部件将这些信息拉入 Studio(更高级一些)。就我而言,我调用了具有以下格式的文件 mapping.json:
[
{
"name": "John Doe",
"phone": "+14075551212",
"email": "jdoe@example.com"
},
{
"name": "Susan Doe",
"phone": "+19545551212",
"email": "sdoe@example.com"
},
{
"name": "Nadia Doe",
"phone": "+14705551212",
"email": "ndoe@example.com"
},
{
"name": "Carl Doe",
"phone": "+18025551212",
"email": "cdoe@example.com"
}
]
然后您将使用 Run Function 小部件并发送 3 个键:值对(函数参数):
来自 - {{trigger.message.From}}
致-{{trigger.message.To}}
正文 - {{trigger.message.Body}}
然后,您的 Twilio 函数将使用这些参数和私有资产的内容来处理映射。确保使用 Sendgrid NPM 包 configure 您的 Twilio Functions 环境,@sendgrid/mail 版本 7.0.1 并使用它们各自的值配置下面的两个 Sendgrid 特定环境变量(通过 JavaScript 中的上下文对象访问):
SENDGRID_API_KEY
FROM_EMAIL_ADDRESS
const fs = require('fs');
const sgMail = require('@sendgrid/mail');
exports.handler = function(context, event, callback) {
let from = event.From;
let to = event.To;
let body = event.Body;
let fileName = 'mapping.json';
let file = Runtime.getAssets()[fileName].path;
let text = fs.readFileSync(file);
let mappings = JSON.parse(text);
// Filter array to match to number
let result = mappings.filter(record => record.phone === to);
if (result.length) {
sgMail.setApiKey(context.SENDGRID_API_KEY);
// Define message params
const msg = {
to: result[0].email,
from: context.FROM_EMAIL_ADDRESS,
text: body,
subject: `New SMS from: ${from}`,
};
// Send message
sgMail.send(msg)
.then(response => {
console.log("Success.");
callback();
})
.catch(err => {
console.log("Not Success.");
callback(err);
});
} else {
console.log("** NO MATCH **");
callback();
}
};
告诉我进展如何。