I'm trying to connect the openai api into my app but I'm not sure why it's not working. From my frontend, I have a createUserData that receives an input and then stores it to my MongoDB database. But now, I want to send that input that I received to the openai API and get a response based on what they said. I tried implementing it here but it crashed on me with this error:
UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
at createError (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (C:\Users\simer\Downloads\Talkhappi\server\node_modules\axios\lib\adapters\http.js:322:11)
at IncomingMessage.emit (events.js:387:35)
at endReadableNT (internal/streams/readable.js:1317:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:17844) 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(). To terminate the node process on unhandled promise
rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:17844) [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.
For some reason I crash when I try and call this API, am I doing it wrong?
Right now I just want to log whatever the response I get from the API, once I'm able to do that then I will store it to the database as well. But I can't even log it as I get an error. Here is my code:
const { Configuration, OpenAIApi } = require("openai");
// create new user data
const createUserData = async (req, res) => {
const {id, scores, transcript} = req.body
const user_id = req.user._id
console.log(user_id)
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const response = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Provide personal feedback for me and give me tips: " + transcript,
temperature: 0.7,
max_tokens: 256,
top_p: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
console.log(response)
const newUserData = new UserData({
id: id,
scores: scores,
transcript: transcript,
user_id: user_id
})
// add doc to db
try {
await newUserData.save()
} catch (error) {
res.status(400).json({error: error.message})
}
console.log('POST:', newUserData)
return res.status(201).json({user_data: newUserData})
}
Related
This is the index.js script of the bot:
const { Client, RichEmbed } = require('discord.js')
const bot = new Client()
const util = require('minecraft-server-util')
const token = 'bot_token'
const PREFIX = 'l.'
bot.on('ready', () => {
console.log('Bot has come online.')
})
bot.on('message', message => {
let args = message.content.substring(PREFIX.length).split(' ')
switch (args[0]) {
case 'status':
util.status('IP', (PORT), (error, reponse) => {
if (error) throw error
const Embed = new RichEmbed()
.setTitle('Server Status')
.addField('Server IP', reponse.host)
.addField('Server Version', reponse.version)
.addField('Online Players', reponse.onlinePlayers)
.addField('Max Players', reponse.maxPlayers)
message.channel.send(Embed)
})
break
}
})
bot.login(token)
When I type node . in the console and I type l.status on the Discord server, it shows this error on the console:
(node:3300) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Expected 'options' to
be an object or undefined, got number
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:46:25
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
at __awaiter (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:4:12)
at status (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:40:12)
at Object.<anonymous> (C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:113:17)
at Generator.next (<anonymous>)
at C:\Users\HNRK\Desktop\LightSide\node_modules\minecraft-server-util\dist\status.js:8:71
at new Promise (<anonymous>)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:3300) 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(). To terminate the node process on unhandled promise rejection, use the
CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:3300) [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.
Can anybody help? I also tried a lot of different solutions, but none of them worked.
You are using an outdatet version of discord.js. Type npm i discord.js#latest into your terminal. In the latest version of discord.js, RichEmbed() has been removed and replaced by MessageEmbed().
This is an answer based on assumption since I've never used minecraft-server-util before. Also assuming that you're using the latest minecraft-server-util,
Based on the error;
Expected 'options' to be an object or undefined, got number
And, based on this commit, You should pass the 2nd argument as an object instead of PORT since it's a type of StatusOptions instead of a number.
So, instead of;
util.status('IP', (PORT), (error, reponse) => {
You should be doing;
util.status('IP', {
port: (PORT)
}, (error, reponse) => {
i'm having a headache with this cause i can't understand what's the problem.
This is my code in Express
router.patch("/:id", verifyToken, async (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
try {
let postId = parseInt(id);
if (postId < 0)
res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
//Validate post data
const { error } = validatePostData({
title,
content,
});
//Is there and error? Let the user know it.
if (error)
res.status(400).json(utils.generateError(error.details[0].message));
const slug = await utils.generateSlug(title);
const summary = await utils.extractSummary(content, 240);
const foundImage = await content.match(/!\[.*?\]\((.*?)\)/);
let image = "";
if (foundImage) image = foundImage[1];
const result = await pool.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
);
if (result) res.json(result.rows[0]);
else throw "Error on updating result";
} catch (e) {
console.log(e);
res.json(utils.generateError("Something went wrong, try again."));
}
});
But when i make a patch request i get this in the console.
(node:20756) UnhandledPromiseRejectionWarning: error: invalid input syntax for integer: "NaN"
at Parser.parseErrorMessage (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/Users/jcmunguia/Desktop/readalot-app/node_modules/pg-protocol/dist/index.js:8:42)
at Socket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
(node:20756) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20756) [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.
I'm using Postgres and pg for node to handle the database, the strange part is that the row is updated in the db but the result of the query doesn't return anything but that error.
Can anyone help me solve this?
I want to use the google-spreadsheet API to fetch and write data to a sheet in my Discord bot (using discord.js). For some reason, I can't get it to work. This is my code:
const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')
module.exports = {
/...
execute(message, args) {
accessSpreadsheet()
}
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('<id was here>')
doc.useServiceAccountAuth(creds)
.then(() => {
doc.getInfo()
.then(info => {
console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
const sheet = info.worksheets[0]
console.log(
`sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
)
})
})
}
This is the error I keep getting:
(node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:4) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:4) [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.
I should actually use async/await for achieving this. My code has become:
async function accessSpreadsheet(message, args, msg) {
const doc = new GoogleSpreadsheet('<id was here>')
await doc.useServiceAccountAuth(creds)
await doc.loadInfo()
console.log(doc.title) //whatever you want to log goes here
})
Hope you all safe,
My scenario is -> Get the message list and get the ID for each message. Get the message body based on the message ID. Finally, the text is Base64 converted,
const gmailGetMessagesAsync = promisify(gmail.users.messages.get);
const gmailListMessagesAsync = promisify(gmail.users.messages.list);
let res = await gmailListMessagesAsync({
auth: oauth2Client,
userId: 'me'
});
const newestMessageId = res.messages[0].id;
res = await gmailGetMessagesAsync({
auth: oauth2Client,
userId: 'me',
id: newestMessageId
});
const base64mailBody = res.payload.parts[0].body.data;
const mailBody = new Buffer(base64mailBody, 'base64').toString();
With this I am getting an error,
(node:9041) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '0' of undefined
at main (/NODEGMAIL/getLabels.js:42:37)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:9041) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
Appreciate your help on this matter
Do
JSON.parse(res) and you will get your object. You can access the content and manipulate it afterward.
Hi I'm currently trying to learn and implement some unit testing for my HTTP Requests. currently I have a SQlite db setup, and a simple post request. This is the test I have written so far:
"use strict";
process.env.NODE_ENV = 'test';
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const app = require('../../../app');
chai.request('http://localhost:8080')
.put('/tempValue')
.send({sensorid: '1', sensorValue: '25.00', timeRecorded: '2020-04-12 12:30'})
.then(function (res) {
expect(res).to.have.status(200);
})
.catch(function (err) {
throw err;
});
I seem to be getting a error that it is unable to open the database file. Currently I am just connecting to the database in the app.js file, using const dbPath = "./database/database.db"; and const dbConnection = sqlite.open(dbPath, { Promise });
I also seem to get errors about incorrect use of .catch? This is the error log:
(node:13952) UnhandledPromiseRejectionWarning: Error: SQLITE_CANTOPEN: unable to open database file
(node:13952) 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(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13952) [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.
(node:13952) UnhandledPromiseRejectionWarning: AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 200 but got 404
at D:\Uni Work\3rd Year\302CEM - Agile Development\Penguin Project\test\api\temperature\get.js:15:29
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13952) 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(). To terminate the node process on unha
ndled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Thanks for any help!
EDIT:
This is the particular post request I'm testing, it uses MQTT to check if the message being sent is to that topic structure, then inserts into the database.
app.ws.use(route.all('/tempValue', function (ctx){
client.on('message', async function(topic,message){
console.log(topic, message.toString());
if (topic === '302CEM/Penguin/Room1/Temperature'){
const SQL = "INSERT INTO sensorData (sensorid, sensorValue, timeRecorded) VALUES (?,?,?)";
try {
const temptostring = message.toString();
const db = await dbConnection;
await db.run(SQL, ["1",temptostring, moment().format('YYYY-MM-DD HH:mm')]);
ctx.websocket.send(temptostring);
} catch (err) {
console.log(err);
}
}
})
}));