用于列出和可选删除Twilio消息和相关媒体的示例PHP脚本?

时间:2018-03-12 22:53:19

标签: twilio-php

以下PHP示例列出并可选地删除SMS和MMS消息以及相关的媒体附件。

1 个答案:

答案 0 :(得分:0)

在下面的示例中,"来自"和"到"已指定数字,$delete设置为false

$client = new Client($twilio_sid, $twilio_token);
$params = array(
    'from' => '+15555555555',
    'to'   => '+16666666666'
);
$delete = false;

$smsCounter = 0;
$mmsCounter = 0;
$mediaCounter = 0;

echo "<div style='font-family:monospace;'>";
foreach ($client->messages->read($params) as $message) {
    if (substr($message->sid, 0, 1) == "S") {
        $smsCounter++;
        echo "SMS #{$smsCounter} SID: {$message->sid} from {$message->from} to {$message->to}.<br>";
    }
    else {
        $mmsCounter++;
        echo "MMS #{$mmsCounter} SID: {$message->sid} from {$message->from} to {$message->to}.<br>";

        $allMedia = $client->messages($message->sid)->media->read();
        if (count($allMedia) > 0) {
            foreach ($allMedia as $media) {
                $mediaCounter++;
                echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Attachment SID: {$media->sid}.<br>";

                if ($delete) {
                    $media->delete($media->sid);
                }
            }  
        }
        else {
            echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;No attachments found.<br>";
        }
    }

    if ($delete) {
        $message->delete($message->sid);
    }
}

echo "<br>{$smsCounter} SMS message" . ($smsCounter === 1 ? "" : "s") . " found" . ($delete ? "and deleted." : ".");
echo "<br>{$mmsCounter} multimedia message" . ($mmsCounter === 1 ? "" : "s") ." found" . ($delete ? "and deleted." : ".");
echo "<br>{$mediaCounter} media attachment" . ($mediaCounter === 1 ? "" : "s") ." found" . ($delete ? "and deleted." : ".");

要同时删除邮件和关联的媒体附件,$delete也可以设置为true

要查看与该帐户相关联的所有邮件和媒体的列表,可以从第一个$params中省略foreach,以便该行显示如下:

foreach ($client->messages->read() as $message) {