RestClient has been removed from this version of the library (TWILIO) - node.js

throw new Error(this.constructor.name + ' has been removed from this
version of the library. Please refer to
https://www.twilio.com/docs/libraries/node for more information.')
^ Error: RestClient has been removed from this version of the library. Please refer to https://www.twilio.com/docs/libraries/node
for more information.
at RestClient.ObsoleteClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:7:9)
at new RestClient (C:\carsapp\node_modules\twilio\lib\base\obsolete.js:12:21)
at Object. (C:\carsapp\helpers\twilio_restful_client_connection.ts:6:34)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
at Object.require.extensions.(anonymous function) [as .ts] (C:\Users\Andrey
Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:425:12)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object. (C:\carsapp\helpers\sing-in-up-helper.ts:8:1)
at Module._compile (module.js:643:30)
at Module.m._compile (C:\Users\Andrey Radkevich\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:422:23)
at Module._extensions..js (module.js:654:10)
const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const Client = require('twilio').RestClient;
const client = new Client(accountSid, authToken);
client.outgoingCallerIds.create(
{
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
},
(err, callerId) => {
if (err) {
console.error(err);
} else {
console.log(callerId.sid);
}
}
);
I have got this error when I tried to create this part of the code above. I tried to add a number to Twilio whitelist ( verify phone number).How can I make it in another way? I use for this Node js
Link on this part of the code in the documentation :
https://www.twilio.com/docs/api/voice/outgoing-caller-ids

const accountSid = 'AC2a54bb2c4ea4992593cc9f0ca2f720c0';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.validationRequests
.create({
friendlyName: 'My Home Phone Number',
phoneNumber: '+14158675310',
})
.then(data => console.log(data.validationCode));
https://www.twilio.com/docs/api/voice/outgoing-caller-ids#add-an-outgoing-caller-id
Here answer on my own question

Related

importing mongodb results in error that is not related to mongodb when running the script using node command

I have a stand alone script that I am using to create an admin user. There will always be only one admin user. However, when I run the standalone script using node command in my nextjs project, I get this weird error below
node indexUser.js
/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:50
var AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf( /*#__PURE__*/_wrapAsyncGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
^
TypeError: Cannot convert undefined or null to object
at Function.getPrototypeOf (<anonymous>)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/utils.js:34:39)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/lib/URL.js:4:15)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/webidl2js-wrapper.js:3:13)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/Users/nabeel.77.dev/Documents/portfolio/node_modules/whatwg-url/index.js:3:34)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/index.ts:1:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Object.newLoader [as .js] (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:141:7)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Function.Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (../src/connection_string.ts:3:1)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._compile (/Users/nabeel.77.dev/Documents/portfolio/node_modules/pirates/lib/index.js:136:24)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
Node.js v19.3.0
The script I am running has the below code:
import bcrypt from 'bcryptjs';
import MongoClientConnection from '../db';
import readline from 'readline';
import { logger } from '../logger';
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.question('Enter username: ', (username) => {
rl.question('Enter email: ', (email) => {
rl.question('Enter password: ', async (password) => {
const hashedPassword = await bcrypt.hash(password, 10);
const adminUserData = { username, email, hashedPassword };
try {
const db = await MongoClientConnection.Get();
const res = await db.insert(adminUserData);
} catch (e) {
logger.error(e);
}
rl.close();
});
});
});
In the code above, when I remove import MongoClientConnection from '../db'; the script works fine so, I believe the error is because of mongodb. I am using singleton connection for mongodb and have the below code for that
import { MongoClient } from 'mongodb';
const MongoClientConnection = (() => {
let db = null;
let instance = 0;
const DbConnect = async () => {
try {
let url = process.env.DB_URL;
let mongoClient = await MongoClient.connect(url, {
useUnifiedTopology: true,
});
const mongoDbInstance = mongoClient.db(process.env.DB);
return mongoDbInstance;
} catch (e) {
return e;
}
};
const Get = async () => {
try {
instance++; // this is just to count how many times our singleton is called.
console.log(`DbConnection called ${instance} times`);
if (db != null) {
console.log(`db connection is already alive`);
return db;
} else {
console.log(`getting new db connection`);
db = await DbConnect();
return db;
}
} catch (e) {
return e;
}
};
return {
Get: Get,
};
})();
export default MongoClientConnection;
Cannot really find any solution to this.

An issue in making my bot online in discord

(Node version: 14.17.6)
When I type node . in terminal, it gives me this issue:
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (C:\Users\DELL\Desktop\Discord Bot\node_modules\discord.js\src\client\Client.js:544:13)
at new Client (C:\Users\DELL\Desktop\Discord Bot\node_modules\discord.js\src\client\Client.js:73:10)
at Object. (C:\Users\DELL\Desktop\Discord Bot\index.js:2:13)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
what I wrote in VSC:
const Discord = require('discord.js');
const bot = new Discord.Client();
const token ='MY TOKEN';
bot.on('ready', () =>{
console.log('This bot is online!');
})
bot.on("message", msg=>{
if (msg.content === "HELLO"){
msg.reply('HELLO FRIEND!');
}
})
bot.login(token);
Client doesn't have intents
These would be your main ones
let bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })

