twilio API:创建一个用python发送短信的功能

时间:2014-01-11 21:14:26

标签: python api twilio

我成功制作了一个python脚本,使用Twilio API将SMS发送到我已验证的电话号码。 这是代码:

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变量??

像这样:send_sms(body =“whatever”)

我尝试这样做,但创建函数抱怨:

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)

1 个答案:

答案 0 :(得分: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_和body,但是create函数只接受两个参数(一个默认值和'self'),其余的必须作为关键字参数传递。这就是为什么回溯表示当你传递4(self,to,from_,body)时函数只接受2个参数(self和from_)的原因。