Пока что я уже создал бэкэнд для чат-бота, и я просто пытаюсь разрешить и бэкенду, и веб-интерфейсу, который является веб-сайтом, обмениваться данными между ними. Итак, я уже сделал это, что веб-интерфейс мог отправлять сообщения, и он будет обновляться в текстовой области, которая имеет историю разговоров. Для внешнего интерфейса это мой Html файл индекс. php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="serviceStyles.css">
<title>Team project</title>
</head>
<body>
<h1>Title n stuff</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
<li><a href="index.html">test link</a></li>
</ul>
</nav>
<h3 style='color: #ccc;font-size: 30px;'>No message yet..</h3>
<div class="message_holder"></div>
<form action="" method="POST">
<input type="text" class="input_msg" placeholder="Messages"/>
<input type="submit"/>
</form>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
<script type="text/javascript">
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on( 'connect', function() {
socket.emit( 'my event', {
data: 'User Connected'
} )
var form = $( 'form' ).on( 'submit', function( e ) {
e.preventDefault()
let user_input = $( 'input.input_msg' ).val()
socket.emit( 'my event', {
message : user_input
} )
$( 'input.input_msg' ).val( '' ).focus()
} )
} )
socket.on( 'my response', function( msg ) {
console.log( msg )
if( typeof msg.message !== 'undefined' ) {
$( 'h3' ).remove()
$( 'div.message_holder' ).append( '<div><b style="color: #000"></b> '+msg.message+'</div>' )
}
})
</script>
</body>
</html>
А это мой бэкэнд-файл, мой app.py, который состоит из всех функций чат-бота и flask.
from flask import Flask, render_template, request
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@app.route('/')
def session():
return render_template('index.html')
def messageReceived(methods=['GET', 'POST']):
print('message was received!!!')
@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
print('received my event: ' + str(json))
socketio.emit('my response', json, callback=messageReceived)
@app.route('/chat', methods=['POST'])
def chat():
print("Start talking with the bot! (type exit to stop)")
while True:
inp = input("You: ")
if inp.lower() == "exit":
break
results = model.predict([bag_of_words(inp, words)])[0]
results_index = numpy.argmax(results)
tag = labels[results_index]
if results[results_index] > 0.7:
for tg in data["intents"]:
if tg['tag'] == tag:
responses = tg['responses']
print(random.choice(responses))
else:
print("Sorry, I didnt quite understand what you typed, try asking a more specified question or another "
"questions.")
return render_template('index.html')
def chat_send():
text = request.form['user_inp']
x = text()
chat(x)
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app, debug=True)
В настоящее время я не могу передать входное сообщение функции chat()
из HTML, а также я получаю сообщения об ошибках типа Method Not Allowed The method is not allowed for the requested URL.
, когда я пытался access http://127.0.0.1: 5000 / chat , консоль выдает следующую ошибку для него. OSError: [WinError 10038] An operation was attempted on something that is not a socket