这就是我想要完成的事情:
在高层,这个想法似乎很直接。但是,我的编程/语法技巧很生疏,我很乐意帮助你。
我正在使用Twilio Functions,我已经能够成功发送和接收消息。现在我被困在如何实现迭代组的想法。
这是我到目前为止所写的内容:
var groupmembers = {
jonathan:{
name: 'Jonathan',
number: '+0000000000'
},
joshua:{
name: 'Joshua',
number: '+1110000000'
}
}
exports.handler = function(context, event, callback) {
// Set some values for later use
this.fromNumber = event.From
this.body = event.Body || ''
let twiml = new Twilio.twiml.MessagingResponse();
groupmembers.forEach(function(member) {
// Skip sending if it's the same number
if (member.number === this.fromNumber ) {
return;
}
// Otherwise, let's send a mesage!
twiml.message("Hello World").to( member.number );
callback(null, twiml);
});
};
我相信我的问题:
message
感谢您提供任何反馈,并指出我正确的方向!
答案 0 :(得分:3)
你犯的错误非常简单。 groupmembers
是一个对象,你想要一个数组。
您可能需要类似于此的内容:
var groupmembers = [{
name: 'Jonathan',
number: '+0000000000'
},
{
name: 'Joshua',
number: '+1110000000'
}]
除此之外,它看起来还不错。
答案 1 :(得分:3)
随着更多的搜索和Slava的正确方向,我能够弄明白!这是完整的代码:
/**
* Represents a search trough an array.
* @function search
* @param {Array} array - The array you wanna search trough
* @param {string} key - The key to search for
* @param {string} [prop] - The property name to find it in
* Props: https://stackoverflow.com/a/33097318/315818
*/
function search(array, key, prop){
// Optional, but fallback to key['name'] if not selected
prop = (typeof prop === 'undefined') ? 'name' : prop;
for (var i=0; i < array.length; i++) {
if (array[i][prop] === key) {
return array[i];
}
}
}
var groupmembers = [
{
name: 'Jonathan',
number: '+000000000'
},
{
name: 'Joshua',
number: '+111111111'
}
];
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.MessagingResponse();
// Search for the group member that matches the sender number
let sender = search(groupmembers, event.From, 'number');
// Now, loop through each of the group members
groupmembers.forEach(function(member) {
// Skip sending if it's the same number
if (member.number === event.From ) {
return;
}
// Now, forward on the message to the group member, using the sender's name
twiml.message(`${sender.name}: ${event.Body}`, {
to: member.number
});
});
// Loop ended
callback(null, twiml);
};