Simple API.AI node.js webhook crashes on Heroku - javascript

I try to get my feet wet implementing a simply webhook for Google's NLP API.AI interface. I want to use Heroku as the server using node.js. The problem is that I can build and deploy the code on Heroku but the execution fails immediately.
Extract from the build log (note that the "real name" app is not test, I just changed it for this post)
[...]
2017-07-21T13:28:57.000000+00:00 app[api]: Build succeeded
2017-07-21T13:29:07.012028+00:00 heroku[web.1]: Starting process with command `npm start`
2017-07-21T13:29:10.516218+00:00 app[web.1]:
2017-07-21T13:29:10.516234+00:00 app[web.1]: > test#0.0.3 start /app
2017-07-21T13:29:10.516235+00:00 app[web.1]: > node app.js
2017-07-21T13:29:10.516236+00:00 app[web.1]:
2017-07-21T13:29:11.076809+00:00 heroku[web.1]: State changed from starting to crashed
I have tried many different versions of code but even this code which is reduced to pretty much nothing fails to execute.
Here is my app.js:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
const ApiAiApp = require('actions-on-google').ApiAiApp;
const test = function(request, response) {
// todo
};
module.exports = {
test
};
And this is the package.json file:
{
"name": "test",
"description": "virtual scrum master",
"version": "0.0.3",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"scripts": {
"lint": "semistandard --fix \"**/*.js\"",
"start": "node app.js",
"monitor": "nodemon app.js",
"deploy": "gcloud app deploy"
},
"engines": {
"node": "6.11.1"
},
"dependencies": {
"actions-on-google": "^1.0.0"
},
"devDependencies": {
"semistandard": "^9.1.0"
}
}

After a log of searching I found the correct setup.
Here is the correct app.js code:
'use strict';
process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));
app.post('/', function (req, res) {
// Todo
});
if (module === require.main) {
// Start the server
let server = app.listen(process.env.PORT || 8080, function () {
let port = server.address().port;
console.log('App listening on port %s', port);
});
}
module.exports = app;

Related

.pr[nodemon] app crashed - waiting for file changes before starting... While deploying NodeJS server on Heroku

