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
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;
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!