2014-01-11 37 views
0

我成功地製作了一個python腳本,該腳本使用Twilio API將SMS發送到我驗證過的電話號碼。 這是代碼:twilio API:使用python發送短信功能

from twilio.rest import TwilioRestClient 


# Your Account Sid and Auth Token from twilio.com/user/account 
account_sid = "the sid" 
auth_token = "the token" 
client = TwilioRestClient(account_sid, auth_token) 


to = "+the number" # Replace with your phone number 
from_ = "+number" # Replace with your Twilio number 
message = client.messages.create(to,from_,body="the message") 

它必須是相當簡單的,但....我怎麼能在一個不錯的功能,所以,我要提供的僅僅是身體變包裹這件事?

像這樣:send_sms(身體= 「無所謂」)

我試圖做這樣的,但創建功能抱怨:

def sendsms(body="vsdvs"): 
    # Your Account Sid and Auth Token from twilio.com/user/account 
    account_sid = "fgdfgdfg" 
    auth_token = "dfgdfgdfg" 
    client = TwilioRestClient(account_sid, auth_token) 


    to = "6345354" # Replace with your phone number 
    from_ = "43534534" # Replace with your Twilio number 
    message = client.messages.create(to,from_,body) 

sendsms() 

我得到的錯誤是:

message = client.messages.create(to,from_,body) 
TypeError: create() takes at most 2 arguments (4 given) 

回答

0

嘗試撥打message = client.messages.create(to,from_,body)作爲message = client.messages.create(to=to,from_=from_,body=body)

查看函數messages.create()函數的簽名here

class Messages(ListResource): 
    name = "Messages" 
    key = "messages" 
    instance = Message 

    def create(self, from_=None, **kwargs): 
     """ 
     Create and send a Message. 

     :param str to: The destination phone number. 
     :param str `from_`: The phone number sending this message 
      (must be a verified Twilio number) 
     :param str body: The message you want to send, 
      limited to 1600 characters. 
     :param list media_url: A list of URLs of images to include in the 
      message. 
     :param status_callback: A URL that Twilio will POST to when 
      your message is processed. 
     :param str application_sid: The 34 character sid of the application 
      Twilio should use to handle this phone call. 
     """ 
     kwargs["from"] = from_ 
     return self.create_instance(kwargs) 

你傳遞給,from_和身體的位置參數,但創建函數只有兩個參數(一個默認和「自我」),其餘有作爲關鍵字參數傳遞。這就是traceback在傳遞4(self,to,from_,body)時只表示函數只帶2個參數(self和from_)的原因。

+0

是......你需要傳遞關鍵字參數 - 創建(from_ = from,body = body)而不是常規的Python參數 - 創建(from,body) –

+0

非常感謝。現在沒關係。我真的很難理解*和**結構。 –