Reputation: 331
I am writing a Facebook messenger bot and am trying to store a text reply after a postback. What I mean by this is I have a message that sends a post back and depending on what option they choose, they can type a message back and I store that text. The problem is I only want to store this text after they select an option for the post back message. Also the text can be anything, so I can't write an if statement for it.
Here is my code:
app.post('/', function (req, res) {
messaging_events = req.body.entry[0].messaging;
for (i = 0; i < messaging_events.length; i++) {
event = req.body.entry[0].messaging[i];
sender = event.sender.id;
if (event.message && event.message.text) {
text = event.message.text;
if (text == "Start") {
sendTextMessage(sender, "Hey User! I'm a bot");
}
}
else if (event.postback) {
// These are for chosing availibility
if (JSON.stringify(event.postback) == '{"payload":"postback"}') {
setTextMessage(sender, "Postback recieved");
}
}
}
Everything is set up and running. But when the postback is received I want to wait for a reply from the user before finishing so I can save the text. Like I said earlier it can be anything meaning I can't just write an if statement like I did with "Start". I also only want to save the text after they click the postback button.
I was thinking about adding a while loop and waiting for text to be received before finishing the postback function but couldn't figure it out.
So how would I wait for text after I sent a message with a postback?
Any help is appreciated, thanks!
Upvotes: 1
Views: 1718
Reputation: 15
I have also tried for a long time to find a way to store the text sent by the sender using message ids and message times to no avail. The only technique that worked for me was declaring a global variable called 'state' and then at the end of each message that I send, I change the value of the variable 'state' to something like '001' or '002'. As such, if I wanted to access the reply to a particular message I sent, I would put if (state === '001')
. Here is an example:
var state = '000';
// if user sends me 'I want dogs'
sendTextMessage(sender, "How many dogs?");
state = '001';
// if user sends me 'I want cats'
sendTextMessage(sender, "How many cats?);
state = '002';
/* now if I want to access the user's response to how many cats they want, I simply write in an if statement:
if (state === '002' && /^\d+$/.test(text)) {
var numberOfCatsWanted = text
}
// in this last part I essentially write 'if the state is '002' and the text contains numbers then a new variable will store the value of the text
I hope this helps!
Upvotes: 1
Reputation: 979
Basically there is no way to do for your requirement. So the thing you only could do is ask the user to enter the text with some characters in prefix, for example with a '?' or '#' or something else that you can parse.
Upvotes: 0