如何处理来自 Twilio REST API 的响应

问题描述 投票:0回答:2

我正在开发一个项目来帮助治疗抑郁症。我对 Twilio 没有深入的了解。我想收集对此消息的回复:

Sent from your Twilio trial account - What are the positive results or outcomes you have achieved lately?
What are the strengths and resources you have available to you to get even more results and were likely the reason you got the results in the first question.
What are your current priorities? What do you and your team need to be focused on right now?
What are the benefits to all involved-you
 your team and all other stakeholders who will be impacted by achieving your priority focus.
How can we (you and/or your team) move close? What action steps are needed?
What am I going to do today?
What am I doing tomorrow ?
What did I do yesterday?

并处理它们1-9。响应将按 1-9 进行枚举。

我已联系 Twilio 支持人员并阅读了这些文档 https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-python

这是我尝试过的:

# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
import logging
import csv
import psycopg2
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

app = Flask(__name__)

logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

# Set environtment variables
DATABASE = os.environ["DATABASE"]
PASSWORD = os.environ["PASSWORD"]
PORT     = os.environ["PORT"]
USER     = os.environ["USER"]
HOST     = os.environ["HOST"]


# initialization TODO: move into env vars
MY_PHONE_NUMBER        = os.environ["MY_PHONE_NUMBER"]
TWILIO_PHONE_NUMBER    = os.environ["TWILIO_PHONE_NUMBER"]
TWILIO_ACCOUNT_SID     = os.environ["TWILIO_ACCOUNT_SID"]
TWILIO_AUTH_TOKEN      = os.environ["TWILIO_AUTH_TOKEN"]

# Configure Twillio
# Set environment variables for your credentials
# Read more at http://twil.io/secure
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
logging.debug(f"Connected to Twilio using MY_PHONE_NUMBER:{MY_PHONE_NUMBER},TWILIO_PHONE_NUMBER{TWILIO_PHONE_NUMBER}")

# Establish db connection
# use psycopg to connect to the db and create a table
conn = psycopg2.connect(
database=DATABASE, user=USER, password=PASSWORD, host=HOST, port=PORT)
conn.autocommit = True
cursor = conn.cursor()


# Step 1: Set up frequency, i.e. times to send messages

# Step 2: Load questions
questionsFile   = open('questions.csv')
questions = csv.reader(questionsFile)
logging.debug(f"message:{questions}")
message = "\n".join([question for row in questions for question in row])
logging.debug(f"message: {message}")

# Step 3: Send questions
# message = client.messages.create(
#   body=message,
#   from_=TWILIO_PHONE_NUMBER,
#   to=MY_PHONE_NUMBER
# )

# Step 4: Collect response
@app.route("/sms", methods=['GET', 'POST'])
def incoming_sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    if body == 'hello':
        resp.message("Hi!")
    elif body == 'bye':
        resp.message("Goodbye")

    return str(resp)


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

# Step 5: Create a database table as the sheet name and Save responses in db
logging.debug(f'Step 2 creating table response')
# TODO: create 10 columns for saving responses (each response contains 10 answers)
sql = f'CREATE TABLE IF NOT EXISTS public.responses'
logging.debug(f'CREATE TABLE IF NOT EXISTS public.responses')
# cursor.execute(sql)
# conn.commit()

# Next steps:
# 1. Process positive and negative sentiment from responses
# 2. Calculuate total positive sentiment
# 3. Calculate  total negative sentiment
# 4. Plot positive sentiment vs. negative sentiment

文档没有提供完成步骤 4 的明确路径。

[显示短信回复。]

[消息网址]

预计 处理问题的答复。

实际:

Sent from your Twilio trial account - What are the positive results or outcomes you have achieved lately?
What are the strengths and resources you have available to you to get even more results and were likely the reason you got the results in the first question.
What are your current priorities? What do you and your team need to be focused on right now?
What are the benefits to all involved-you
 your team and all other stakeholders who will be impacted by achieving your priority focus.
How can we (you and/or your team) move close? What action steps are needed?
What am I going to do today?
What am I doing tomorrow ?
What did I do yesterday?

我添加了 Twilio 流来测试与 Twilio 的连接。这可以通过 Python 或使用 Twilio 流向两个方向进行。即使添加了正确的数字后,流程也不起作用。

messages screenshot

python twilio
2个回答
0
投票

您链接的页面上有第二个代码示例。这解释了如何解析传入消息的正文以使用 request.values.get('Body', None)

:
读取有效负载

@app.route("/sms", methods=['GET', 'POST']) def incoming_sms(): """Send a dynamic reply to an incoming text message""" # Get the message the user sent our Twilio number body = request.values.get('Body', None) # Start our TwiML response resp = MessagingResponse() # Determine the right reply for this message if body == 'hello': resp.message("Hi!") elif body == 'bye': resp.message("Goodbye") return str(resp)
但是,互相提问是有意义的,这意味着您需要处理许多不同的端点,而且它很快就会变得复杂。

但是还有一个可视化编辑器,允许您在浏览器中几分钟内定义它: 使用 Twilio Studio 构建聊天机器人


0
投票
call = client.calls.create( twiml='<Response><Say>Ahoy there!</Say></Response>', to='+15558675310', from_='+15552223214' ) print(call.__dict__)
    
© www.soinside.com 2019 - 2024. All rights reserved.