KeyError в flask Twilio chatbot - PullRequest
       3

KeyError в flask Twilio chatbot

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

Это может показаться похожим на вопрос, который я задавал ранее. Тем не менее, я сделал довольно много изменений в своем коде, и это изменило проблему, с которой я столкнулся. Для контекста я создаю чат-бот WhatsApp Twilio на flask. Идея заключается в том, что если пользователь введет определенное ключевое слово, он получит сообщение в зависимости от того, что он набрал.

В дополнение к этому я создал функцию, которая пытается ограничить количество запросов / ответов человека можно сделать / получить в течение 24 часов. Таким образом, пользователь может использовать этот чат-бот только 5 раз в течение 24 часов с момента его первого действия.

Это код, который я написал для этого чат-бота, я добавил комментарии, чтобы объяснить логи c, поэтому легче обнаружить любые ошибки, которые я сделал, и включил все библиотеки, которые я использую:

from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
from datetime import datetime
import pytz
import re

app = Flask(__name__)

@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()
    responded = False
    # 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 sett ing request counter to 0
    def add_user(user,time,counter):
        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,time,counter):
        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, counter):
        sessionStorage[user][counter] += 1

    if request_check(user=cleaned_number, time=datetime.now(pytz.timezone('Africa/Harare')), counter=0):
        if incoming_msg == 'help':
            output = 'This is a chatbot designed to send XYZ.'
            msg.body(output)
        responded = True
        # returns sender's number
        if 'test' in incoming_msg:
            msg.body(cleaned_number)
            responded = True
        if 'first' in incoming_msg:
            text = 'First test text'
            msg.body(text)
            responded = True
        if 'second' in incoming_msg:
            text = 'Second test text'
            msg.body(text)
            responded = True
        if not responded:
            msg.body('Not programmed to return this text')
        return str(resp)
        increment_request_counter(user=cleaned_number)

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

Когда я пытаюсь ввести ключевое слово. Например 'first' в WhatsApp, я получаю сообщение об ошибке в моем терминале Pycharm:

  File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\venv\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\bot.py", line 46, in bot
    if request_check(user=cleaned_number, time=datetime.now(pytz.timezone('Africa/Harare')), counter=0):
  File "C:\Users\User\Documents\GitHub\gradientboostwhatsapp\bot.py", line 33, in request_check
    difference = sessionStorage[user][time] - datetime.now(pytz.timezone('Africa/Harare'))
KeyError: '27652581300'
...