Search code examples
encodingutf-8facebook-messengerwit.aifacebook-chatbot

facebook messenger bot encoding error


I have written sample echo message bot using facebook messenger api and wit.ai actions.

My message from facebook page is received and the proper action function defined using wit api's is also getting called. However while returning the response, i am getting followin error as -

Oops! An error occurred while forwarding the response to : Error: (#100) Param message[text] must be a UTF-8 encoded string at fetch.then.then.json (/app/index.js:106:13) at process._tickCallback (internal/process/next_tick.js:103:7)

Here is the function which is used to return the response -

const fbMessage = (id, text) => {  
  const body = JSON.stringify({
    recipient: { id },
    message: { text },
  });
  const qs = 'access_token=' + encodeURIComponent(FB_PAGE_ACCESS_TOKEN);
  return fetch('https://graph.facebook.com/v2.6/me/messages?' + qs, {
    method: 'POST',
    headers: {'Content-Type': 'application/json; charset=UTF-8'},
    body
  })
  .then(rsp => rsp.json())
  .then(json => {
    if (json.error && json.error.message) {
      throw new Error(json.error.message);`enter code here`
    }   
    return json;
  });
};

I have copied this function from the messenger.js file from the documentation since i am just trying the POC. I checked the values for text and id in this function and verified using console.log statements and those are coming properly.

Can some experts help me to solve this error?

Note - I tried encoding the text using text.toString("utf8"); but it returns the encoding string as [object object] and thats the response i get from bot. so it doesnt work.


Solution

  • Get the latest code from node-wit, there is a change in facebook id usage,

    According to Facebook:

    On Tue May 17 format of user and page ids delivered via webhooks will change from an int to a string to better support default json encoder in js (that trims long ints). Please make sure your app works with string ids returned from webhooks as well as with ints.

    Still you are getting issue with the api try to add if(event.message && !event.message.is_echo) condition as shown in below code.

     // Message handler
     app.post('/webhook', (req, res) => {
       const data = req.body;
        if (data.object === 'page') {
          data.entry.forEach(entry => {
            entry.messaging.forEach(event => {
             if (event.message && !event.message.is_echo) {
                const sender = event.sender.id;
               const sessionId = findOrCreateSession(sender);
               const {text, attachments} = event.message;
               if (attachments) {
                 fbMessage(sender, 'Sorry I can only process text messages for now.')
                 .catch(console.error);
               } else if (text) {
                 wit.runActions(
                   sessionId, // the user's current session
                   text, // the user's message
                   sessions[sessionId].context // the user's current session state
                 ).then((context) => {
                   console.log('Waiting for next user messages');
                   sessions[sessionId].context = context;
                 })
                 .catch((err) => {
                   console.error('Oops! Got an error from Wit: ', err.stack || err);
                 })
               }
             } else {
               console.log('received event', JSON.stringify(event));
             }
           });
         });
       }
       res.sendStatus(200);
     });
    

    Reference:
    no matching user bug
    no matching user fix