Smooch: How to do postback dependent state transition?

后端 未结 3 953
挽巷
挽巷 2021-01-20 19:42

I am trying to transition the script from one state to another based on Smooch postback payloads; but getting error code H12.

Consider the example https://github.com

3条回答
  •  花落未央
    2021-01-20 20:14

    If you want to advance the conversation based on a postback you'll have to first output the buttons from the bot's prompt (so you can handle the button click in the receive), modify the handlePostback function in index.js, then handle the user's "reply" in your receive method - try this - modify script.js like so:

    start: {
        prompt: (bot) => bot.say(`Hi! I'm Smooch Bot! Continue? %[Yes](postback:askName) %[No](postback:bye)`),
        receive: (bot, message) => {
    
          switch(message.text) {
            case 'Yes':
              return bot.say(`Ok, great!`)
                .then(() => 'hi')
              break;
            case 'No':
              return bot.say(`Ok, no prob!`)
                .then(() => 'bye')
              break;
            default:
              return bot.say(`hmm...`)
                .then(() => 'processing')
              break;          
          }
        }
    },
    
    hi: {
        prompt: (bot) => bot.say('Pleasure meeting you'),
        receive: () => 'processing'
    },
    
    bye: {
        prompt: (bot) => bot.say('Pleasure meeting you'),
        receive: () => 'processing'
    },
    

    Then modify the handlePostback function in index.js so that it treats a postback like a regular message:

    function handlePostback(req, res) {
    
        const postback = req.body.postbacks[0];
    
        if (!postback || !postback.action)
            res.end();
    
        const stateMachine = new StateMachine({
            script,
            bot: createBot(req.body.appUser)
        });
    
        const msg = postback;
    
        // if you want the payload instead just do msg.action.paylod
        msg.text = msg.action.text;
    
        stateMachine.receiveMessage(msg)
          .then(() => res.end())
          .catch((err) => {
            console.error('SmoochBot error:', err);
            res.end();
          });
    }
    

    Now when a user clicks your button it will be pushed to the stateMachine and handled like a reply.

提交回复
热议问题