You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twilio Autopilot中从接收的SMS获取发送方手机号?

获取Twilio SMS发送方手机号并传入Autopilot上下文

1. 从Twilio Webhook请求提取发送方号码

当用户发送短信到你的Twilio号码时,Twilio会向配置的messaging URL发送POST请求,请求参数里的From字段就是发送方的手机号(格式为E.164标准,比如+1234567890)。

用Python Flask处理的示例代码:

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import json

app = Flask(__name__)

# 替换为你的Twilio账户SID和助手SID
YOUR_ACCOUNT_SID = "你的账户SID"
YOUR_ASSISTANT_SID = "你的助手SID"

@app.route("/sms", methods=['POST'])
def handle_sms():
    # 提取发送方手机号
    sender_phone = request.form.get('From')
    
    # 根据手机号查询用户信息,构造上下文数据
    user_context = {"sender_phone": sender_phone, "user_profile": "已匹配用户"}
    
    # 跳转到Autopilot并携带上下文
    resp = MessagingResponse()
    autopilot_url = f"https://channels.autopilot.twilio.com/v1/Accounts/{YOUR_ACCOUNT_SID}/Assistants/{YOUR_ASSISTANT_SID}/Tasks?Memory={json.dumps(user_context)}"
    resp.redirect(autopilot_url)
    
    return str(resp)

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

2. 在Autopilot自定义函数中使用上下文

如果使用Autopilot的自定义运行时函数(Python),可以直接从event对象获取发送方号码,或读取传入的上下文:

def handler(event, context):
    # 直接从event中获取发送方手机号
    sender_phone = event['From']
    
    # 读取传入的上下文数据
    memory = event.get('Memory', {})
    user_profile = memory.get('user_profile', '未匹配用户')
    
    return {
        "actions": [
            {
                "say": f"您好,已识别您的手机号:{sender_phone},当前用户状态:{user_profile}"
            }
        ]
    }

3. 关键注意点

  • 确保webhook端点能接收Twilio的POST请求,且返回合法的Twiml或Autopilot跳转指令
  • From字段是国际标准号码格式,匹配用户时需保持格式统一
  • 若需要持久化上下文,可将手机号作为键,存储到Redis、PostgreSQL等数据库中,后续请求直接读取

内容的提问来源于stack exchange,提问作者brrrrrrrrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:54:27