I am facing
[nodemon] app crashed - waiting for file changes before starting...
While hosting my NodeJS Apollo GraphQL express server on Heroku.
It is also showing
2022-10-06T17:21:11.889722+00:00 app[web.1]: [nodemon] 2.0.20
2022-10-06T17:21:11.889912+00:00 app[web.1]: [nodemon] to restart at any time, enter `rs`
2022-10-06T17:21:11.890274+00:00 app[web.1]: [nodemon] watching path(s): *.*
2022-10-06T17:21:11.890314+00:00 app[web.1]: [nodemon] watching extensions: js,mjs,json
2022-10-06T17:21:11.890669+00:00 app[web.1]: [nodemon] starting `nodemon -r esm .`
2022-10-06T17:21:13.608667+00:00 app[web.1]: /app/node_modules/esm/esm.js:1
2022-10-06T17:21:13.616378+00:00 app[web.1]: const __global__ = this;(function (require, module, __shared__) { var __shared__;const
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Here is my index.js
import express from "express";
import mongoose from "mongoose";
import { DB, mode } from "./config";
import { ApolloServer } from "apollo-server-express";
import AuthMiddleware from "./middlewares/auth";
import * as AppModels from "./models";
import { resolvers, typeDefs } from "./graphql";
const startServer = async () => {
const PORT = process.env.PORT || 3000;
try {
const app = express();
app.use(AuthMiddleware);
const apolloServer = new ApolloServer({
typeDefs,
resolvers,
playground: mode,
context: ({ req }) => {
let { isAuth, user } = req;
return { req, isAuth, user, ...AppModels };
},
});
mongoose.connect(DB, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await apolloServer.start();
await apolloServer.applyMiddleware({ app });
app.listen({ port: PORT }, () =>
console.log(`Server started at port ${PORT}`,)
);
} catch (err) {
console.log("error: "+err);
}
};
startServer();
Here is my package.json
{
"name": "forefest-backend",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon -r esm .",
"server": "sudo systemctl start mongod && nodemon -r esm",
"dev": "nodemon -r esm"
},
"repository": {
"type": "git",
"url": "git+https://github.com/anshuman-8/forefest-backend.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/anshuman-8/forefest-backend/issues"
},
"homepage": "https://github.com/anshuman-8/forefest-backend#readme",
"dependencies": {
"apollo-server-express": "^3.10.2",
"bcryptjs": "^2.4.3",
"consola": "^2.15.3",
"dotenv": "^16.0.2",
"esm": "^3.2.25",
"express": "^4.18.1",
"graphql": "^16.6.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.21",
"mongoose": "^6.6.1",
"mongoose-paginate-v2": "^1.7.1",
"nodemon": "^2.0.20",
"yup": "^0.32.11"
}
}
I have tried multiple ways of fixing this problem, Please help me.
This is my first time deploying a server.

Heroku Keeps timing out: Error waiting for network: Resource temporarily unavailable

My index.js file:
const Discord = require('discord.js');
const levels = require('discord-xp');
const client = new Discord.Client();
const mongoose = require('./database/mongoose');
const fs = require(`fs`);
require('dotenv').config();
const port = process.env.PORT || 5000;
const host = '0.0.0.0';
const chalk = require('chalk');
const { Player } = require('discord-player');
const Gamedig = require('gamedig');
client.prefix = (`${process.env.PREFIX}`);
client.commands = new Discord.Collection();
client.player = new Player(client);
client.config = require('./config/bot');
client.emotes = client.config.emojis;
client.filters = client.config.filters;
fs.readdirSync('./commands').forEach(dirs => {
const commands = fs.readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));
for (const file of commands) {
const command = require(`./commands/${dirs}/${file}`);
console.log(`Loading command ${file}`);
client.commands.set(command.name.toLowerCase(), command);
};
});
const player = fs.readdirSync(`./player`).filter(file => file.endsWith('.js'));
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of player) {
console.log(`Loading discord-player event ${file}`);
const event = require(`./player/${file}`);
client.player.on(file.split(".")[0], event.bind(null, client));
};
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
};
mongoose.init();
client.login(process.env.TOKEN)
My Procfile:
Worker: node index.js
My package.json:
{
"name": "icrp-bot",
"version": "1.0.0",
"description": "Made For ICRP ",
"main": "index.js",
"scripts": {
"test": ".test",
"start": "node index.js"
},
"author": "Bombo43453#1901",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"baseplayer": "^0.2.9",
"chalk": "^4.1.1",
"discord-fivem-api": "^1.0.4",
"discord-player": "^3.4.0",
"discord-xp": "^1.1.14",
"discord.js": "^12.5.3",
"dotenv": "^8.2.0",
"ffmpeg-static": "^4.3.0",
"gamedig": "^3.0.1",
"log-timestamp": "^0.3.0",
"moment": "^2.29.1",
"moment-timezone": "^0.5.33",
"mongoose": "^5.11.14",
"node-gyp": "^8.0.0",
"opus": "0.0.0",
"opusscript": "0.0.8",
"pm2": "^4.5.6",
"python": "0.0.4",
"rebuild": "^0.1.2"
}
}
Full Error:
2021-04-23T17:18:33.808571+00:00 heroku[Worker.1]: State changed from down to starting
2021-04-23T17:18:43.196477+00:00 heroku[Worker.1]: Starting process with command `node index.js`
2021-04-23T17:18:43.846098+00:00 heroku[Worker.1]: State changed from starting to up
2021-04-23T17:18:43.854420+00:00 heroku[Worker.1]: Idling
2021-04-23T17:18:43.856605+00:00 heroku[Worker.1]: State changed from up to down
2021-04-23T17:18:43.870047+00:00 heroku[Worker.1]: Idling because quota is exhausted
2021-04-23T17:18:50.422071+00:00 app[Worker.1]: Error waiting for network: Resource temporarily unavailable
Info: this is a simple bot I have made for a fivem server. I tried to host it with heroku and tried to fix it. I tried adding a port const and a const host but that did not fix anything. I also think that my issue is very small and I have 200 hours left on heroku meaning that hours are not the issue. I tried changing the port to 8080 too and that did not help with anything. If you have an idea please tell me.
I know you said you have 200 hours left.
But Idling because quota is exhausted only shows when you run out of free hours.
Also you said you changed the port to 8080 but please note that YOU CAN'T CHANGE THE PORT ON HEROKU you get the port as env variable (Like process.env.PORT as you did above) and you can't change it.
If you're using worker that means you can't run a web process and the PORT is useless anyway.
About your last Error this is from Heroku support
This is caused by kernel-level issues that can surface occasionally on the backend instances that dynos run on. Unfortunately, there is not really a work around for this issue. Scheduler dynos will crash if this happens and the job will not be executed again until its next scheduled run time. Other dyno types will typically enter a bad state and require a manual restart (you may see "App boot timeout" errors when this happens).
Check this

