获取视图不会在我的 Flask 聊天机器人上返回有效的响应错误消息 [英] Getting a view does not return a valid response error message on my flask chatbot

查看:35
本文介绍了获取视图不会在我的 Flask 聊天机器人上返回有效的响应错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在 Twilio 上创建一个 whatsapp 机器人,以限制用户在 24 小时内可以发出的请求数量.

Trying to create a whatsapp bot on Twilio that limits the number of requests a user can make within a 24 hour period.

但是,当我发送请求时,我在 ngrok 上收到此错误消息

However, when I send through a request I get this error message on ngrok

  File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
    "The view function did not return a valid response. The"
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.

这是我在 twilio 控制台上看到的:

This is what I see on my twilio console:

MESSAGE
Internal Server Error

在我的终端上:

File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 2097, in make_response
    "The view function did not return a valid response. The"

这是我写的代码

from flask import Flask, request
import requests
from twilio.twiml.messaging_response import MessagingResponse
import random
from pathlib import Path
from twilio.rest import Client
from datetime import datetime
import pytz
import re

app = Flask(__name__)
#this will store information about user session such as the time of user's first request and request counter
sessionStorage = {}
#addng user to session storage with current time and setting request counter to 0
time = datetime.now(pytz.timezone('Africa/Harare'))
counter = 0
def add_user(user):
    sessionStorage[user] = {}
    #time when first session starts
    sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
    sessionStorage[user][counter] = 0
#checking if user can perform a request and updating time if required
def request_check(user):
    difference = sessionStorage[user][time] - datetime.now(pytz.timezone('Africa/Harare'))
    #check if it has been 24 hours after first request, if so then reset request counter and set last request time to current time
    sessionStorage[user][counter] = 0
    sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))
    #if user requests exceed 5 then do not allow any more requests
    if sessionStorage[user][counter] > 5:
        return False
    #in other cases allow user to continue requesting
    return True
#function to increment request counter for current user
def increment_request_counter(user):
    sessionStorage[user][counter] +=1

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    #extract phone number from ngrok
    number = request.values.get('From', '')
    #remove non numerical values
    cleaned_number = re.sub('[^0-9]', '', number)
    msg = resp.message()
    #create new user
    add_user(user=cleaned_number)
    responded = False
    if request_check(user=cleaned_number):
        if incoming_msg == 'help':
            output = 'Introduction text.'
            msg.body(output)
        responded = True
        if 'testing' in incoming_msg:
            msg.body(cleaned_number)
            responded = True
        if 'a' in incoming_msg:
            pre = 'More text
            msg.body(pre)
            responded = True
        if 'b' in incoming_msg:
            pre = 'Test text'
            msg.body(pre)
            responded = True
        if 'c' in incoming_msg:
            pre = 'I do not currently have any stats challanges, but will be adding a few soon.'
            msg.body(pre)
            responded = True
        if not responded:
            msg.body('Test message.')
            return str(resp)
        increment_request_counter(user=cleaned_number)

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

当我尝试添加逻辑以限制用户在 24 小时内可以发出的请求数时,问题就开始了

The problem started when I tried to add the logic to limit the number of requests a user can make within a 24 hour period

推荐答案

问题是您没有返回flask 认为是有效响应的响应.您可以在此处阅读有关flask中响应的更多信息.

The problem is that you are not returning a response which flask thinks as a valid response. You can read more about responses in flask here.

因此,在您的情况下,在 if request_check(user=cleaned_number): 下的 bot() 方法中的所有 ifs 之后添加一个 return.你也不应该return None.我认为您希望返回一个 json(只是一个建议).

So in your case add a return after all of your ifs under if request_check(user=cleaned_number): in bot() method. Also you should not return None. I think you are looking to return a json (just an advice).

例如:

@app.route('/bot', methods=['POST'])
def bot():
    incoming_msg = request.values.get('Body', '').lower()
    resp = MessagingResponse()
    #extract phone number from ngrok
    number = request.values.get('From', '')
    #remove non numerical values
    cleaned_number = re.sub('[^0-9]', '', number)
    msg = resp.message()
    #create new user
    add_user(user=cleaned_number)
    responded = False
    if request_check(user=cleaned_number):
        if incoming_msg == 'help':
            output = 'Introduction text.'
            msg.body(output)
            responded = True
            return "My Message"

这篇关于获取视图不会在我的 Flask 聊天机器人上返回有效的响应错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