Skip to content

Instantly share code, notes, and snippets.

@OverPoweredDev
Last active August 6, 2021 05:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OverPoweredDev/b295e7e805b4994c93bbf6a486c27486 to your computer and use it in GitHub Desktop.
Save OverPoweredDev/b295e7e805b4994c93bbf6a486c27486 to your computer and use it in GitHub Desktop.
A few instructions on connecting a chatbot back-end to a web front-end using Flask

Connecting a Chatbot to a Web Front-End

First off, this is just a quick fix so you can get what you want up and running quick enough. Look up how API's work and fetch/axios calls in javascript so you can do this stuff easily later on. With that said, a few things I'm assuming you already have are:

  • An input field for the user of the type

    <input id='input-id'>...</input>
  • A button to post the message

    <button id='button-id'>...</button>
  • Finally, a python function you want to call with the button

    def reply(user_input):
      # whatever your chatbot does...
      # but the reply must be a string
      return reply

This would be much easier if you use a <form>. If that is the case, you can check this StackOverflow Answer as well. The next section shows what you need to add to your files, I'll use the function names and element id's from above


app.py

Add the following lines to your flask app file

def reply(user_input):
  # whatever your chatbot does...
  # but the reply must be a string
  return reply

@app.route('/getreply/<user_input>', methods=['GET','POST'])
def get_chatbot_reply(user_input):
  # call your chatbot reply function here after you've validated the user input
  chatbot_reply = reply(validated_input)
  return chatbot_reply;

index.html

Add the following scripts to the end of your html page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
  $('#button-id').on('click', async function () {
    let user_reply = $('#input-id').val();
    fetch(`/getreply/${user_reply}`)            // call our python function
      .then(function (response) {
          return response.text();               // convert json response to text
      }).then(function (reply) {
          $('#chatbot-textbox-id').val(reply);  // set chatbot's reply
      });
  });
</script>

With the instructions above, you should have a general idea of what you're doing. If this still doesn't get it to work, check out this towardsdatascience Article that describes it in more detail.

And if this did help you, be sure to star the gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment