Получение представления не возвращает действительное сообщение об ошибке ответа на мой flask чатбот - PullRequest
0 голосов
/ 24 марта 2020

Попытка создания бота WhatsApp на Twilio, который ограничивает количество запросов, которые пользователь может сделать в течение 24 часов.

Однако, когда я отправляю запрос, я получаю это сообщение об ошибке на 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:

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)

Проблема началась, когда я попытался добавить логи c, чтобы ограничить количество запросов, которые пользователь может сделать в течение 24 часов

1 Ответ

0 голосов
/ 24 марта 2020

Проблема в том, что вы не возвращаете ответ, который flask считает действительным. Вы можете прочитать больше об ответах в flask здесь .

Так что в вашем случае добавьте return после всех ваших ifs под if request_check(user=cleaned_number): в bot() методе. Также не стоит return None. Я думаю, что вы хотите вернуть json (просто совет).

Например:

@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"

...