Twilio REST API响应处理问题:抑郁症辅助程序开发遇阻
抑郁症辅助治疗程序Twilio集成问题解决
需求说明
- 开发抑郁症辅助治疗程序,需通过Twilio收集用户对9条指定问题的回复,并按1-9项顺序处理
- 已查阅Twilio官方文档并联系支持,仍存在两个核心问题:
- 编写的Python代码仅能发送问题,无法完成回复收集与按顺序处理的步骤
- 配置的Twilio Flow无法正常工作,且当前UI与官方演示视频不符
待收集回复的问题列表
注:第一条包含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?
已尝试的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
核心问题拆解
代码层面问题
现有/sms路由仅能处理固定关键词(hello/bye),未实现:
- 按顺序向用户推送单个问题(而非一次性发送所有)
- 跟踪用户当前回答到第几个问题的状态
- 将用户回复关联到对应问题并存储到数据库
Twilio Flow问题
- 当前Flow界面与演示视频不一致,导致配置逻辑无法匹配
- 未实现多轮对话的状态跟踪,无法引导用户完成9个问题的回复
解决方案实现
1. 代码改造:实现多轮对话与回复收集
核心思路
- 使用用户手机号作为唯一标识,存储当前对话状态(已回答的问题序号)
- 每次收到回复后,先存储该回复到数据库,再推送下一个问题
- 所有问题回复完成后,发送结束提示
改造后代码片段
# 新增:存储用户对话状态(生产环境建议用数据库替代内存字典) user_session = {} # 加载问题列表(按顺序存储) def load_questions(): questions = [] with open('questions.csv', 'r') as f: reader = csv.reader(f) for row in reader: questions.extend(row) # 确保是9个问题 return questions[:9] QUESTIONS = load_questions() @app.route("/sms", methods=['GET', 'POST']) def incoming_sms(): resp = MessagingResponse() body = request.values.get('Body', '').strip() from_number = request.values.get('From', '') # 初始化用户会话 if from_number not in user_session: user_session[from_number] = {'current_question': 0, 'responses': {}} # 发送第一个问题 resp.message(QUESTIONS[0]) return str(resp) current_session = user_session[from_number] current_idx = current_session['current_question'] # 存储当前回复 current_session['responses'][current_idx + 1] = body # 判断是否还有下一个问题 if current_idx + 1 < len(QUESTIONS): current_session['current_question'] += 1 next_question = QUESTIONS[current_session['current_question']] resp.message(next_question) else: # 所有问题完成,保存到数据库 save_responses_to_db(from_number, current_session['responses']) resp.message("感谢你的回复,我们会尽快处理你的信息!") # 清除会话状态 del user_session[from_number] return str(resp) # 新增:保存回复到数据库函数 def save_responses_to_db(phone_number, responses): # 创建完整的表结构 create_table_sql = """ CREATE TABLE IF NOT EXISTS public.responses ( id SERIAL PRIMARY KEY, phone_number VARCHAR(20) NOT NULL, question1 TEXT, question2 TEXT, question3 TEXT, question4 TEXT, question5 TEXT, question6 TEXT, question7 TEXT, question8 TEXT, question9 TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """ cursor.execute(create_table_sql) # 插入数据 insert_sql = """ INSERT INTO public.responses (phone_number, question1, question2, question3, question4, question5, question6, question7, question8, question9) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) """ # 按顺序提取1-9的回复,无内容则用空字符串填充 response_values = [ responses.get(1, ''), responses.get(2, ''), responses.get(3, ''), responses.get(4, ''), responses.get(5, ''), responses.get(6, ''), responses.get(7, ''), responses.get(8, ''), responses.get(9, '') ] cursor.execute(insert_sql, (phone_number, *response_values))
2. Twilio Flow配置修复
核心步骤
- 进入Twilio控制台的Studio页面,创建新的Flow
- 使用Send & Wait for Reply组件实现多轮对话:
- 第一个组件发送第1个问题,等待用户回复
- 添加Split Based On...组件,直接跳转到下一个Send & Wait for Reply组件(无需判断关键词,需收集任意文本回复)
- 重复上述步骤,直到9个问题全部发送完成
- 最后添加Send Message组件发送结束提示
- 将Flow的触发方式设置为Incoming Message,关联到你的Twilio号码
注意事项
- 若当前UI与演示视频不同,优先参考Twilio Studio官方最新文档
- 使用Set Variables组件存储用户当前的问题序号,实现状态跟踪
- 所有回复可通过Flow的Widgets数据传递到你的Flask接口进行存储
后续优化建议
- 将
user_session从内存字典改为数据库存储,避免服务重启丢失状态 - 添加错误处理逻辑(如用户长时间未回复时的提醒)
- 实现定时发送问题的功能(使用Twilio Scheduled Messages或第三方定时任务工具)
内容的提问来源于stack exchange,提问作者Evan Gertis
相关产品推荐
相关产品推荐

