简体   繁体   中英

How do I chat with the chatbot with html and flask

So far I have already created the backend for the chatbot and I just trying to allow both the backend and the frontend which is the website to communicate between them. So, I already made it that the frontend was able to send messages and it would be updated on the textarea which has the conversation history. For the frontend, This is my Html file index.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>

And this is my backend file, my app.py which consists of all the chatbot functions and 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)

Currently, I'm unable to pass the input message towards the chat() function from HTML, and I'm also getting Errors like Method Not Allowed The method is not allowed for the requested URL. when I tried to access http://127.0.0.1:5000/chat , the console prompts the following error for it. OSError: [WinError 10038] An operation was attempted on something that is not a socket

This is because your method is post but when you are using the api call it should be get

replace

@app.route('/chat', methods=["POST"])

to

@app.route('/chat', methods=["GET", "POST"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM