Getting a view does not return a valid response error message on my flask chatbot [duplicate]

2024/11/17 7:29:16

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

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.

This is what I see on my twilio console:

MESSAGE
Internal Server Error

and on my terminal:

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"

Here is the code I wrote

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 reapp = 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 startssessionStorage[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 timesessionStorage[user][counter] = 0sessionStorage[user][time] = datetime.now(pytz.timezone('Africa/Harare'))#if user requests exceed 5 then do not allow any more requestsif sessionStorage[user][counter] > 5:return False#in other cases allow user to continue requestingreturn 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 ngroknumber = request.values.get('From', '')#remove non numerical valuescleaned_number = re.sub('[^0-9]', '', number)msg = resp.message()#create new useradd_user(user=cleaned_number)responded = Falseif request_check(user=cleaned_number):if incoming_msg == 'help':output = 'Introduction text.'msg.body(output)responded = Trueif 'testing' in incoming_msg:msg.body(cleaned_number)responded = Trueif 'a' in incoming_msg:pre = 'More textmsg.body(pre)responded = Trueif 'b' in incoming_msg:pre = 'Test text'msg.body(pre)responded = Trueif 'c' in incoming_msg:pre = 'I do not currently have any stats challanges, but will be adding a few soon.'msg.body(pre)responded = Trueif not responded:msg.body('Test message.')return str(resp)increment_request_counter(user=cleaned_number)if __name__ == '__main__':app.run(debug=True)

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

Answer

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.

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).

For example:

@app.route('/bot', methods=['POST'])
def bot():incoming_msg = request.values.get('Body', '').lower()resp = MessagingResponse()#extract phone number from ngroknumber = request.values.get('From', '')#remove non numerical valuescleaned_number = re.sub('[^0-9]', '', number)msg = resp.message()#create new useradd_user(user=cleaned_number)responded = Falseif request_check(user=cleaned_number):if incoming_msg == 'help':output = 'Introduction text.'msg.body(output)responded = Truereturn "My Message"
https://en.xdnf.cn/q/118827.html

Related Q&A

Django how to add data to Object from queryset

I would like show list of clients and show tags assigned to them but I have problem because I have my tags in other table and I dont know how to connect data together. Clients can have couple of tags o…

before_action ... only: how to do this in python flask? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 5 years ago.Improve…

Destroy function not destroying a frame efficiently after the first iteration in Tkinter Python

I have built a code that saves the calculated data at every iteration in a for loop and the results are stored in 3 different csv files. These saved results are read in another python code that display…

Access columns and rows of numpy.ndarray

I currently struggling with extracting certain columns and rows from a matrix stored as a numpy.ndarray. I have a list in which Ive appended these numpy.ndarrays. This list is stored in a variable name…

How to access instance object in list and display there data? in python

class Bank:def __init__(self, name, balance=0):self.name = nameself.balance = balance# def Display_details(self):# print( self.name),# print(self.balance),#### def Withdraw(self, a):# self.…

Using Class, Methods to define variables

I have a number of chemicals with corresponding data held within a database, how do I go about returning a specific chemical, and its data, via its formula, eg o2.class SourceNotDefinedException(Except…

Python Tkinter: Color changing grid of buttons?

I understand that you can make a button that can do some actions when clicked with Tkinter, but how can I just make a button that turns from one color to another when clicked? Then, from that, how do …

Writing a function that checks prime numbers

def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False breakelse: return TrueIm trying to make a function that checks if an input is prime or not. This code does …

Getting error code 1 while installing geopandas with pip

This is the error I get when trying to install geopandas using pip install geopandas. Im using Python 3.7.Collecting geopandasUsing cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd7…

Find if a sorted array of floats contains numbers in a certain range efficiently

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that Im not interested in the positions of the number in the array. I only want to k…