Twilio& NodeJS:无法查找和删除媒体实例/资源

时间:2015-01-28 04:41:35

标签: arrays node.js rest callback twilio

我正在使用Twilio的NodeJS模块&用于发送带有附加图像的MMS消息的API(来自远程URL),我希望在发送消息后立即删除在Twilio服务器上创建的Media实例。

我的消息正确发送,在回调中,我试图1)列出当前消息的媒体实例,然后2)循环遍历这些实例并删除。问题是从API返回的当前消息的mediaList数组始终为空。

这是我的代码:

twilio_client.messages.create({
    body: "Thanks for taking a photo. Here it is!",
    to: req.query.From,
    from: TWILIO_SHORTCODE,
    mediaUrl: photo_URL,
    statusCallback: STATUS_CALLBACK_URL
    }, function(error, message) {
        if (!error) {

            twilio_client.messages(message.sid).media.list(function(err, data) {
                console.log(data);
                // The correct object comes back as 'data' here per the API
                // but the mediaList array is empty
            }

            console.log('Message sent via Twilio.');
            res.status(200).send('');
        } else {
            console.log('Could not send message via Twilio: ');
            console.log(error);
            res.status(500).send('');
        }
});

1 个答案:

答案 0 :(得分:1)

因此,事实证明,试图获取媒体列表时,我试图不起作用,因为媒体实例尚未存在。

我在statusCallback上运行了一个单独的小应用程序(我通过上面代码中的常量提供了一个URL,STATUS_CALLBACK_URL),直到现在,我只是检查了我试图向用户发送彩信的消息是不是&#39 ;由Twilio正确处理,并通过短信提醒用户注意问题。所以,我在同一个应用程序中添加了一个检查,以查看该消息是否实际上已发送'对用户,然后检查并删除与该消息相关联的媒体实例,并且它工作正常。这是我的代码:

// issue message to user if there's a problem with Twilio getting the photo
if (req.body.SmsStatus === 'undelivered' || req.body.SmsStatus === 'failed') {
    twilio_client.messages.create({
    body: "We're sorry, but we couldn't process your photo. Please try again.",
    to: req.body.To,
    from: TWILIO_SHORTCODE
    }, function(error, message) {
        if (!error) {
            console.log('Processing error message sent via Twilio.');
            res.send(200,'');
        } else {
            console.log('Could not send processing error message via Twilio: ' + error);
            res.send(500);
        }
    });
}

// delete media instance from Twilio servers
if (req.body.SmsStatus === 'sent') {
    twilio_client.messages(req.body.MessageSid).media.list(function(err, data) {
        if (data.media_list.length > 0) {
            data.media_list.forEach(function(mediaElement) {
              twilio_client.media(mediaElement.sid).delete;
              console.log("Twilio media instance deleted"); 
            });
        }
    });
}
相关问题