Я развернул flask twilio chatbot на AWS lambda, используя zappa. Однако, когда я пытаюсь запустить чат-бота, я получаю сообщение об ошибке:
Error - 11200
... Msg=Internal+Server+Error&sourceComponent=14100&ErrorCode=11200&EmailNotification=false&httpResponse=500&LogLevel=ERROR&url=https%3A%2F%2Ft6ps265p77.execute-api.us-east-1.amazonaws.com%2Fdev%2Fbot
на моем отладчике Twilio. Я впервые пытаюсь развернуть что-либо на AWS, и у меня очень ограниченный опыт работы с AWS. Это код для приложения
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from twilio.twiml.messaging_response import MessagingResponse
import random
from pathlib import Path
import re
from datetime import datetime, timedelta
import pytz
from flask import Flask
from twilio.rest import Client
import os
app = Flask(__name__)
db = SQLAlchemy(app)
#connect to mysql database
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://xxx'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
#aws credentials
aws_access_key_id = os.environ.get('xxx')
aws_secret_access_key = os.environ.get('xxx')
#creating mapping to database
class Users(db.Model):
__tablename__ = 'users'
cell_number = db.Column(db.Integer, primary_key = True)
interaction_date = db.Column(db.DateTime, default = datetime.now(pytz.timezone('Africa/Harare')), nullable=False)
request_key = db.Column(db.String(64000))
counter = db.Column(db.Integer())
@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()
#set start and end time
current = datetime.now(pytz.timezone('Africa/Harare'))
start = datetime.now(pytz.timezone('Africa/Harare')) - timedelta(hours=23, minutes=59)
total_interactions = Users.query.filter(Users.cell_number == cleaned_number).\
filter(Users.interaction_date <= current).\
filter(Users.interaction_date >= start).\
filter(Users.counter == 1).count()
responded = False
#in instances when we don't want to increment attempts
def action_control_no_increment(output, incoming_msg):
msg.body(output)
user_object = Users()
user_object.request_key = incoming_msg
db.session.add(user_object)
db.session.commit
#when we want to increment attempts
def action_control(file_path, incoming_msg):
with open(file_path, "r") as f:
lines = f.readlines()
code = random.choice(lines)
msg.body(code)
user_object = Users()
user_object.cell_number = int(cleaned_number)
user_object.request_key = incoming_msg
user_object.counter = 1
db.session.add(user_object)
db.session.commit()
#when out of attempts
def action_else():
output = 'xxx'
msg.body(output)
if 'help' in incoming_msg:
output = "xxx" \
"xxx"
action_control_no_increment(output=output, incoming_msg=incoming_msg)
responded = True
if 'number' in incoming_msg:
output = str(cleaned_number)
action_control_no_increment(output=output, incoming_msg=incoming_msg)
responded = True
if 'easy' in incoming_msg:
if total_interactions <= 5:
file_path = "C://Users//User//Downloads//python_test.txt"
action_control(file_path=file_path, incoming_msg=incoming_msg)
responded = True
else:
action_else()
responded = True
if 'intermediate' in incoming_msg:
if total_interactions <= 5:
file_path = "C://Users//User//Downloads//python_medium.txt"
action_control(file_path=file_path, incoming_msg=incoming_msg)
responded = True
else:
action_else()
responded = True
if not responded:
msg.body("xxx")
user_object = Users()
user_object.cell_number = int(cleaned_number)
user_object.request_key = incoming_msg
user_object.counter = 0
db.session.add(user_object)
db.session.commit()
return str(resp)
if __name__ == '__main__':
app.run(debug=True)
Это мои zappa_settings. json:
{
"dev": {
"app_function": "bot.app",
"profile_name": null,
"project_name": "xxx",
"runtime": "python3.7",
"s3_bucket": "zappa-xxx",
"aws_region": "us-east-1"
}
и мои настройки на twilio
WHEN A MESSAGE COMES IN: https://t6ps265p77.execute-api.us-east-1.amazonaws.com/dev/bot
Приложение запускается, если я запускаю его локально с помощью ngrok