这是我在这里的第一篇文章,如果有任何不正确的地方,我深表歉意。我一直在尝试通过twilio检索SMS的正文。最终目标是有一个基本的聊天机器人,我可以在文本上使用,但我不想在一个Python文件中编写所有代码。这就是把它拉出来的目的。
我正在寻找一些关于我下一步应该去哪里的指导。要从以下错误开始:
Traceback (most recent call last):
File "main.py", line 24, in <module>
print (sms_reply().message_body)
File "/home/pi/PythonScripts/BasicSMSBot/SMSIncoming.py", line 18, in
sms_reply
message_body = request.form['Body']
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 347,
in __getattr__
return getattr(self._get_current_object(), name)
File "/usr/local/lib/python3.4/dist-packages/werkzeug/local.py", line 306,
in _get_current_object
return self.__local()
File "/usr/local/lib/python3.4/dist-packages/flask/globals.py", line 37, in
_lookup_req_object
raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.从表面上看,我想把身体拉出来的方式有些问题。
以下是当前SMSIncoming中的代码:
#importing nessisary scripts and files
import os
#import SMSOutgoing
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
#initilizing the global user variable
#glo_user_var = (' T ');
#initilizing app
app = Flask(__name__)
@app.route("/sms", methods=["GET", "POST"])
def sms_reply():
resp = MessagingResponse()
#body = request.values.get('Body', None)
message_body = request.form['Body']
#for debuging the SMS instercept
#saveFile = open('bodyfile.txt', 'w')
#saveFile.write(body)
#saveFile.close()
resp.message("Testting the SMS responce")
return str(resp)
return str(body)
#lets main app process run
if __name__ == "__main__":
app.run(debug=True)下面是当前在main.py中的代码
#place all imports and scripts to be run
import os
import SMSOutgoing
from SMSIncoming import sms_reply
#from SMSIncoming.py import app, sms_reply
import time
#call up ngrok and make server on port 5000
#os.system("./ngrok http 5000");
#start running the SMSIncoming app
#if __name__ == "__main__":
# app.run(debug=True)
# have to start apps separately! #
#this block will handle incoming SMS (User Input)
while True:
# global glo_user_var
print (sms_reply().message_body)
#file = open('test_user_input.txt', 'w')
#file.write(glo_user_var)
#file.close()
time.sleep(1)main.py中的所有内容要么被注释掉,要么被放在合适的位置进行测试。
我想打印正文的原因是确保它到达了我想要的位置。之后,我将使用它作为用户输入,这将定义回复。
我还使用ngrok作为我的http webhook。
发布于 2017-06-05 17:21:03
Twilio开发者的布道者在这里。
首先,您遇到的问题是因为您正在将flask应用程序分解为多个文件,并尝试每秒调用一次也是路由的函数。因此,您肯定需要从一开始就删除while True循环。
接下来,我理解您可以看到,如果在一个文件中构建整个应用程序,事情可能会变得不堪重负。然而,您目前过早地进行了优化。我建议您首先在一个文件中让它工作,然后将应用程序重构为更易于管理的块。
根据记录,您正在做正确的事情来获取SMS消息的正文。Twilio message webhook将以表单参数Body的形式发送正文,这样您就能够在对该请求的响应中使用
message_body = request.form['Body']一旦你达到了这个阶段,看看building larger applications上的Flask文档,然后看看building modular applications with Blueprints上的信息。
https://stackoverflow.com/questions/44146329
复制相似问题