Twilio SMS Python - Simple send a message

こ雲淡風輕ζ 提交于 2019-12-30 12:15:14

问题


New to Twilio, have followed the SMS Python Quickstart guide successfully, and have combined two bits together, but now have some redundant code that I can't seem to get rid of without getting errors.

I have Python code that takes in coordinates from a text message, converts this into a Google Maps link, and sends that link to a different phone number.

However, currently it is also sending this reply to the original sender phone number, as that is what the original guide has you set up.

I only want it to send the message to the specified number, not reply to the original sender.

run.py:

# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse


# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'account_sid'
auth_token = 'auth_token'
client = Client(account_sid, auth_token)


app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def sms_reply():

    messages = client.messages.list()

    print(messages[0].body)

    coord = messages[0].body

    lat,lon = coord.split(":")

    mapURL = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + lon

    message = client.messages.create(
        body=mapURL,
        from_='+442030954643',
        to='+447445678954'
    )

    """Respond to incoming messages with a friendly SMS."""
    # Start our response
    resp = MessagingResponse()

    # Add a message
    resp.message(mapURL)

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

Whenever I take out the lines I think are to do with the replying message to sender, it seems to break some of the other lines that I still need.

Any help much appreciated, thanks!


回答1:


It's because your output in your sms_reply function is returning a TwiML that sends a message. I think it's normal to have some feedback from the service. If you don't want to reply with the mapURL you can just say somethink like "Thank you".

Otherwise, you can take a look to TwiML documentation to see what other actions you can do.




回答2:


Twilio developer evangelist here.

You don't need to reply back to the incoming message and you can avoid this by returning an empty TwiML response.

As an extra win here, you don't have to call the API to get the body of the last message that was sent. That will be available in the POST request parameters to the endpoint. You can access those via request.form so the Body parameter will be available at request.form['Body'].

Try something like this:

# /usr/bin/env python
# Download the twilio-python library from twilio.com/docs/libraries/python
from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse


# Download the helper library from https://www.twilio.com/docs/python/install
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
account_sid = 'account_sid'
auth_token = 'auth_token'
client = Client(account_sid, auth_token)

app = Flask(__name__)

@app.route("/", methods=['GET', 'POST'])
def sms_reply():
    coord = request.form['Body']
    lat,lon = coord.split(":")
    mapURL = "https://www.google.com/maps/search/?api=1&query=" + lat + "," + lon

    message = client.messages.create(
        body=mapURL,
        from_='+442030954643',
        to='+447445678954'
    )

    # Start our empty response
    resp = MessagingResponse()
    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)


来源:https://stackoverflow.com/questions/51169705/twilio-sms-python-simple-send-a-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!