An error occurred while loading the file. Please try again.
-
Muhamad Nobel Fauzan authorede43a07b2
app.py 1.57 KiB
from flask import Flask
from flask_socketio import SocketIO, send
from flask_sqlalchemy import SQLAlchemy
from difflib import get_close_matches
import time
import threading
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins='*')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///qa.sqlite3'
db = SQLAlchemy(app)
class QAPair(db.Model):
id = db.Column(db.Integer, primary_key=True)
question = db.Column(db.String(80), unique=True, nullable=False)
answer = db.Column(db.String(80), unique=True, nullable=False)
def __repr__(self):
return self.question
waiting_time = 10
last_msg = time.time() + 12
question = QAPair.query.with_entities(QAPair.question).all()
questions = [a.question for a in question]
@socketio.on('message')
def handleMessage(msg):
q = get_close_matches(msg, questions)
# send(q, broadcast=False)
if q:
ans = QAPair.query.filter_by(question = q[0]).first().answer
send(ans, broadcast=False)
else:
send("sorry, I don't understand the question", broadcast = False)
global last_msg
last_msg = time.time()
def idle_check_thread():
global last_msg
global waiting_time
while True:
current_time = time.time()
if (last_msg + waiting_time) < current_time and (last_msg + waiting_time + 4) > current_time:
socketio.send("are you there?")
time.sleep(5)
x = threading.Thread(target=idle_check_thread)
x.start()
if __name__ == '__main__':
socketio.run(app)