(node:4677) UnhandledPromiseRejectionWarning: Unhandled promise rejection - javascript

im creating a discord bot in Glitch.com and i was creating a Warn command, when i finished i try to node him and it works but when I try to warn someone it not warn the user who i selected, so, i go to console log and i fund this error:
"(node:4677) 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(). (rejection id: 4)"
I watch the async and for me it its good, but idk, can you please help me?
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
let warns = JSON.parse(fs.readFileSync("./warnings.json", "utf8"));
module.exports.run = async (bot, message, args) => {
if(!message.member.hasPermission("MANAGE_MEMBERS")) return message.reply("I cant warn a staff member");
let wUser = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0])
if(!wUser) return message.reply("Sir >:( listen plez mention someone no trollies >:(");
if(wUser.hasPermission("MANAGE_MESSAGES")) return message.reply("hey stahp u dont have permision >:(");
let reason = args.join(" ").slice(22);
if(!warns[wUser.id]) warns[wUser.i
] = {
warns: 0
};
warns[wUser.id].warns++;
fs.writeFile("./warnings.json", JSON.stringify(warns), (err) => {
if(err) console.log(err);
});
let warnEmbed = new Discord.RichEmbed()
.setDescription("Warns")
.setAuthor(message.author.name)
.setColor("#ff0000")
.addField("Warned User", wUser.tag)
.addField("Warned in", message.channel)
.addField("Number of Warnings", warns[wUser.id].warns)
.addField("Reason:", reason);
let warnchannel = message.guild.channels.fin('name', "incidents");
if(!warnchannel) return message.reply("Couldn't find channel, if you dont have one create one");
warnchannel.send(warnEmbed);
if(warns[wUser.id].warns == 2) {
let muterole = message.guild.roles.fin('name', "muted");
if(!muterole) return message.reply("You dont have a muterole!, that breaks my heart :(!");
let mutetime = "10m";
await(wUser.addRole(muterole.id));
message.channel.send('${wUser.tag} has been temporaly muted');
setTimeout(function(){
wUser.removeRole(muterole.id)
message.channel.reply('Carlos is da best')
})
}
if(warns[wUser.id].warns == 3) {
message.guild.member(wUser).ban(reason);
message.channel.send('${wUser.tag} has been banned.')
}
}

Well, whats happening is something inside your function is throwing an error. A promise is failing to resolve. To handle promises failing you either follow with .catch(callback) if you are using the .then(callback).catch(callback) style, or you surround with
try{
}
catch(err){
}
if you're using async and await. This should help you figure out what is failing exactly

Related

Discord.js V13 Player is not defined

I'm building a discord.js v13.6.0 music bot and everything is working except this code
const { QueryType } = require('discord-player');
module.exports = {
name: 'play',
aliases: ['p'],
utilisation: '{prefix}play [song name/URL]',
voiceChannel: true,
async execute(client, message, args) {
if (!args[0]) return message.channel.send(`${message.author}, Write the name of the music you want to search. ❌`);
const res = await client.player.search(args.join(' '), {
requestedBy: message.member,
searchEngine: QueryType.AUTO
});
if (!res || !res.tracks.length) return message.channel.send(`${message.author}, No results found! ❌`);
const queue = await client.player.createQueue(message.guild, {
metadata: message.channel
});
try {
if (!queue.connection) await queue.connect(message.member.voice.channel);
} catch {
await client.player.deleteQueue(message.guild.id);
return message.channel.send(`${message.author}, I can't join audio channel. ❌`);
}
await message.channel.send(`Your ${res.playlist ? 'Your Playlist' : 'Your Track'} Loading... 🎧`);
res.playlist ? queue.addTracks(res.tracks) : queue.addTrack(res.tracks[0]);
if (!queue.playing) await queue.play();
},
};
When I use this command, the following error occurs:
Unhandled promise rejection: ReferenceError: player is not defined
I'm new to programming, sorry for any silly mistakes, if you need any info don't hesitate to ask
The possibility of such errors appears either by throwing inside of a async function without a catch block or rejecting a promise which didn't had a .catch()
You might be doing:
you put your code inside an async function in order to use await calls.
The awaited function fails.
The solutions are:
Either use .catch()
await returnsPromise().catch(e => { console.log(e) })
or
2.Use try/ catch block
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
}

Mute role not working with time, UnhandledPromiseRejectionWarning

