Skip to main content
 首页 » 编程设计

python之使用 Twilio/Flask 转发 SMS 的模式验证警告

2025年02月15日7birdshome

我的代码接收传入的 SMS 文本消息,提取正文并将正文转发到另一个号码。 (tPhone 是 Twilio 号码,ePhone 是我要转发消息的号码)

import twilio.twiml 
from flask import Flask, request, redirect 
from twilio.rest import TwilioRestClient 
from passwords import * 
 
client = TwilioRestClient(account_sid, auth_token) 
 
app = Flask(__name__) 
 
@app.route("/", methods=['GET', 'POST']) 
def AlertService(): 
    TheMessage=request.form.get("Body") 
    if (TheMessage != None): 
        print(TheMessage) 
        client.messages.create(to=ePhone, from_=tPhone, body=TheMessage) 
    return str(TheMessage) 
 
if __name__ == "__main__": 
    app.run(debug=True,host="0.0.0.0") 

代码有效(消息被转发)但 Twilio 调试器告诉我

Content is not allowed in prolog.

Warning - 12200

Schema validation warning

The provided XML does not conform to the Twilio Markup XML schema.

如何修复发送到 Twilio 的 XML?


编辑:我发现的一些东西。即使我将“TheMessage”设置为预定义的字符串(例如 TheMessage="hello"),我也会从 Twilio 收到相同的错误。

此外,如果我尝试生成并发送 XML,我仍然会遇到同样的错误。

    resp = twiml.Response() 
    XML = resp.message(TheMessage) 
    print(XML) 
    client.messages.create(body=str(XML),to=ePhone,from_=tPhone) 

如果我尝试 body=XML,代码将无法发送,如果我尝试 body=str(XML),它只会将 XML 作为纯文本发送。

请您参考如下方法:

此处为 Twilio 开发人员布道师。

目前您似乎正在使用 REST API to forward the SMS message .虽然您可以这样做,但使用起来更容易 TwiML使用 <Message> verb 在请求中执行此操作.在您的第二个示例中,您似乎在尝试同时使用 TwiML 和 REST API,但这行不通。

因此,您只想建立一个 TwiML 响应,如果有传入消息,则将消息添加到其中,然后使用 <Message> attributes to and from 将其转发到您的电话号码。像这样:

import twilio.twiml 
from flask import Flask, request, redirect 
from passwords import * 
 
app = Flask(__name__) 
 
@app.route("/", methods=['GET', 'POST']) 
def AlertService(): 
    TheMessage=request.form.get("Body") 
    resp = twiml.Response() 
    if (TheMessage != None): 
        resp.message(TheMessage, to=ePhone) 
    return str(resp) 
 
if __name__ == "__main__": 
    app.run(debug=True,host="0.0.0.0") 

让我知道这是否有帮助。