How can I remove my errors in Alan AI project? - javascript

I am trying to build a voice assistant news app using Alan AI. In my code, I have used newsapi.org API. When I am trying to execute the code, it is showing me 2 errors. "uncaught user exception" and "Cannot read property 'length' of undefined". If possible someone pleas help on how to get rid off this error. Here's my code
intent('What does this app do?', 'What can I do here?',
reply('This is a news project.'));
const API_KEY = 'e1f728171ee54ccd861576421b6a9fbc';
let savedArticles = [];
intent('Give me the news from $(source* (.*))', (p) => {
let NEWS_API_URL = `https://newsapi.org/v2/top-headlines?apiKey=${API_KEY}`;
if(p.source.value){
NEWS_API_URL = `${NEWS_API_URL}&sources=${p.source.value.toLowerCase().split(" ").join('-')}`
}
api.request(NEWS_API_URL, (error, response, body) => {
const {articles} = JSON.parse(body);
if(!articles.length) {
p.play('Sorry, please try searching for news from a different source');
return;
}
savedArticles = articles;
p.play({ command: 'newHeadlines', articles });
p.play(`Here are the (latest|recent) ${p.source.value}.`);
});
})

I just recently got into this, the problem is that when you try to call the news from CNN or ESPN (words that doesn't have that "-" hyphen symbol) it says undefined,
Try calling BBC-news or ABC-news first then CNN or any other news feed, that's what worked for me

Just you need to update api request method.
This code works perfectly, thanks.
let NEWS_API_URL = `https://newsapi.org/v2/top-headlines?apiKey=${API_KEY}`;
if(p.source.value){
NEWS_API_URL=`${NEWS_API_URL}&sources=${p.source.value.toLowerCase().split(" ").join('-')}`;
}
api.request.get(NEWS_API_URL, (err, res, body) => {
const {articles,totalResults} = JSON.parse(body);
if(!totalResults){
p.play('sorry, Please try searching news from different sources.!')
return;
}
p.play({command:'newHeadLines',articles});
p.play(`Here are the total ${totalResults} latest news.`);
});

This is due to the UserAgentMissing error therefore the articles are not set correctly. Here is the solution:
const options = {
url: NEWS_API_URL,
headers: {'User-Agent': 'request'}
};
api.request(options, (error, response, body) => {...}

Related

Error connect ECONNREFUSED 127.0.0.1:8000 at try fetch to localhost:8000 in NextJs

I would like to make a good query that I have not been able to solve anywhere, I need to use a plugin that prints to a thermal printer, but it throws me an error connect ECONNREFUSED 127.0.0.1:8000, first I had CORS problems and looking for it I solved it but I am left with that problem, I leave the code for more idea.
async imprimirEn(nombreImpresora) {
const payload = {
operaciones: this.operaciones,
nombreImpresora,
};
const { data } = await axios.post(
"/api/print/print",
//// JSON.stringify(payload)
payload
);
return data;
I had to call it this way to the next API, since it otherwise threw the cors error, so the call looked like this:
const print = nc().use(cors()).post(async (req, res) => {
const body = req.body;
console.log("mensaje desde nc:", body);
const { data } = await axios.post(
"http://localhost:8000/imprimir",
JSON.stringify(body)
);
res.json(data)
});
export default print;

authClient.request is not a function problem

I followed several hundred links, most including stackoverflow links, to try to come up with a solution to this problem, but none yielded results.
I am simply trying to get the server to access client's detail via google. Ie, get the client's Google Sheets. I followed their documentation, but for the most part, its on client side only. I followed the instructions for server-side, but it has uncompleted work in it. I found out that the method to do is to have the client sign in via OAuth2.0 and then send the recieved code to the server to process to its very own access code. That is what I'm doing, however, when I try to query any data, I get that error in the title. Here is the code snippets, please let me know if there's anything I'm missing. RIP my rep.
server:
const Router=require("express").Router()
const auth=require("../utils/auth")
const fs= require("fs")
const {OAuth2Client}=require("google-auth-library")//I tried with this library instead, and it will give the exact same error.
const {google} = require('googleapis');
var auths=[]
function oAuth2ClientGetToken(oAuth2Client, code) {
return new Promise((resolve, reject) => {
oAuth2Client.getToken(code, (err, token) => { // errors out here
if (err) reject(err);
resolve(token);
});
});
}
async function formAuthClient(code) {
const {client_secret, client_id,redirect_uris} = JSON.parse(fs.readFileSync(__dirname+"/credentials.json"))
const oAuth2Client = new google.auth.OAuth2( // form authObject
client_id, client_secret,redirect_uris[1]
);
// var oauth2Client = new OAuth2Client(client_id,client_secret,redirect_uris[1]); other method
const token = await oAuth2ClientGetToken(oAuth2Client, code).catch(console.err);
// oauth2Client.credentials=token other method of oauth2.0
oAuth2Client.setCredentials(token);
return oAuth2Client;
}
Router.get("/",(req,res)=>{
res.render("home")
})
Router.post("/sheet",async (req,res)=>{
try {
const requestBody = {
properties: {
title:"hello"
}
};
var sheets= google.sheets({version:"v4", auth: auths[req.session.id]})
await sheets.spreadsheets.create(requestBody)
} catch (error) {
res.json(error)
}
})
Router.post("/login",(req,res)=>{
console.log("token: ",req.body.token);
req.session.token=req.body.token
console.log("req.session.id:",req.session.id);
auths[req.session.id]=formAuthClient(req.body.token)
res.status(200).json()
})
module.exports=Router
the client scripts is a simple button that will trigger an "getOfflineAccess" command and ask the user to log in and then send that data to the server with "/login". then, once another button is pushed, it will call "/sheet". I appreciate all help with this. I ran out of links to click on trying to solve this problem

Fastify Error: ERR_AVVIO_PLUGIN_TIMEOUT: Plugin did not start in time

I'm following a Fastify tutorial, everything has been going well so far (connected to Database, routes working, etc.) however when attempting to add the notesDAL I'm receiving the following error:
Error: ERR_AVVIO_PLUGIN_TIMEOUT: plugin did not start in time: /routes/notes/notesDAL.js. You may have forgotten to call 'done' function or to resolve a Promise
The code is exactly the same as the tutorial, so I assume it's perhaps outdated but I'm lost. I've tried a few different ways and seem to constantly face errors. Any assistance would be much appreciated.
notes.js
"use strict";
const NotesDAL = require("./notesDAL");
module.exports = async function (fastify, opts) {
const notesDAL = NotesDAL(fastify.db);
fastify.route({
method: "POST",
url: "/",
handler: async (request, reply) => {
const { title, body } = request.body;
const newNote = await notesDAL.createNote(title, body);
return newNote;
},
});
};
notesDAL.js
const NotesDAL = (db) => {
const createNote = async (title, body) => {
const { id } = await db.one(
"INSERT INTO notes (title, body) VALUES ($1, $2) RETURNING id",
[title, body]
);
return { id, title, body };
};
return { createNote };
};
module.exports = NotesDAL;
If it matters, the folder structure is:
/app.js
/plugins/db.js
/routes/notes/notes.js
/routes/notes/notesDAL.js
Edit:
I've gotten it working however I am sure it's not the right way to do things, it looks very odd.
notesDAL.js
const NotesDAL = (db) => {}
updated to:
const NotesDAL = async (db) => {}
notes.js
const newNote = await notesDAL.createNote(title, body)
updated to:
const newNote = await (await.notesDAL).createNote(title, body)
As I mentioned, this looks bad but appears to be working. I'd still like to know a better method of doing this.
Thank you.
Turns out that by creating the project with fastify-cli I was using fastify-autoload which prevented this from working.
AutoLoad can ignore the DAL files by adding the following to app.js when it registers AutoLoad:
ignorePattern: /.*(DAL).js/,
It then works successfully. Alternatively, I can move notesDAL.js to a folder called services and it works. So the folder structure would be:
/app.js
/plugins/db.js
/routes/notes/notes.js
/services/notesDAL.js

chatbot answers my previously asked questions again even when i am silent/not asking anything

I am developing a chatbot in urdu with wit.ai framework. Chatbot works fine but the issue is when i leave the chatbot for sometime after asking some questions, it start answering the previously told answers in a sequence by starting from first answer to the last one.it means it repeats a sentence but only once. when all the answers are resent, then chatbot does not send them again. I a using Pusher API for realtime responses.I am adding here things in the code which i am not sure about like i don't know what is the purpose of using cors.
Here is some part of my server.js file.
const cors = require('cors');
app.post('/chat', (req, res) => {
const { message } = req.body;
const responses = {
helloo: ["ہیلو! میں امید کرتا ہوں کہ آپ خیریت سے ہیں", ],
};
const firstEntityValue = (entities, entity) => {
const val =
entities &&
entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value;
if (!val) {
return null;
}
return val;
};
const handleMessage = ({ entities }) => {
const helloo = firstEntityValue(entities, 'hello');
if(helloo){
return pusher.trigger('bot', 'bot-response', {
message:
responses.helloo[Math.floor(Math.random() * responses.helloo.length)
],
});
}
return pusher.trigger('bot', 'bot-response', {
message: "میں معزرت خواہ ہوں۔ ",
});
};
client
.message(message)
.then(data => {
handleMessage(data);
})
.catch(error => console.log(error));
});
All this code works fine but i don't know where the issue is that chatbot answers the same answer twice.i am new to javascript and react also. i don't see a loop here which gives answer twice. kindly help me solve the issue.
https://drive.google.com/drive/folders/1TxbqAz_Hfv9bpgY60fLf5TVXwyux_fcI
This is the drive link to my project.

Tweeting w/ media fails using Firebase Cloud Functions

My Firebase web project has been working for several months now. But on Sunday June 3, 2018, my application stopped sending tweets with media (images) attached. Before this, it was working for several months. I have not changed the failing code before the 3rd and I have even reverted to code that worked before that date but the app still fails :(
SDK versions:
I am using the most up to date versions of Firebase tools (3.18.6), and cloud functions (1.0.3). Along with twit (2.2.10) a javascript library for twitter api.
Do note my project was also working on older versions of the above including pre v1.0 cloud functions. Also note, I am still able to send regular text tweets just not ones with any media (image,gif,mp4).
This mainly relates to Twitter's API, but I cannot rule out something funky going on in Firebase's Node.js environment.
How to reproduce:
For simplicity, I will link to the code in a tutorial which I originally used when starting the project.
Setup a twitter account and retrieve all the necessary tokens as outlined in the tutorial. Then simply call the cloud function below and it will attempt to tweet the NASA image of the day.
The function is able to upload the picture to the twitter server and the response I get is expected:
{ media_id: 1004461244487643100,
media_id_string: '1004461244487643136',
media_key: '5_1004461244487643136',
size: 92917,
expires_after_secs: 86400,
image: { image_type: 'image/jpeg', w: 960, h: 1318 } }
However, once it attempts to post the tweet with the media attached, I receive an error
code 324: 'Unsupported raw media category'
which doesn't exist in Twitter's docs: https://developer.twitter.com/en/docs/basics/response-codes.html
Now, Code 324 does exist but in Twitter's docs there is a different description:
"The validation of media ids failed"
Which I have yet to receive. So my media id is valid, so something else is wrong? No where on the internet can I find someone with this exact error.
Link to tutorial code:
https://medium.freecodecamp.org/how-to-build-and-deploy-a-multifunctional-twitter-bot-49e941bb3092
Javascript code that reproduces the issue:
**index.js
'use strict';
const functions = require('firebase-functions');
const request = require('request');
const path = require('path');
const os = require('os');
const fs = require('fs');
const tmpDir = os.tmpdir(); // Ref to the temporary dir on worker machine
const Twit = require('twit');
const T = new Twit({
consumer_key: 'your twitter key'
,consumer_secret: 'your twitter secret'
,access_token: 'your twitter token'
,access_token_secret: 'your twitter token secret'
});
exports.http_testMediaTweet = functions.https.onRequest((req, res) => {
function getPhoto() {
const parameters = {
url: 'https://api.nasa.gov/planetary/apod',
qs: {
api_key: 'DEMO_KEY'
},
encoding: 'binary'
};
request.get(parameters, (err, response, body) => {
if (err) {console.log('err: ' + err)}
body = JSON.parse(body);
var f = path.join(tmpDir, 'nasa.jpg');
saveFile(body, f);
});
}
function saveFile(body, fileName) {
const file = fs.createWriteStream(fileName);
request(body).pipe(file).on('close', err => {
if (err) {
console.log(err)
} else {
console.log('Media saved! '+body.title)
const descriptionText = body.title
uploadMedia(descriptionText, fileName);
}
})
}
function uploadMedia(descriptionText, fileName) {
const filePath = path.join(__dirname, `../${fileName}`)
console.log(`uploadMedia: file PATH ${fileName}`)
T.postMediaChunked({
file_path: fileName
}, (err, data, respone) => {
if (err) {
console.log(err)
} else {
console.log(data)
const params = {
status: descriptionText,
media_ids: data.media_id_string
}
postStatus(params);
}
})
}
function postStatus(params) {
T.post('statuses/update', params, (err, data, respone) => {
if (err) {
console.log(err)
res.status(500).send('Error: ' + err);
} else {
console.log('Status posted!')
res.status(200).send('success');
}
})
}
// Do thing
getPhoto();
});
I was hoping to launch my app next week but this has become a major issue for me. I've tried everything I can think of and consulted the docs for Twitter and the js library but I seem to be doing everything right. Hopefully someone can shed some light on this, thanks.

Categories