我试图启动使用botkit和javascript完成的聊天机器人。但是我得到了Error: read ECONNRESET
:
C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app>node .
Initializing Botkit v0.6.21
info: ** Using custom storage system.
fn it is not a function when importing ./express_middleware/Icon_
fn it is not a function when importing ./express_middleware/Icon_
fn it is not a function when importing ./express_middleware/Icon_
Could not load bot identity!
(node:15184) UnhandledPromiseRejectionWarning: Error: Error: read ECONNRESET
at C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app\node_modules\botkit\lib\Facebook.js:1766:15
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:15184) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15184) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
[2019-04-23T14:20:44.897Z] @firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"read ECONNRESET\"."}
C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app\components\subscribe_events.js:11
throw new Error(err);
^
Error: Error: read ECONNRESET
at Request._callback (C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app\components\subscribe_events.js:11:23)
at self.callback (C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app\node_modules\request\request.js:185:22)
at Request.emit (events.js:189:13)
at Request.onRequestError (C:\Users\antoi\Documents\Programming\PACO\Code 19-04-03\app\node_modules\request\request.js:881:8)
at ClientRequest.emit (events.js:189:13)
at TLSSocket.socketErrorListener (_http_client.js:392:9)
at TLSSocket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
如何处理此错误?我不知道什么是诺言拒绝。似乎与我使程序编写的消息有关:fn it is not a function when importing ./express_middleware/Icon_
。但是我确实有这个文件,尽管它是空的。这是可能需要它的express_webserevers
文件:
var express = require("express");
var bodyParser = require("body-parser");
var querystring = require("querystring");
var debug = require("debug")("botkit:webserver");
module.exports = function(controller, bot) {
var webserver = express();
webserver.use(bodyParser.json());
webserver.use(bodyParser.urlencoded({ extended: true }));
webserver.use((req, res, next) => {
// res.setHeader('X-Frame-Options', 'ALLOW-FROM https://www.messenger.com/ https://www.facebook.com/');
// res.setHeader("X-Frame-Options", "ALLOW-FROM https://www.facebook.com/");
// res.setHeader('X-Frame-Options', 'ALLOW-FROM https://l.facebook.com/');
next();
});
// import express middlewares that are present in /components/express_middleware
var normalizedPath = require("path").join(__dirname, "express_middleware");
require("fs")
.readdirSync(normalizedPath)
.forEach(function(file) {
const fn = require(`./express_middleware/${file}`);
if (typeof fn === 'function') {
fn(webserver, controller);
} else {
console.log(`fn it is not a function when importing ./express_middleware/${file}`);
}
});
webserver.use(express.static("build"));
webserver.use(express.static('public'));
webserver.listen(process.env.PORT || 3000, null, function() {
debug(
"Express webserver configured and listening at http://localhost:" +
process.env.PORT || 3000
);
});
// import all the pre-defined routes that are present in /components/routes
var normalizedPath = require("path").join(__dirname, "routes");
require("fs")
.readdirSync(normalizedPath)
.forEach(function(file) {
const fn = require(`./routes/${file}`);
if (typeof fn === 'function') {
fn(webserver, controller);
} else {
console.log(`fn it is not a function when importing ./express_middleware/${file}`);
}
});
controller.webserver = webserver;
return webserver;
};
或来自bot.js
文件:
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
______ ______ ______ __ __ __ ______
/\ == \ /\ __ \ /\__ _\ /\ \/ / /\ \ /\__ _\
\ \ __< \ \ \/\ \ \/_/\ \/ \ \ _"-. \ \ \ \/_/\ \/
\ \_____\ \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\
\/_____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/
This is a sample Facebook bot built with Botkit.
# RUN THE BOT:
Follow the instructions here to set up your Facebook app and page:
-> https://developers.facebook.com/docs/messenger-platform/implementation
Run your bot from the command line:
page_token=<MY PAGE TOKEN> verify_token=<MY_VERIFY_TOKEN> node bot.js
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
var env = require('node-env-file');
env(__dirname + '/.env');
if (!process.env.page_token) {
console.log('Error: Specify a Facebook page_token in environment.');
usage_tip();
process.exit(1);
}
if (!process.env.verify_token) {
console.log('Error: Specify a Facebook verify_token in environment.');
usage_tip();
process.exit(1);
}
var Botkit = require('botkit');
var debug = require('debug')('botkit:main');
// Bot options
var bot_options = {
// debug: true,
stats_optout: true,
verify_token: process.env.verify_token,
access_token: process.env.page_token,
studio_token: process.env.studio_token,
studio_command_uri: process.env.studio_command_uri
};
// Select storage
if (process.env.FIREBASE_URI) {
let firebaseStorage = require('botkit-storage-firebase')({firebase_uri: process.env.FIREBASE_URI,
firebase_json: process.env.FIREBASE_JSON});
bot_options.storage = firebaseStorage;
}
else {
bot_options.json_file_store = __dirname + '/.data/db/'; // store user data in a simple JSON format
}
// Create the Botkit controller, which controls all instances of the bot.
var controller = Botkit.facebookbot(bot_options);
// Set up an Express-powered webserver to expose oauth and webhook endpoints
var webserver = require(__dirname + '/components/express_webserver.js')(controller);
// Tell Facebook to start sending events to this application
require(__dirname + '/components/subscribe_events.js')(controller);
// Set up Facebook "thread settings" such as get started button, persistent menu
require(__dirname + '/components/thread_settings.js')(controller);
// Send an onboarding message when a user activates the bot
require(__dirname + '/components/onboarding.js')(controller);
// Load in some helpers that make running Botkit on Glitch.com better
require(__dirname + '/components/plugin_glitch.js')(controller);
// enable advanced botkit studio metrics
require('botkit-studio-metrics')(controller);
var normalizedPath = require("path").join(__dirname, "skills");
require("fs").readdirSync(normalizedPath).forEach(function(file) {
/* require("./skills/" + file)(controller);
});*/
const fn = require(`./skills/${file}`);
if (typeof fn === 'function') {
fn(controller);
} else {
console.log(`fn it is not a function when importing ./express_middleware/${file}`);
}
});
// Add fbuser middleware
var fbuser = require('botkit-middleware-fbuser')({
accessToken: bot_options.access_token,
fields: ['first_name', 'last_name', 'locale', 'profile_pic','timezone'],
logLevel: 'error',
expire: 24 * 60 * 60 * 1000, // refresh profile info every 24 hours
storage: bot_options.storage
});
controller.middleware.receive.use(fbuser.receive)
function attachExt(buttons) {
return buttons.map(b => {
if (b.type == "web_url") {
b.messenger_extensions = true;
}
return b;
})
}
controller.middleware.format.use(function(bot, message, platform_message, next) {
if (message.isExt) {
let elements = message.attachment.payload.elements;
if (elements) {
platform_message.message.attachment.payload.elements = elements.map(elem => {
elem.buttons = attachExt(elem.buttons);
return elem;
});
}
let buttons = message.attachment.payload.buttons;
if (buttons) {
platform_message.message.attachment.payload.buttons = attachExt(buttons);
}
}
next();
})
// This captures and evaluates any message sent to the bot as a DM
// or sent to the bot in the form "@bot message" and passes it to
// Botkit Studio to evaluate for trigger words and patterns.
// If a trigger is matched, the conversation will automatically fire!
// You can tie into the execution of the script using the functions
// controller.studio.before, controller.studio.after and controller.studio.validate
if (process.env.studio_token) {
controller.on('message_received,facebook_postback', function(bot, message) {
if (message.text) {
controller.studio.runTrigger(bot, message.text, message.user, message.channel, message).then(function(convo) {
if (!convo) {
// no trigger was matched
// If you want your bot to respond to every message,
// define a 'fallback' script in Botkit Studio
// and uncomment the line below.
controller.studio.run(bot, 'fallback', message.user, message.channel, message);
} else {
// set variables here that are needed for EVERY script
// use controller.studio.before('script') to set variables specific to a script
convo.setVar('current_time', new Date());
}
}).catch(function(err) {
if (err) {
bot.reply(message, 'I experienced an error with a request to Botkit Studio: ' + err);
debug('Botkit Studio: ', err);
}
});
}
});
} else {
console.log('~~~~~~~~~~');
console.log('NOTE: Botkit Studio functionality has not been enabled');
console.log('To enable, pass in a studio_token parameter with a token from https://studio.botkit.ai/');
}
function usage_tip() {
console.log('~~~~~~~~~~');
console.log('Botkit Studio Starter Kit');
console.log('Execute your bot application like this:');
console.log('page_token=<MY PAGE TOKEN> verify_token=<MY VERIFY TOKEN> studio_token=<MY BOTKIT STUDIO TOKEN> node bot.js');
console.log('Get Facebook token here: https://developers.facebook.com/docs/messenger-platform/implementation')
console.log('Get a Botkit Studio token here: https://studio.botkit.ai/')
console.log('~~~~~~~~~~');
}