cant send a message to a specific channel - node.js

I have a simple dc bot, code goes like this. I tried to simplfy it to make it more readable
const client = new Discord.Client();
...
client.on('ready', () => {
client.channels.cache.get('315445287374028800').send("works here");
});
setInterval(( () =>{
try{
removeHTML(downloadHTML);
} catch(err){
console.log(err);
}
}),30000);
...
...
let removeHTML = function(callback){
client.channels.cache.get('315445287374028800').send("WORKS HERE");
readHTML();
...
}
let readHTML = function(){
console.log("dolar is read");
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
fs.readFile(dir + '/index.html' , 'utf-8', function(err,html){
if(err)
console.log(err);
else{
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
if(isPeak){
//client.channels.cache.get('315445287374028800').send("DOESNT WORK HERE");
}
}
});
}
seems like send function doesnt work in callback functions but how can i fix this?
Error type: same error for all ("DOESNT WORK HERE") lines :
TypeError: Cannot read property 'send' of undefined
at readHTML (C:\Users\user\Desktop\Discord Bot\index.js:142:18)
at Object.<anonymous> (C:\Users\user\Desktop\Discord Bot\index.js:182:1)
at Module._compile (internal/modules/cjs/loader.js:1015:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1035:10)
at Module.load (internal/modules/cjs/loader.js:879:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.executeUserEntryPoint [as runMain]

I have turned all functions to async-await instead and it worked

Related

TypeError: Cannot read properties of undefined (reading 'getBalance') in node.js

I am getting error when using web3.js to get the balance of an account. I am using ganache. My code is below,
var Web3 = require("web3");
//connect with ganache
const ganacheWeb3 = new Web3(
new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545")
);
console.log(ganacheWeb3);
//check the balance of an account
const balanceOfAccount = Web3.Eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5"
);
console.log(
balanceOfAccount.then((result) =>
console.log(Web3.utils.fromWei(result, "ether"))
)
);
Web3.eth.getBalance(
"0xaEA4e665291fdBFe4bAFc5b81F6F213551180ab5",
(error, result) => {
if (error) {
console.log(error);
} else {
console.log(result);
}
}
);
I have used the normal functional way and callback way. I don't know which one is correct. But still I am getting error. The error is,
const balanceOfAccount = Web3.Eth.getBalance(
^
TypeError: Cannot read properties of undefined (reading 'getBalance')
at Object.<anonymous> (D:\Blockchain Development\Web3.js\intro-to-web3.js\index.js:10:35)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
I am trying to get the value of an ethereum account. But getting an error.
Change Web3.Eth.getBalance(...) to Web3.eth.getBalance(...).
Documentation: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html#getbalance

Express : using await before bcrypt.compare gives error

I am trying to use bcrypt to compare user's password with stored password.
But Express is giving error is I use await before bcrypt.compare
Here is the code :
app.post ('/users/login', (req, res) => {
const user = users.find(user=> user.name === req.body.user)
if (user == null) {
return res.status(400).send('Can Not find user');
} else {
try{
if ( await bcrypt.compare(req.body.password, user.password)) {
res.send("Success");
} else {
res.send("Incorrect PAssword");
}
} catch {
return res.status(500).send('Some Error has occurred');
}
}
});
I am getting this error :
C:\Data\Ashish\projects\jwtAuthentication\app.js:32
if ( await bcrypt.compare(req.body.password, user.password)) {
^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:723:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
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 Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
Please help to find the mistake..
Regards,
Ashish
You forgot to add async to the callback function.
app.post ('/users/login', (req, res) => {
Should be:
app.post ('/users/login', async (req, res) => {
Await will work only with async functions.
It is different from the chrome console. In the console you can directly use await keyword, but in case of node.js, you need to specify async nature of the parent function in which you want to use await.
For further reference, you can refer to this link.

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)"

SyntaxError: Unexpected token function in async function?

Hi everyone I'm beginner in Nodejs and mongoose.I have tried to insert and retrieve the data in mongoose.I'm using async await function to execute one by one (sequence).can anyone help me? Thanks in advance....
i.e: I want to execute (Async await)concept (SEQUENCE STEP)
1.connect the db
2.create the user
3.find the user.
I'm getting the error :
async function calltaskone(){
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:78:16)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
Code for your reference:
'use strict';
const mongoose=require('mongoose');
const calldbconnect=()=>{
return new Promise((resolve,reject)=>{
if(true){
mongoose.connect('mongodb://vdsd:vdwdwh12dw3,#ds11dwdw.mlab.com:1w5664/vorganisation',{useNewUrlParser:true},(err,db)=>{
if(err){
console.log(err);
reject('Db is not connected');
}
else{
resolve('Db is connected');
}
});
}
});
}
const schemadesign=new mongoose.Schema({
clientName:String,
clientId:Number,
clientAddress:String
});
const modeldata=mongoose.model('clientInfo',schemadesign);
const data=[{
clientName:'VIGNESH Mack',
clientId:4128,
clientAddress:'UK'
},{
clientName:'VIGNESH Tokyo',
clientId:4988,
clientAddress:'USA'
}];
function calldatasave(){
return new Promise((resolve,reject)=>{
modeldata.create(data,(err,a,b)=>{
if(err){
reject(`Error occured while data saved ${err}`);
}
else{
resolve('Data saved successfully');
}
});
});
}
const calldatafind=()=>{
return new Promise((resolve,reject)=>{
if(true){
console.log('try to find');
modeldata.find({'clientId':4988},(err,data)=>{
if(err){
reject(`Error occured while find data: ${err}`)
}
else{
console.log(data);
resolve('Data found');
}
});
}
});
}
async function calltaskone(){
const a=await calldbconnect();
console.log(a);
const b=await calldatasave();
console.log(b);
const c=await calldatafind();
console.log(c);
}
calltaskone();
I believe you're using a older version of Node. Async functions are not supported by Node versions older than version 7.6. You can check here.
If you want to use async/await then you need to transpile using Babel for your node version.
Edit:
As you said you are using v7.3, you can use (from v7.0 to v7.5) the --harmony flag to enable the experimental features. To know more about the flag, check this out: What does `node --harmony` do?

TypeError: Object #<Object> has no method 'Request' with elastic.js

i tried the following sample code:
var es=require("elasticsearch");
var ejs = require("ejs");
var client = new es.Client({
host: 'localhost:9200',
log: 'trace'
});
client.ping({
requestTimeout: 3000,
// undocumented params are appended to the query string
hello: "elasticsearch"
}, function (error) {
if (error) {
console.error('elasticsearch cluster is down!');
} else {
console.log('All is well');
}
});
client.search({
index: 'message-1',
type: 'message',
body: ejs.Request().query(ejs.MatchAllQuery())
}).then(function (resp) {
var hits = resp.hits.hits;
}, function (err) {
console.trace(err.message);
});
i am getting the following error when i try to run: node metric.js
/home/karunakar/test/metricagg/metric.js:27
body: ejs.Request().query(ejs.MatchAllQuery())
^
TypeError: Object #<Object> has no method 'Request'
at Object.<anonymous> (/home/karunakar/test/metricagg/metric.js:27:13)
at Module._compile (module.js:456:26)
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 Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:929:3
i could not locate the problem.
-- Thanks
You want the elastic.js module and not ejs, which is a templating engine module.
You can keep the first require("elasticsearch") but the second one should be require("elastic.js") instead of require("ejs")

Resources