TwilioAPI:使用python创建发送SMS的函数
我成功地编写了一个python脚本,它使用TwilioAPI将短信发送到我的已验证电话号码。 代码如下:TwilioAPI:使用python创建发送SMS的函数,python,api,twilio,Python,Api,Twilio,我成功地编写了一个python脚本,它使用TwilioAPI将短信发送到我的已验证电话号码。 代码如下: 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, aut
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")
这一定很简单,但是。。。。如何将其封装在一个好的函数中,这样我唯一需要提供的就是body变量
像这样:发送短信(body=“whatever”)
我试图这样做,但create函数抱怨:
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)
尝试调用
message=client.messages.create(to,from,body)
asmessage=client.messages.create(to=to,from=from,body=body)
请参见messages.create()函数的函数签名
您将to、from和body作为位置参数传递,但create函数只接受两个参数(一个默认参数和“self”),其余参数必须作为关键字参数传递。这就是为什么回溯说,当您传递4(self、to、from、body)时,函数只接受2个参数(self和from) 是的。。。您需要传递关键字参数-create(from=from,body=body)而不是常规的Python参数-create(from,body)非常感谢。现在就可以了。我真的很难理解*和**结构。
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)