[英]How to retrieve SMS message after a given date with python in Twilio API
[英]How to output the twilio sms logs in a csv file using Python API
我正在使用此腳本從Twilio下載短信日志文件。
https://github.com/asplunker/twilio-app/blob/master/bin/get_sms_logs.py
在第一次運行中,它正確下載了文件,但是在第二次運行中,它拋出了“ index out of range error "
因此,該函數中懷疑有錯誤:
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文件是否未在一行中指定每個記錄。
任何指針將不勝感激。
我會添加一些錯誤處理,以查找故障時對象的狀態。
您曾經使用try / except嗎? https://docs.python.org/2/tutorial/errors.html
基本上你可以這樣設置
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
我能想到的第一件事是未正確讀取您的CSV文件。
索引不足錯誤可能在這里發生:
date = line.split(',')[1]
嘗試添加一個有條件的日期:
date_ = line.split(',') date = date_[1] if len(date_) >= 1 else ""
但您真的應該看看標准庫中的CSV
關於如何導出短信/呼叫日志的常見問題解答顯示了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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.