如何使用Python API将Twilio短信日志输出为CSV文件

0 投票
3 回答
752 浏览
提问于 2025-04-18 16:40

我正在使用这个脚本从Twilio下载短信日志文件。

https://github.com/asplunker/twilio-app/blob/master/bin/get_sms_logs.py

第一次运行时,文件下载得很好,但第二次运行时出现了“索引超出范围错误”。

所以这个错误可能出现在这个函数里:

def write_records():
# avoid duplicates

data = []
if os.path.exists(LOG_FILE):
    with codecs.open(LOG_FILE) as d:
        file_data = d.readlines()
        for line in file_data:
            print line
            date = line.split(',')[1]
            if  date == LAST_ENTRY:
                    data.append(date)

with codecs.open(LOG_FILE, 'a') as f:
    for record in reversed(RECORDS):
        if not record.split(',')[1] in data:
            f.write(record)
            f.write('\n')

我不确定第一次运行生成的csv文件是否每条记录都在单独的一行。

如果能给点建议,我会非常感激。

3 个回答

0

关于如何导出你的短信和通话记录的常见问题解答中,给出了一个用PHP写的CSV示例。我自己是个Python爱好者,不过根据情况,我会用这个方法快速测试一下。

<!--?php <br ?-->/**
 * Download the library from: https://github.com/twilio/twilio-php
 * Copy the 'Services' folder into a directory containing this file.
 */
require('Services/Twilio.php');

$account_sid = "ACXXXXXXXXX"; // Your Twilio account sid
$auth_token = "YYYYYYYYYYYY"; // Your Twilio auth token

// Download data from Twilio API
$client = new Services_Twilio($account_sid, $auth_token);
$messages = $client->account->sms_messages->getIterator(0, 50, array(
    'DateSent>' => '2012-09-01',
    'DateSent<' => '2012-09-30',
    //'From' => '+17075551234', // **Optional** filter by 'From'...
    //'To' => '+18085559876', // ...or by 'To'
));

// Browser magic
$filename = $account_sid."_sms.csv";
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename={$filename}");

// Write headers
$fields = array(
    'SMS Message SID', 'From', 'To', 'Date Sent',
    'Status', 'Direction', 'Price', 'Body'
);
echo '"'.implode('","', $fields).'"'."\n";

// Write rows
foreach ($messages as $sms) {
    $row = array(
        $sms->sid, $sms->from, $sms->to, $sms->date_sent,
        $sms->status, $sms->direction, $sms->price, $sms->body
    );
    echo '"'.implode('","', $row).'"'."\n";
}
1

我想到的第一件事是,你的CSV文件可能没有被正确读取。

出现索引超出范围的错误可能是在这里发生的:

date = line.split(',')[1]

你可以在这里加一个条件来处理日期:

date_ = line.split(',') date = date_[1] if len(date_) >= 1 else ""

不过,你真的应该看看标准库里的CSV模块。

https://docs.python.org/2/library/csv.html

1

我建议加一些错误处理,这样可以在出错的时候找到对象的状态。

你有没有用过try/except?

基本上,你可以这样设置:

def write_records():
# avoid duplicates
    try:
        data = []
        if os.path.exists(LOG_FILE):
            with codecs.open(LOG_FILE) as d:
                file_data = d.readlines()
                for line in file_data:
                    print line
                    date = line.split(',')[1]
                    if  date == LAST_ENTRY:
                            data.append(date)

        with codecs.open(LOG_FILE, 'a') as f:
            for record in reversed(RECORDS):
                if not record.split(',')[1] in data:
                    f.write(record)
                    f.write('\n')

    except IndexError:
        #log variables here and examine the issue closely

撰写回答