Failed to launch the browser process! when deploying node.js app on shared hosting

So I built a simple project to test out and it works well on my local machine. the challenge comes when I deploy it on my Cpanel hosting I get an error A UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
//app.json
const { Client } = require('whatsapp-web.js');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const client = new Client();
client.on('qr', (qr) => {
// Generate and scan this code with your phone
console.log('QR RECEIVED', qr);
});
client.on('ready', () => {
console.log('Client is ready!');
});
client.on('message', msg => {
if (msg.body == '!ping') {
msg.reply('pong');
}
});
client.initialize();
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
// package.json
{
"name": "puppet",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start" : "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"whatsapp-web.js": "^1.12.0"
}
}
everything installs correctly but when the app starts it writes this error in the log file
App 4096690 output: (node:4096690) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
App 4096690 output: /home/linearcb/nodevenv/repositories/whatsapp/10/lib/node_modules/puppeteer/.local-chromium/linux-818858/chrome-linux/chrome: error while loading shared libraries: libatk-1.0.so.0: cannot open shared object file: No such file or directory

Failed to connect with redis in node.js

I am trying to connect with redis(of docker instance) using express(node.js).
Here is my index.ts file in which i am trying to connect with redis
import mongoose from 'mongoose'
import express from 'express'
import session from 'express-session'
import connectRedis from 'connect-redis'
import Redis from 'ioredis'
import { MONGO_URI, MONGO_OPTIONS, REDIS_OPTIONS, APP_PORT } from './config'
import { createApp } from './app';
; (async () => {
await mongoose.connect(MONGO_URI, MONGO_OPTIONS)
const RedistStore = connectRedis(session)
const client = new Redis(REDIS_OPTIONS)
const store = new RedistStore({ client })
const app = createApp(store)
app.listen(APP_PORT, () => console.log('server running on port 3000'))
})()
Here is my REDIS_OPTIONS file in which i have all redis options.
import { RedisOptions } from 'ioredis'
const {
REDIS_PORT = 6379,
REDIS_HOST = 'localhost',
REDIS_PASSWORD = 'secret'
} = process.env
export const REDIS_OPTIONS: RedisOptions = {
port: +REDIS_PORT,
host: REDIS_HOST,
password: REDIS_PASSWORD
}
docker-compose.yml
version: '3'
services:
db:
user: $UID
image: mongo
ports:
- '27017:27017'
environment:
MONGO_INITDB_ROOT: ''
MONGO_INITDB_PASSWORD: ''
MONGO_INITDB_DATABASE: auth,
MONGO_USERNAME: ''
MONGO_PASSWORD: ''
volumes:
- ./data:/data/db
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh:ro
cache:
image: redis:alpine
ports:
- '6379:6379'
command: ['--requirepass "secret"']
package.json
{
"name": "node-auth",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"up": "docker-compose up -d",
"postup": "npm run dev",
"stop": "docker-compose stop",
"down": "docker-compose down",
"dev": "npm run dev --prefix api"
},
"keywords": [],
"author": "",
"license": "ISC"
}
Now when i try to run my main app file so i am getting this error
[ioredis] Unhandled error event: Error: connect ECONNREFUSED 127.0.0.1:6379 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14) node.js
How can i get rid of this error?
Looks like it might be a problem with the Redis container. What command you used to run the container? Try adding -p 6379:6379 with your docker command. Also, check whether port 6379 is used by something else or blocked by antivirus or firewall.
change host in index.ts from 'localhost' to 'redis'

Deploying botkit framework to azure and testing in the webchat returns 502

