how to fix UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Channel - discord.js

i gonna make read this channel only
but it error (node:17212) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Channel
my code
client.on('message', async message => {
if(message.channel.name.includes("Command-only")){
message.channel.bulkDelete("1", true);
if(!message.author.bot){
message.channel.send("Test, you say :" + `${message.content}`);
}
}
})

Your bot is reading all messages coming to it, including DMs, which do not have names. You should filter out dm channels.
if(message.channel.type === 'dm') return;

Related

TypeError [INVALID_TYPE]: Supplied options is not an object error when trying to ban someone

My ban command checks if a user is bannable then bans them. My kick does the same thing but it actually works. The ban message sends so the user is bannable but doesn't actually get banned. Here's my code
if (memberTarget.bannable) {
if (
message.member.roles.highest.position >
message.guild.members.cache.get(target.id).roles.highest.position
) {
target.ban(reason);
let banReason = new Discord.MessageEmbed()
.setDescription(`**${target.user.tag}** has been banned.`)
.addField("Reason:", `${!reason ? "Unspecified" : `${reason}`}`)
.setFooter(
`banned by ${message.author.tag}`,
"https://cdn.discordapp.com/attachments/375020097431011328/881012463645126686/3dgifmaker15131.gif"
)
.setColor("#000000");
message.reply({ embeds: [banReason] }).catch((err) => {
message.channel.send({ embeds: [banReason] });
});
}
My problem with this is everytime I try to go and kick someone, I get my error:
if (!memberTarget.bannable) {
let lowPerms = new Discord.MessageEmbed()
.setDescription(
`<:role:887134365476335626> I lack the required permission to ban **${target.user.tag}**.`
)
.setColor("#000000");
message.reply({ embeds: [lowPerms] });
}
This happens even why I try to kick someone with no roles and my bot had administrative permissions.
The actual error itself:
C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142
if (typeof options !== 'object') throw new TypeError('INVALID_TYPE', 'options', 'object', true);
^
TypeError [INVALID_TYPE]: Supplied options is not an object.
at GuildBanManager.create (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildBanManager.js:142:44)
at GuildMemberManager.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\managers\GuildMemberManager.js:364:28)
at GuildMember.ban (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\structures\GuildMember.js:299:31)
at Object.execute (C:\Users\\Documents\GitHub\omex\commands\ban.js:32:22)
at Client.<anonymous> (C:\Users\\Documents\GitHub\omex\index.js:133:20)
at Client.emit (node:events:394:28)
at MessageCreateAction.handle (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\actions\MessageCreate.js:23:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketManager.js:345:31)
at WebSocketShard.onPacket (C:\Users\\Documents\GitHub\omex\node_modules\discord.js\src\client\websocket\WebSocketShard.js:443:22) {
[Symbol(code)]: 'INVALID_TYPE'
}
The error attached in question is originated via this specific line:
target.ban(reason)
The GuildMember#ban([options]) if needed to be called with options the options must be an array of options / object like so
target.ban({
reason: `${!reason ? "Unspecified" : `${reason}`}`
});
NodeJS is freaking out because I'm guessing the reason you passed into target.ban() is a string, not an object. In discord.js, you have to provide an object into the GuildMember#ban() method, like this:
target.ban({ reason });
You can also choose how many days (from 0-7) of messages to delete, like this:
target.ban({ days: 7, reason }); // Deletes all messages the member banned sent within the past 7 days

Discord.JS | AwaitReaction in DM

