An error occurred while loading the file. Please try again.
-
Muhamad Nobel Fauzan authoredb522727a
app.py 1.90 KiB
from flask import Flask
from flask_socketio import SocketIO, send, disconnect
from flask_sqlalchemy import SQLAlchemy
from flask import request
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 = {}
question = QAPair.query.with_entities(QAPair.question).all()
questions = [a.question for a in question]
@socketio.on('connect')
def welcomeMessage(auth):
if auth['token'] == "password123":
send("hello there", broadcast = False)
else:
disconnect()
@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[request.sid] = time.time()
def idle_check_thread():
global last_msg
global waiting_time
while True:
current_time = time.time()
try:
for e in last_msg:
if (last_msg[e] + waiting_time) < current_time and (last_msg[e] + waiting_time + 4) > current_time:
socketio.send("are you there?",to= e )
last_msg[e] = 0
except:
pass
x = threading.Thread(target=idle_check_thread)
x.start()
if __name__ == '__main__':
socketio.run(app)