I am trying to deploy my functions but that shows an error. I am trying to use cloud speech api & cloud translation api with firebase cloud function.
const functions = require('firebase-functions');
const Speech = require('#google-cloud/speech');
const Translate = require('#google-cloud/translate');
const speech = Speech({keyFilename: "credentials.json"});
const translate = Translate({keyFilename: "credentials.json"});
const Encoding = Speech.v1.types.RecognitionConfig.AudioEncoding;
function getLanguageWithoutLocale(languageCode) {
if (languageCode.indexOf("-") >= 0) {
return languageCode.substring(0, languageCode.indexOf("-"));
}
return languageCode;
}
exports.onUpload = functions.database
.ref("/uploads/{uploadId}")
.onWrite((event) => {
let data = event.data.val();
let language = data.language ? data.language : "en";
let sampleRate = data.sampleRate ? data.sampleRate : 16000;
let encoding = data.encoding === "FLAC" ? Encoding.FLAC : Encoding.AMR;
let request = {
config: {
languageCode : language,
sampleRateHertz : sampleRate,
encoding : encoding
},
audio: { uri : `gs://mimming-babelfire.appspot.com/${data.fullPath}` }
};
return speech.recognize(request).then((response) => {
let transcript = response[0].results[0].alternatives[0].transcript;
return event.data.adminRef.root
.child("transcripts").child(event.params.uploadId)
.set({text: transcript, language: language});
});
});
exports.onTranscript = functions.database
.ref("/transcripts/{transcriptId}")
.onWrite((event) => {
let value = event.data.val();
let transcriptId = event.params.transcriptId;
let text = value.text ? value.text : value;
let languages = ["en", "es", "pt", "de", "ja", "hi", "nl", "fr", "pl"];
// All supported languages: https://cloud.google.com/translate/docs/languages
let from = value.language ? getLanguageWithoutLocale(value.language) : "en";
let promises = languages.map(to => {
console.log(`translating from '${from}' to '${to}', text '${text}'`);
// Call the Google Cloud Platform Translate API
if (from === to) {
return event.data.adminRef.root
.child("translations").child(transcriptId).child(to)
.set({text: text, language: from});
} else {
return translate.translate(text, {
from: from,
to: to
}).then(result => {
// Write the translation to the database
let translation = result[0];
return event.data.adminRef.root
.child("translations").child(transcriptId).child(to)
.set({text: translation, language: to});
});
}
});
return Promise.all(promises);
});
I installed #google-cloud/speech and #google-cloud/translate in npm.
it shows error
Error: Error occurred while parsing your function triggers.
TypeError: Speech is not a function
at Object.<anonymous> (C:\Users\Akash\AndroidStudioProjects\Translator\functions\index.js:6:16)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Module.require (module.js:593:17)
at require (internal/module.js:11:18)
at C:\Users\Akash\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:18:11
at Object.<anonymous> (C:\Users\Akash\AppData\Roaming\npm\node_modules\firebase-tools\lib\triggerParser.js:38:3)
please help me to find the error if anyone knows. Thank you in advance
It's complaining about this line:
const speech = Speech({keyFilename: "credentials.json"});
You're using Speech as if it's a function, but it's not a function.
Looking at the documentation, it seems that you're supposed to initialize it like this:
const speech = require('#google-cloud/speech');
const client = new speech.SpeechClient();
Related
Every time I try to run my discord bot I get this error:
node:internal/modules/cjs/loader:1047
const err = new Error(message);
^
Error: Cannot find module './src/Commands/Tools/ping.js'
Require stack:
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js
- /Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js
at Module._resolveFilename (node:internal/modules/cjs/loader:1047:15)
at Module._load (node:internal/modules/cjs/loader:893:27)
at Module.require (node:internal/modules/cjs/loader:1113:19)
at require (node:internal/modules/cjs/helpers:103:18)
at client.handleCommands (/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js:15:25)
at Object.<anonymous> (/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js:19:8)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1280:10)
at Module.load (node:internal/modules/cjs/loader:1089:32)
at Module._load (node:internal/modules/cjs/loader:930:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/Functions/Handlers/commandHandler.js',
'/Users/011935/Programming/JS/Bots/Command Bot v3/src/bot.js'
]
}
Here are my bot.js, commandHandler.js, and ping.js files and my file structure
bot.js
require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];
const functionFolders = fs.readdirSync(`./src/Functions`);
for (const folder of functionFolders) {
const functionFiles = fs
.readdirSync(`./src/Functions/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of functionFiles)
require(`./Functions/${folder}/${file}`)(client);
}
client.handleCommands();
client.handleEvents();
client.login(token);
commandHandler.js
const { REST } = require("#discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
const path = require("node:path");
module.exports = (client) => {
client.handleCommands = async () => {
const commandFolders = fs.readdirSync(`./src/Commands`);
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(`src/Commands/${folder}`)
.filter((file) => file.endsWith(".js"));
const { commands, commandArray } = client;
for (const file of commandFiles) {
const command = require(`src/Commands/${folder}/${file}`);
commands.set(command.data.name, command);
commandArray.push(command, command.data.toJSON());
console.log(`Command: ${command.data.name} has been registered`);
}
}
const clientId = "1070133880671174697";
const guildId = "1070126560004276305";
const rest = new REST({ version: "9" }).setToken(process.env.token);
try {
console.log("Started refreshing commands.");
await rest.put(Routes.applicationCommands(clientId, guildId), {
body: client.commandArray,
});
console.log("Successfully refreshed commands.");
} catch (err) {
console.error(error);
}
};
};
ping.js
module.exports = {
data: new SlashCommandBuilder()
.setName("ping")
.setDescription("Returns my ping"),
async execute(interaction, client) {
console.log("pinged");
},
};
File Structure
File Structure
I've tried editing it myself, checking I've written the right code in the tutorial, and extensive googling, but nothing works, and for people who have had the same problem theirs just 'magically' fixed.
Edit 1 - I have tried ../../src as #rebe100x suggested but when I did path.basename it gave me this error
Error: ENOENT: no such file or directory, scandir 'Tools'
Edit 2 - I used 'src/Commands/${folder} but now it gives me the same error as before
On commandHandler.js line 15
const command = require(`./src/Commands/${folder}/${file}`);
The file directory is wrong. From your structure, commandHandler.js is in Function > Handlers > commandHandler.js.
Simply change the directory to ../../src/Commands/${folder}/${file} and it should fix the path problem
I'm trying to learn how to create NFTs on the Ethereum block chain.
In terminal (Ubuntu 20.04.3 LTS)
Aki-Zeta:~/my-nft$ node scripts/mint-nft.js
I keep getting
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
Syntax Error Unexpected Token {
see bottom for full error
Here is my code using VScode
require("dotenv").config()
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")
const contractAddress = "0xf469355dc12e00d8cda65b3a465bdad65da27e22"
const nftContract = new web3.eth.Contract(contract.abi, contractAddress)
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI(),
}
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
signPromise
.then((signedTx) => {
web3.eth.sendSignedTransaction(
signedTx.rawTransaction,
function (err, hash) {
if (!err) {
console.log(
"The hash of your transaction is: ",
hash,
"\nCheck Alchemy's Mempool to view the status of your transaction!"
)
} else {
console.log(
"Something went wrong when submitting your transaction:",
err
)
}
}
)
})
.catch((err) => {
console.log(" Promise failed:", err)
})
}
mintNFT(
"https://gateway.pinata.cloud/ipfs/QmcRikKfA6xdaNZkojW28xpvZYysQXSJEb52YdeRJP3GGv"
)
Is it something to do with that "{" in line 6, or something else in line 6?
Prior to running this script I ran "npm install #alch/alchemy-web3", and verified the directories exist (both by going there and with cd). Other people with similar issues are missing something, and I have no idea what I'm missing. I have checked for spurious spaces and semicolons but I am not experienced with this language.
I have been using the tutorials off of the Ethereum project site.
full error
/home/patonn89/my-nft/scripts/mint-nft.js:6
const { createAlchemyWeb3 }
^
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:471:10)
at startup (node.js:117:18)
at node.js:951:3
I had exactly the same error, and it was just a spurious character in my VScode editor, same example as you from ethereum.org.
As you can see in line 24
change const { createAlchemyWeb3 } to const { createAlchemyWeb3 } = require("#alch/alchemy-web3")
I'm trying to run Document OCR from Google with a Node js app.
So i used the client library for Node js #google-cloud/documentai
I did everything like in documentation sample
There is my code
const projectId = '*******';
const location = 'eu'; // Format is 'us' or 'eu'
const processor = '******'; // Create processor in Cloud Console
const keyFilename = './secret/******.json';
const { DocumentProcessorServiceClient } = require('#google-cloud/documentai').v1beta3;
const client = new DocumentProcessorServiceClient({projectId, keyFilename});
async function start(encodedImage) {
console.log("Google AI Started")
const name = `projects/${projectId}/locations/${location}/processors/${processor}`;
const request = {
name,
document: {
content: encodedImage,
mimeType: 'application/pdf',
},
}
try {
const [result] = await client.processDocument(request);
const { document } = result;
const { text } = document;
const getText = textAnchor => {
if (!textAnchor.textSegments || textAnchor.textSegments.length === 0) {
return '';
}
// First shard in document doesn't have startIndex property
const startIndex = textAnchor.textSegments[0].startIndex || 0;
const endIndex = textAnchor.textSegments[0].endIndex;
return text.substring(startIndex, endIndex);
};
const [page1] = document;
const { paragraphs } = page1;
for (const paragraph of paragraphs) {
const paragraphText = getText(paragraph.layout.textAnchor);
console.log(`Paragraph text:\n${paragraphText}`);
}
return paragraphs;
}
catch (error) {
console.error(error);
}
}
module.exports = {
start
}
Image encoding is here
const {start: google} = require('./document-ai/index')
if (mimeType === 'application/pdf') {
pdf = true;
encoded = Buffer.from(file).toString('base64');
}
await google(encoded);
In result i get this error
Google AI Started
Error: 3 INVALID_ARGUMENT: Request contains an invalid argument.
at Object.callErrorFromStatus (C:\Users\NIKIGAN\WebstormProjects\papper-project\server\node_modules\google-gax\node_modules\#grpc\grpc-js\build\src\call.js:31:26)
at Object.onReceiveStatus (C:\Users\NIKIGAN\WebstormProjects\papper-project\server\node_modules\google-gax\node_modules\#grpc\grpc-js\build\src\client.js:176:52)
at Object.onReceiveStatus (C:\Users\NIKIGAN\WebstormProjects\papper-project\server\node_modules\google-gax\node_modules\#grpc\grpc-js\build\src\client-interceptors.js:342:141)
at Object.onReceiveStatus (C:\Users\NIKIGAN\WebstormProjects\papper-project\server\node_modules\google-gax\node_modules\#grpc\grpc-js\build\src\client-interceptors.js:305:181)
at C:\Users\NIKIGAN\WebstormProjects\papper-project\server\node_modules\google-gax\node_modules\#grpc\grpc-js\build\src\call-stream.js:124:78
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
code: 3,
details: 'Request contains an invalid argument.',
metadata: Metadata {
internalRepr: Map { 'grpc-server-stats-bin' => [Array] },
options: {}
},
note: 'Exception occurred in retry method that was not classified as transient'
}
What invalid arguments do I have in my request?
Environment details
OS: Windows 10
Node.js version: 12.18.3
npm version: 6.14.8
#google-cloud/documentai version: 2.2.1
I've strugglid with this as well and the solution is quite simple as it turns out: you have to set the parameter apiEndpoint when your location is not "us".
Here's an example for location "eu":
const client = new DocumentProcessorServiceClient({
keyFilename,
apiEndpoint: 'eu-documentai.googleapis.com'
});
More information here: GitHub: googleapis /
nodejs-document-ai
i'm just newbie on nodeJs ,and i need your help
my utile.js file :
const fs = require('fs');
const addNotes = function(name,age,birthday){
const notesExist = loadNotes()
notesExist.push({
name: name,
age: age,
birthday:birthday
})
}
const loadNotes = function (){
try{
binaryVersion = fs.readFileSync('./JsonFile/data.json');
stringVersion = binaryVersion.toString();
dataParsed = JSON.parse(stringVersion);
return dataParsed;
}
catch(err){
return [];
}
}
module.exports = {
addNotes: addNotes,
loadNotes: loadNotes
}
my intro.js file
yargs = require('yargs');
const utile = require('./utile.js');
yargs.command({
command: 'add',
describe: 'Adding new record',
builder:{
name:{
describe:'note name',
demandOption:true, // title option to be requires in the command line
type:'string' //requie a string as title value
},
age:{
describe:'note age',
demandOption:true,
type:'string' //require astring as body value
},
birthday:{
describe:'note birthday',
demandOption:true,
type:'string' //require astring as body value
},
},
handler: function(argv){
// console.log(chalk.green(chalk.red(argv.title)))
/* console.log(chalk.green(chalk.green(argv.body))) */
utile.addNotes(argv.name,argv.age,argv.birthday);
}
});
my data.json file :
{"name":"Hannani","age":25,"birthday":1995}
But when i run the intro.js file by : node intro.js add --name="booktitle" --age="dsds" --birthday="1995" i got i nice erro [I spent 3 hours but i didn't find anything to solve that error ]
Error :
/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1195
else throw err
^
TypeError: notesExist.push is not a function
at Object.addNotes (/home/simo/Documents/nodeJs/utile.js:34:20)
at Object.handler (/home/simo/Documents/nodeJs/intro.js:56:19)
at Object.runCommand (/home/simo/Documents/nodeJs/node_modules/yargs/lib/command.js:240:40)
at Object.parseArgs [as _parseArgs] (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1107:41)
at Object.parse (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:566:25)
at Object.<anonymous> (/home/simo/Documents/nodeJs/intro.js:86:7)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
ps: I didn't change anything in my yargs.js file ..
Please what i'm doing wrong ? Thanks in advance !
THe data.json needs to be array format for you to be able to push. Something like this
[{"name":"Hannani","age":25,"birthday":1995}]
Also, since it is a normal json file you could simply require it as will instead of using fs to read it.
const data = require('./JsonFile/data.json')
Hope this helps.
I had implemented firebase functions in my app and previously it was working fine but now it is showing error Cannot read property 'previous' of undefined
Error Logs of function
TypeError: Cannot read property 'previous' of undefined
at exports.LoveNotification.functions.database.ref.onWrite (/user_code/index.js:223:16)
at cloudFunctionNewSignature (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:109:23)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:139:20)
at /var/tmp/worker/worker.js:730:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
The signature of Cloud Functions triggers has changed. You seem to be using beta, but are deploying to the latest version. See the migration guide for complete instructions.
From there:
Before (<= v0.9.1)
exports.dbWrite = functions.database.ref('/path').onWrite((event) => {
const beforeData = event.data.previous.val(); // data before the write
const afterData = event.data.val(); // data after the write
});
Now (>= v1.0.0)
exports.dbWrite = functions.database.ref('/path').onWrite((change, context) => {
const beforeData = change.before.val(); // data before the write
const afterData = change.after.val(); // data after the write
});
So your code should look something like this:
exports.LoveNotification = functions.database.ref("/Member/{pushId}").onWrite((change, context) => {
if (change.before.exists()) {
return;
} else {
var eventLove = change.after.data.val();
var author =eventLove.fullname;
var title = eventLove.course;
var key = eventLove.key;
const payload = {
"data": {
"post_id": key
},
notification: {
title: author +'Joined the app',
body: `Course `+title,
sound: "default",
icon: "ic_launcher",
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 * 24 //24 hours
};
console.log('Sending notifications');
return admin.messaging().sendToTopic("Member", payload, options);
}
});