I don't want bots to join my server and advertise in chat or dm's of users, so I thought I'll let new users react to a message, and after that my bot will send them a question in dm's, if they answer correctly he should give them the verified role. The bot can send the message, but after that an error appears.
(node:12356) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'type' of undefined
I dont know how to solve this, because in the Docs channel.type exists.
Here is the code
client.on('messageReactionAdd', async (reaction, user) =>{
const filter = m => true
if (reaction.message.partials) await reaction.message.fetch();
if (reaction.partials) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.id === '814035246399488001'){
if (reaction.emoji.name === '✅'){
user.send("What is the subtrahend of 156 - 123?")
.catch(()=>{console.log('couldnt send a DM')})
if ( channel.type === 'dm' )
user.dmChannel.awaitMessages(filter, {
max:1,
time:30000,
error:["time"]
})
.then(collected => {
if (collected.first().content === "33"){
reaction.message.guild.members.cache.get(user.id).roles.add('779523805492019254')
if(err => {
console.log(err)
});
}else{
user.send("this is not the correct answer, you will not get verified.")
return;
}
})
}
}
});
I have asked around in some discord servers and found the solution:
if (reaction.emoji.name === '✅'){
let msg = await user.send("What is the subtrahend of 156 - 123?")
.catch(()=>{console.log('couldnt send a DM')})
if (msg.channel.type == `dm`)
What i think happens is, the bot now knows that msg.channel.type is the channel where he sent the message before, and yeah, i am so happy now that it works :3 and thank you too NullDev your comment lead to the solution too <3

How do i send a DM to a user using discord.js?

I've put a silly bot together that will join a voice channel when prompted and play a clip of Gordon Ramsay. The voice feature works great after some trial and error. Currently I'm trying to have it DM a list of the mp3's available to play but I'm running into an error. I think my if statement to DM the user is interacting with my logic to play a random mp3 in voice channel. I'm still quite new to this.
client.on('message', async message => {
if(message.member.voice.channel && message.content === `${prefix}list`) {
message.author.send('placeholder');
}
if (message.member.voice.channel && message.content === `${prefix}gordon`) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play(mp3[Math.floor(Math.random() * mp3.length)]);
dispatcher.on('start', () => {
console.log('Audio is now playing!\n Deleting command in chat.');
message.delete();
});
dispatcher.on('finish', () => {
console.log('Audio has finished playing!');
connection.disconnect();
});
dispatcher.on('error', console.error);
}});
It successfully sends the DM but it has errors.
```(node:14168) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'voice' of null
at Client.<anonymous> (c:\Users\Havok\Desktop\GordonBot\index.js:53:20)
at Client.emit (events.js:310:20)
at MessageCreateAction.handle (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:386:31)
at WebSocketShard.onPacket (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (c:\Users\Havok\Desktop\GordonBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (c:\Users\Havok\Desktop\GordonBot\node_modules\ws\lib\event-target.js:125:16)
at WebSocket.emit (events.js:310:20)
at Receiver.receiverOnMessage
(node:14168) 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:14168) [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.
When the bot receives a DM message, message.member will be null (because it can't be a guild member; it wasn't sent in a guild).
Check if the message was sent in a guild first before attempting use message.member.voice or playing music:
client.on('message', async message => {
if (!message.guild) return;
// rest of code...
})
dm user
message.user.send("msg");
client.on('message', async message => {
if(message.member.voice.channel && message.content === `${prefix}list`) {
messsge.user.send("Message");
}
})

Getting every channel in a guild

I'm trying to get every channel in a discord guild, but it gives me an error message.
if (message.content.startsWith('!get-channels')) {
message.guild.channels.forEach(channel => {
console.log(channel)
})
}
Here is the error message:
message.guild.channels.forEach(channel => {
^
TypeError: message.guild.channels.forEach is not a function
You are getting that error because since discord.js v12 you now need to access Guild Channels using their cache, so your solution would be to use message.guild.channels.cache.forEach()

Send is not a function discord.js

I am trying to send a message to channel but I keep getting Error: send is not a function.I have been stuck on this problem for over an hour.
What I have tried:
using sendMessage
tried reading the discord.js documentation but it doesnt seem to be working at all.
Here is my code:
//Grab the Discord Library
const Discord = require("discord.js");
//What will connect to the server.
const bot = new Discord.Client();
//
bot.on('ready', () => {
console.log("Connected as " + bot.user.tag)
//Shows and set the activity of the user.
bot.user.setActivity("El Professor build me", {type: "Watching"})
//Inform you of the servers this bot is connected to.
bot.guilds.forEach((guild) => {
console.log(guild.name)
guild.channels.forEach((channel) => {
console.log(` - ${channel.name} ${channel.type} ${channel.id}`)
})
//Voice Channel ID =
})
var generalChannel = bot.channels.get("123456789").send("Hello World")
})
Error message:
C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21
var generalChannel = bot.channels.get("123456789").send("Hello World")
^
TypeError: bot.channels.get(...).send is not a function
at Client.bot.on (C:\Users\F4_ALFA\documents\FirstDiscordBot\index.js:21:63)
at Client.emit (events.js:194:15)
at WebSocketConnection.triggerReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:125:17)
at WebSocketConnection.checkIfReady (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConn
ection.js:141:61)
at GuildCreateHandler.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\handlers\Gui
ldCreate.js:13:31)
at WebSocketPacketManager.handle (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\packets\WebSocke
tPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnecti
on.js:333:35)
at WebSocketConnection.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\discord.js\src\client\websocket\WebSocketConnect
ion.js:296:17)
at WebSocket.onMessage (C:\Users\F4_ALFA\documents\FirstDiscordBot\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:189:13)
Discord.js uses cache and your code has no '.cache', you should try
bot.channels.cache.get('id').send('Hello world!')
The channels property returns a Collection with pair of ID and Channel object.
The Channel class could represent any channel in discord. You couldn't send any messages through it because it doesn't have send() method.
I’ve used this before client.guilds.find(x => x.name === "ChatLogs").channels.find(y => y.name === "server-testing1").send(botEmbed) try that

Resources