For my internship I am making a chatbot. I created a bot using botkit framework (yo botkit) and got as far as using it in the ms Teams client. But only using my localhost + ngrok setup. when I want to use https://{myproject}.azurewebsites.net/api/messages after deployment I get a 502 error message.
To try if I actually did my deployment okay, I made another project using "yo botbuilder" without botkit framework. Following the same steps I deployed it to a fresh Group. This time using the https://{myproject}.azurewebsites.net/api/messages url worked. (standard echo bot)
After that, I copied my bot files from my first project into my new one and replaced my index.js from my standard botbuilder project with my bot.js file from my botkit framework project.
I just used the standard botbuilder -> index.js file and botkit -> bot.js file +
in my package.json I changed the main and the scripts to point to bot.js instead of index.js.
After deploying, it just gave me my 502 again.
index.js
const dotenv = require('dotenv');
const path = require('path');
const restify = require('restify');
// Import required bot services.
// See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter } = require('botbuilder');
// This bot's main dialog.
const { EchoBot } = require('./bot');
// Import required bot configuration.
const ENV_FILE = path.join(__dirname, '.env');
dotenv.config({ path: ENV_FILE });
// Create HTTP server
const server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, () => {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log('\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator');
console.log('\nTo talk to your bot, open the emulator select "Open Bot"');
});
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about how bots work.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
const onTurnErrorHandler = async (context, error) => {
// This check writes out errors to console log .vs. app insights.
// NOTE: In production environment, you should consider logging this to Azure
// application insights.
console.error(`\n [onTurnError] unhandled error: ${ error }`);
// Send a trace activity, which will be displayed in Bot Framework Emulator
await context.sendTraceActivity(
'OnTurnError Trace',
`${ error }`,
'https://www.botframework.com/schemas/error',
'TurnError'
);
// Send a message to the user
await context.sendActivity('The bot encountered an error or bug.');
await context.sendActivity('To continue to run this bot, please fix the bot source code.');
};
// Set the onTurnError for the singleton BotFrameworkAdapter.
adapter.onTurnError = onTurnErrorHandler;
// Create the main dialog.
const myBot = new EchoBot();
// Listen for incoming requests.
server.post('/api/messages', (req, res) => {
adapter.processActivity(req, res, async (context) => {
// Route to main dialog.
await myBot.run(context);
});
});
// Listen for Upgrade requests for Streaming.
server.on('upgrade', (req, socket, head) => {
// Create an adapter scoped to this WebSocket connection to allow storing session data.
const streamingAdapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Set onTurnError for the BotFrameworkAdapter created for each connection.
streamingAdapter.onTurnError = onTurnErrorHandler;
streamingAdapter.useWebSocket(req, socket, head, async (context) => {
// After connecting via WebSocket, run this logic for every request sent over
// the WebSocket connection.
await myBot.run(context);
});
});
bot.js
const { Botkit } = require('botkit');
const { BotkitCMSHelper } = require('botkit-plugin-cms');
// Import a platform-specific adapter for botframework.
const { MongoDbStorage } = require('botbuilder-storage-mongodb');
// Load process.env values from .env file
require('dotenv').config();
let storage = null;
if (process.env.MONGO_URI) {
storage = mongoStorage = new MongoDbStorage({
url : process.env.MONGO_URI,
});
}
const controller = new Botkit({
webhook_uri: '/api/messages',
adapterConfig: {
appId: process.env.APP_ID,
appPassword: process.env.APP_PASSWORD,
},
storage
});
if (process.env.CMS_URI) {
controller.usePlugin(new BotkitCMSHelper({
uri: process.env.CMS_URI,
token: process.env.CMS_TOKEN,
}));
}
// Once the bot has booted up its internal services, you can use them to do stuff.
controller.ready(() => {
// load traditional developer-created local custom feature modules
controller.loadModules(__dirname + '/features');
/* catch-all that uses the CMS to trigger dialogs */
if (controller.plugins.cms) {
controller.on('message,direct_message', async (bot, message) => {
let results = false;
results = await controller.plugins.cms.testTrigger(bot, message);
if (results !== false) {
// do not continue middleware!
return false;
}
});
}
});
controller.webserver.get('/', (req, res) => {
res.send(`This app is running Botkit ${ controller.version }.`);
});
package.json
{
"name": "my-chat-bot",
"version": "1.0.0",
"description": "Demonstrate the core capabilities of the Microsoft Bot Framework",
"author": "Generated using Microsoft Bot Builder Yeoman generator v4.7.0",
"license": "MIT",
"main": "bot.js",
"scripts": {
"start": "node ./bot.js",
"watch": "nodemon ./bot.js",
"lint": "eslint .",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://github.com"
},
"dependencies": {
"botbuilder": "~4.7.0",
"dotenv": "^8.2.0",
"restify": "~8.4.0",
"botbuilder-storage-mongodb": "^0.9.5",
"botkit": "^4.6.2",
"botkit-plugin-cms": "^1.0.3",
"firebase-admin": "^8.9.2",
"jira-client": "^6.15.0",
"request": "^2.88.2"
},
"devDependencies": {
"eslint": "^6.6.0",
"eslint-config-standard": "^14.1.0",
"eslint-plugin-import": "^2.18.2",
"eslint-plugin-node": "^10.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"nodemon": "~1.19.4"
}
}

Categories

Resources