I'm making a mute and unmute command for our system bot, the mute should be timed by hours, but I have it as seconds just to test it, anyway, my problem is that when the command is used whether there is an args1 which is the time the mute will last in hours or not it sends an error and just uses the default time, anyone knows why?
My code:
const { MessageEmbed } = require('discord.js');
module.exports = {
name: 'mute',
category: 'Owner',
aliases: ["t"],
description: 'Mute command.',
usage: 'mute <memeberid> <time>',
userperms: [],
botperms: [],
run: async (client, message, args) => {
if (!message.guild) return;
if (message.author.bot) return;
if (!message.member.roles.cache.has("916785912267034674")) return message.channel.send("You are not a staff member.").then(m => m.delete({timeout: 4000}))
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("I don't have permission to do this.").then(m => m.delete({timeout: 4000}))
let time = args[1]
let reason = args[2]
if (!reason) reason = "Violated server rules";
if (!time) time = "1"
const user = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const muterole = message.guild.roles.cache.get("916963460540157962");
const embed = new MessageEmbed()
.setTitle('Member muted!')
.addField('User muted', '<#'+user+'>')
.addField('muted by', message.author)
.addField('Reason', reason)
.addField('For', time + " hour(s)")
.setFooter('Time muted', client.user.displayAvatarURL())
.setThumbnail('https://th.bing.com/th/id/R.3e3ee93bca49df93c9751dbb284d7ec8?rik=fKLepuY9WQQnew&riu=http%3a%2f%2fimage.flaticon.com%2ficons%2fpng%2f512%2f25%2f25632.png&ehk=mdsvAx56LxLhOmmktJkpp5Vbse%2fxjnaW8mxahrVoQeU%3d&risl=&pid=ImgRaw&r=0')
.setTimestamp()
if (!args[0]) return message.channel.send("Please mention a member or use an ID.")
if (!user) return message.channel.send("Error: Can't find that user.")
if (user.user.id == message.author.id) return message.channel.send("Uhh, why don't you just shut up like humans?")
if (user.user.id == client.user.id) return message.channel.send("You good bro?")
if (user == message.author.id) return message.channel.send("Uhh, why don't you just shut up like humans?")
if (user == client.user.id) return message.channel.send("You good bro?")
if (user.roles.cache.has("916963460540157962")) return message.channel.send("Chill, his already muted!")
if (user.roles.cache.has("916785912267034674")) return message.channel.send("You can't mute staff, idoit.")
message.channel.send(embed).catch(err => console.log("Error: " + err));
user.roles.add("916963460540157962").then(user.roles.remove("916963460540157962") ({timeout: time+"00000"})).catch(err => console.log("Error: " + err));
}
}
Error:
(node:1460) UnhandledPromiseRejectionWarning: TypeError: user.roles.remove(...) is not a function
at Object.run (/home/runner/DwaCraft-Main-bot/commands/owner/Mute.js:47:87)
at module.exports (/home/runner/DwaCraft-Main-bot/events/guild/message.js:52:11)
at Client.emit (events.js:314:20)
at MessageCreateAction.handle (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/actions/MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/handlers/MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:384:31)
at WebSocketShard.onPacket (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:444:22)
at WebSocketShard.onMessage (/home/runner/DwaCraft-Main-bot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/home/runner/DwaCraft-Main-bot/node_modules/ws/lib/event-target.js:132:16)
at WebSocket.emit (events.js:314:20)
(node:1460) 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:1460) [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.
Thanks !
You are using user.roles.remove(id) ({timeout: time+"00000"}) which is obviously bad syntax. Also, role removal does not have a built in timeout. You will need to use setTimeout, or a database for larger times
await user.roles.add(id)
setTimeout(() => user.roles.remove(id), time * 1000) // *1000 for seconds
As I said before, it only works well with short times, use a database for longer times
The syntax seems to be incorrect, try with :
user.roles.add("916963460540157962").then(() => setTimeout(() => user.roles.remove("916963460540157962", +time))

How to fix Unhandled promise rejection in nodejs?

I get an error message I don't know how to fix:
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)
My code:
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require('fs');
client.login('NzUzNzAwMzQ2MDI2Nzg2ODI2.X1qAJQ.K-2nBZOSxz8k0LAnGmNC_EGaKqQ');
(async () => {
client.on('message', async (message) => {
// Voice only works in guilds, if the message does not come from a guild,
// we ignore it
if (!message.guild)
return;
if (message.content === '/join') {
// Only try to join the sender's voice channel if they are in one themselves
if (message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
} else {
message.reply('You need to join a voice channel first!');
}
const dispatcher = connection.playFile('C:/Users/vikto/Desktop/FFBot/Audio/gab.mp3');
}
});
throw();
})()
client.login('NzUzNzAwMzQ2MDI2Nzg2ODI2.X1qAJQ.K-2nBZOSxz8k0LAnGmNC_EGaKqQ');
you should encompass all that code inside a try catch as there several statements can also produce a rejected promise.

Giphy not working on Discord bot (javascript)

I was following this tutorial on how to make a discord bot, everything was working fine until 33:32 where he added the giphy stuff i had already installed giphy sdk/api, created an application, but after he made the search statement he said you can console log it so i did it, and there were some gif results coming out, which returned undefined on my console(i dunno why), then he added some math stuff, which i also did, then at the point where he added the messaging part where he also added this code files:[responseFinal.images.fixed_height.url] which then returned this on my console
(node:3136) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'images' of undefined
at D:\Discord bots\Oboto v2.0\index.js:24:61
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:3136) 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:3136) [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.
and this confused the flip outta me, then i picked an alt approach, instead of doing giphy.search i did
giphy.random with the same arguments, removed the math stuff and console.log(response)the response and guess what it actually gave me a single gif!(in the console of course) then i implemented to my files:[]statement aaaaand it returned the same thing (cannot read property 'images' of undefined) im also kinda new to discord.js and javascript, also here is my entire code,
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const client = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core')
giphy = GphApiClient(giphyToken)
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
if (message.member.hasPermission(["KICK_MEMBERS", "BAN_MEMBERS"])){
if (message.content.startsWith(`${prefix}kick`)) {
let member = message.mentions.members.first();
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
})
})
}
}
})
client.login(token);
cannot read property 'images' of undefined, this means you are trying to access a null object. Same as null pointer exception in java. It means your response is null.
And you are also getting UnhandledPromiseRejectionWarning which means your promise is throwing error which you are not catching anywhere. You can catch your error like this
member.kick().then((member) =>{
giphy.random('gifs', {'q':'fail'})
.then((response) => {
console.log(response);
message.channel.send(":wave:",{files:[response.images.fixed_height.url]});
}).catch(e => { console.error(e}) }
}).catch(e => { console.error(e) }
Now you can see what error you are getting. You can also use try catch approach with async await.
THIS CODE IS FIXED BY ME :D
Discord Bot - Kick member with Giphy
IM NOT A PROFESSIONAL AT ALL.
You can also add this giphy to new member notice.
const Discord = require('discord.js');
const { prefix, token, giphyToken } = require('./config.json');
const bot = new Discord.Client();
var GphApiClient = require('giphy-js-sdk-core');
bot.giphy = GphApiClient(giphyToken);
bot.on('message', (message) => {
if (message.member.hasPermission(['KICK_MEMBER', 'BAN_MEMBERS'])) {
//console.log(message.content);
if (message.content.startsWith(`${prefix}kick`)) {
//message.channel.send("kick")
let member = message.mentions.members.first();
member.kick().then((member) => {
bot.giphy.search('gifs', { q: 'fail' }).then((response) => {
var totalResponses = response.data.length;
var responseIndex = Math.floor(Math.random() * 10 + 1) % totalResponses;
var responseFinal = response.data[responseIndex];
message.channel.send(':wave: ' + member.displayName + ' has been kicked!',{
files: [responseFinal.images.fixed_height.url]
}
)
})
})
}
}
});
bot.login(token);

Handle promise rejection with Chai

I have the following validation function checking if a user exists:
validate.user = async (user, password) => {
const matches = await bcrypt.compare(password, user.password);
if (matches) return user;
if (!matches) {
return validate.logAndThrow('User password does not match');
}
return validate.logAndThrow('Error in bcrypt compare');
};
The following test using Chai should test this:
chai.use(sinonChai);
const { expect } = chai;
describe('#user', () => {
it('show throw if user is undefined', () => {
expect(() => validate.user(undefined, 'pass')).to.throw('User does not exist');
});
The error does get thrown, however mocha shows the following in the console:
2) show throw if user is undefined
(node:18587) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: User does not exist
So my question is, how I can rewrite the test such that it does catch promise rejections?
For testing promise-based functions (async) use chai-as-promised plugin:
expect(validate.user(undefined, 'pass')).to.be.rejectedWith(Error, 'User does not exist');
In this case you do not put () => validate.user() into expect because it will not return a promise. async functions always return a promise, so it's enough to just call your method inside expect (without wrapping it into a method).
I hope this is clear :) If you have any questions - feel free to ask.
Im not totally sure it is mocha that throws that unhandled rejection.
I think it is your bcrypt.compare which is async by nature and uses callbacks. await can't really be used out of the box with async functions.
but you can promisify the async calls with nodes util library like this:
const util = require('util');
const bcrypt = require('bcrypt');
const bcryptCompare = util.promisify(bcrypt.compare);
Now you can use await bcryptCompare(password, user.password); like you intended. please note that i changed the constant after the await call.
Also to handle rejections with async/await you should use try/catch like this:
let matches;
try {
matches = await bcryptCompare(password, user.password);
} catch(bcryptError) {
throw new Error(bcryptError);
}

Categories