loader.js:800 throw err: node.js

I am trying to make a discord bot for my server and everytime I try to start the bot it gives me the same error every time.
I haven't tried anything else because a google search does not find the error.
I was following a YouTube video that was made in 2017.
const Discord = require("discord.js");
const client = new Discord.Client();
const config = require("./config.json");
var prefix = config.prefix;
//Startup
client.login(config.token);
client.on("ready", () => {
console.log(`Online ${new Date()}`);
client.user.setGame("Online");
});
client.on("message", async message => {
//Ingore bots
if(message.author.bot) return;
//Prefix in command
if(message.content.indexOf(config.prefix) !==0) return;
const args = message.content.slice(config.prefix.legth).trim().split(/
+/g);
const command = args.shift().toLowerCase();
if (command === "ping") {
message.reply("Pong!");
}
});
I expected the bot to start fully but gave me the following error
"internal/modules/cjs/loader.js:800
throw err;
^
SyntaxError: C:\Users\adoss\Desktop\DiscordBot\config.json: Unexpected
string in JSON at position 37
at JSON.parse (<anonymous>)
at Object.Module._extensions..json
(internal/modules/cjs/loader.js:797:27)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\adoss\Desktop\DiscordBot\bot.js:3:16)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)"

Azure Chatbot fails with "SyntaxError: Unexpected identifier - cosmosClient.databases.createIfNotExists" while connecting to CosmosDB

I am extremely new to Azure Bot Services and the Azure platform as a whole.
I am trying to create a Chatbot using node.js but I am getting the below error while trying to connect to CosmosDB.
The bot was running fine before I added the below code to connect to CosmosDB.
Any help or guidance on this would be appreciated!
P.S. - I have added the '#azure/cosmos' package and the code runs without any error if I just remove the try-catch segment.
Code for connecting to CosmosDB:
var async=require("async");
var await=require("await");
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
async function readDatabase() {
const { body: databaseDefinition } = await cosmosClient.database(databaseId).read();
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}
Error Message:
Sat Jan 12 2019 03:40:08 GMT+0000 (Coordinated Universal Time): Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
Application has thrown an uncaught exception and is terminated:
D:\home\site\wwwroot\app.js:40
async function readDatabase() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:76:16)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (D:\Program Files (x86)\iisnode\interceptor.js:459:1)
at Module._compile (module.js:570:32)
You can't await without being in an async function.
Dump all your code into a async function main(){} method, then call main().catch((err) => console.log(err)); or some similar thing to start the promise and handle errors.
You can see a sample of that kind of pattern here in this sample: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ChangeFeed/app.js#L33
--- EDIT 1 ---
Here's your sample rewritten with Promises:
const CosmosClientInterface = require("#azure/cosmos").CosmosClient;
const databaseId = "ToDoList";
const containerId = "custInfo";
const endpoint = "<Have provided the Endpoint URL here>";
const authKey = "<Have provided the AuthKey here>";
const cosmosClient = new CosmosClientInterface({
endpoint: endpoint,
auth: {
masterKey: authKey
},
consistencyLevel: "Session"
});
cosmosClient.database(databaseId).read().then(({body: databaseDefinition}) => {
console.log(`Reading database:\n${databaseDefinition.id}\n`);
}).catch((err) {
console.err("Something went wrong" + err);
});
For your sample above, you don't need to import async/await, they are keywords in JavaScript now.
Here's a blog post that compares and contrasts Async/Await and Promises: https://hackernoon.com/should-i-use-promises-or-async-await-126ab5c98789

How to integrate FCM in node.js for push notifications?

I want to add the push notification thing using FCM in Node.js .For that I tried this
and this and also this
My nodejs code
var FCM = require('fcm-node');
var serverkey = 'SERVERKEY';
var fcm = new FCM(serverkey);
var message = {
to : req.body.userToken,
collapse_key : 'XXX',
data : {
my_key: 'my value', contents: "abcv/"
},
notification : {
title : 'Title of the notification',
body : 'Body of the notification'
}
};
fcm.send(message, function(err,response){
if(err) {
console.log(message);
console.log("Something has gone wrong !");
} else {
console.log("Successfully sent with resposne :",response);
}
});
Whenever I try to run this code and start my server,I get this error in the console always.
/var/www/html/chatApp/node_modules/fcm-node/lib/fcm.js:10
function FCM(accountKey, proxy_url=null) {
^
SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/html/chatApp/node_modules/fcm-node/index.js:1:80)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Can anybody please explain what I'm doing wrong?
I used the firebase-admin package for sending the notifications (https://firebase.google.com/docs/cloud-messaging/admin/send-messages)
var admin = require("firebase-admin");
var serviceAccount = require("./firebase-adminSDK.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const messaging = admin.messaging()
var payload = {
notification: {
title: "This is a Notification",
body: "This is the body of the notification message."
},
topic: 'topic'
};
messaging.send(payload)
.then((result) => {
console.log(result)
})
The firebase-adminSDK.json can be download following the steps in https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app
This code will send a notification to the topic 'topic', however, the firebase-admin package allows sending notifications to a specific device.

Resources