Node.js TypeError:Wit不是构造函数

Node.js TypeError:Wit不是构造函数,node.js,wit.ai,Node.js,Wit.ai,如何解决Node.js在执行和文档中给出的代码时出现的“Wit不是构造函数”错误。 // Setting up our bot const wit = new Wit(WIT_TOKEN, actions); 我尝试了升级和降级npm/节点版本的所有方法,但没有成功 更新:请查找我使用的index.js源代码, 我需要在这方面做些改变吗 module.exports = { Logger: require('./lib/logger.js').Logger, logLevels: re

如何解决Node.js在执行和文档中给出的代码时出现的“Wit不是构造函数”错误。

// Setting up our bot
const wit = new Wit(WIT_TOKEN, actions);
我尝试了升级和降级npm/节点版本的所有方法,但没有成功

更新:请查找我使用的index.js源代码,
我需要在这方面做些改变吗

module.exports = {
  Logger: require('./lib/logger.js').Logger,
  logLevels: require('./lib/logger.js').logLevels,
  Wit: require('./lib/wit.js').Wit,
}

'use strict';

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
const Logger = require('node-wit').Logger;
const levels = require('node-wit').logLevels;
var app = express();

app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 3000));

//const Wit = require('node-wit').Wit;
const WIT_TOKEN = process.env.WIT_TOKEN;
const FB_PAGE_TOKEN = process.env.FB_PAGE_TOKEN;
const Wit = require('node-wit').Wit;

// Server frontpage
app.get('/', function (req, res) {
    debugger;
    res.send('This is TestBot Server');
});


// Messenger API specific code

// See the Send API reference
// https://developers.facebook.com/docs/messenger-platform/send-api-reference
const fbReq = request.defaults({
  uri: 'https://graph.facebook.com/me/messages',
  method: 'POST',
  json: true,
  qs: { access_token: FB_PAGE_TOKEN },
  headers: {'Content-Type': 'application/json'},
});

const fbMessage = (recipientId, msg, cb) => {
  const opts = {
    form: {
      recipient: {
        id: recipientId,
      },
      message: {
        text: msg,
      },
    },
  };
  fbReq(opts, (err, resp, data) => {
    if (cb) {
      cb(err || data.error && data.error.message, data);
    }
  });
};

// See the Webhook reference
// https://developers.facebook.com/docs/messenger-platform/webhook-reference
const getFirstMessagingEntry = (body) => {
  const val = body.object == 'page' &&
    body.entry &&
    Array.isArray(body.entry) &&
    body.entry.length > 0 &&
    body.entry[0] &&
    body.entry[0].id === FB_PAGE_ID &&
    body.entry[0].messaging &&
    Array.isArray(body.entry[0].messaging) &&
    body.entry[0].messaging.length > 0 &&
    body.entry[0].messaging[0]
  ;
  return val || null;
};

// Wit.ai bot specific code

// This will contain all user sessions.
// Each session has an entry:
// sessionId -> {fbid: facebookUserId, context: sessionState}
const sessions = {};

const findOrCreateSession = (fbid) => {
  var sessionId;
  // Let's see if we already have a session for the user fbid
  Object.keys(sessions).forEach(k => {
    if (sessions[k].fbid === fbid) {
      // Yep, got it!
      sessionId = k;
    }
  });
  if (!sessionId) {
    // No session found for user fbid, let's create a new one
    sessionId = new Date().toISOString();
    sessions[sessionId] = {fbid: fbid, context: {}};
  }
  return sessionId;
};

// Our bot actions
const actions = {
  say(sessionId, context, message, cb) {
    // Our bot has something to say!
    // Let's retrieve the Facebook user whose session belongs to
    const recipientId = sessions[sessionId].fbid;
    if (recipientId) {
      // Yay, we found our recipient!
      // Let's forward our bot response to her.
      fbMessage(recipientId, message, (err, data) => {
        if (err) {
          console.log(
            'Oops! An error occurred while forwarding the response to',
            recipientId,
            ':',
            err
          );
        }

        // Let's give the wheel back to our bot
        cb();
      });
    } else {
      console.log('Oops! Couldn\'t find user for session:', sessionId);
      // Giving the wheel back to our bot
      cb();
    }
  },
  merge(sessionId, context, entities, message, cb) {
    cb(context);
  },
  error(sessionId, context, error) {
    console.log(error.message);
  },
  // You should implement your custom actions here
  // See https://wit.ai/docs/quickstart
};

const wit = new Wit(WIT_TOKEN, actions);

// Message handler
app.post('/webhook', (req, res) => {
  // Parsing the Messenger API response
  // Setting up our bot
//const wit = new Wit(WIT_TOKEN, actions);
  const messaging = getFirstMessagingEntry(req.body);
  if (messaging && messaging.message && messaging.message.text) {
    // Yay! We got a new message!

    // We retrieve the Facebook user ID of the sender
    const sender = messaging.sender.id;

    // We retrieve the user's current session, or create one if it doesn't exist
    // This is needed for our bot to figure out the conversation history
    const sessionId = findOrCreateSession(sender);

    // We retrieve the message content
    const msg = messaging.message.text;
    const atts = messaging.message.attachments;

    if (atts) {
      // We received an attachment

      // Let's reply with an automatic message
      fbMessage(
        sender,
        'Sorry I can only process text messages for now.'
      );
    } else if (msg) {
      // We received a text message

      // Let's forward the message to the Wit.ai Bot Engine
      // This will run all actions until our bot has nothing left to do
      wit.runActions(
        sessionId, // the user's current session
        msg, // the user's message 
        sessions[sessionId].context, // the user's current session state
        (error, context) => {
          if (error) {
            console.log('Oops! Got an error from Wit:', error);
          } else {
            // Our bot did everything it has to do.
            // Now it's waiting for further messages to proceed.
            console.log('Waiting for futher messages.');

            // Based on the session state, you might want to reset the session.
            // This depends heavily on the business logic of your bot.
            // Example:
            // if (context['done']) {
            //   delete sessions[sessionId];
            // }

            // Updating the user's current session state
            sessions[sessionId].context = context;
          }
        }
      );
    }
  }
  res.sendStatus(200);
});

您的问题有两个典型的原因,一个是忘记
需要
您的模块,另一个是忘记
npm安装它。检查您是否:

  • 忘记了
    require('node-wit')
    并从返回的对象获取构造函数:
    • const-Wit=require('node-Wit')。Wit
  • 正确要求
    Wit
    但忘记了
    npm安装节点Wit

  • 对于所有将messenger.js用作index.js的用户,请使用以下内容:

    const Wit = require('./lib/wit');
    const log = require('./lib/log');
    

    请检查节点wit包的节点\模块目录

    如果存在节点wit,请在尝试创建其实例之前要求它

    const {Wit} = require('node-wit');
    
    witHandler = new Wit({
          accessToken: accessToken
    });
    

    如何定义
    Wit
    ?请注意,示例中使用的
    require(“../”)
    仅在其存储库中工作。您将要改为使用。是否确实需要名为
    wit
    的wit?这似乎是唯一的错误