Discord.js bot Cannot read property 'send' of undefined - javascript

I am trying to implement for my discord server and my discord bot a possibility to send a PM message to a lot of users.
I created something like this:
client.on("message", message => {
mentiondm = message.mentions.users.first();
mentionMessage = message.content.slice(22)
mentiondm.send(mentionMessage);
console.log('Message Sent!')
})
It's working for first mentioned user, message is sending but there are several problems:
after sending first message bot is crashing down with this error Cannot read property 'send' of undefined
I tried to change message.mentions.users to message.mentions.roles but then message is not sending.
There is a way to do my functionality better or at least upgrade this what I have here to working properly?

It's because it tries to get the first mentioned user from the bot's message too. Check if the message author is a bot and if it is, don't send the message.
Also, try to check if there is someone mentioned and if not, simply return.
client.on('message', (message) => {
if (message.author.bot) return;
let mentionDM = message.mentions.users.first();
if (!mentionDM)
return console.log('No mentioned user');
let mentionMessage = message.content.slice(22);
mentionDM.send(mentionMessage);
console.log('Message Sent!');
});

Related

Getting the channel name in discord.js

I'm trying to specify the channel my discord bot is posting in using the following code:
client.on("message", message => {
if message.content.includes("?chan") {
const channel = client.channels.cache.get('CHANNEL_ID_HERE')
console.log(channel)
channel.send("pong")
}
})
Upon sending the message "?chan", I want the discord bot to print whatever "channel" contains into the console, as well as send the message "pong" to the specified channel. It does neither of these things, and I'm not sure why. Also the rest of the code runs fine, including the parts with code from discord.js.

Check if a Discord.js DM went through

I know you can send a DM like this:
message.author.send("Go to example.com for help");
But some people have the setting that allows other server members to DM them off:
How do I find out if the DM actually sent or not? I know this is possible in the Discord API, since other bots do it.
If the user has that option, or isn't DMable, it will throw an error, namely:
DiscordAPIError: Cannot send messages to this user
Now, we can catch that error and run a command based on it, say replying in the channel that the user can't be DMed.
user.send(...).catch(async err => message.reply("I can't DM this user"));
// In the above, async is useless, but you can actually do what you want with it.
To run more than a single line of command, use a promise based catch.
user.send(...).catch(async err => {
console.log(err);
message.reply("I can't DM this user");
});
If a user has that option enabled, DMing them will return an error, so you'll be able to use a .catch() statement:
user.send().catch(() => console.log('Could not DM this user'));
You can get error notices aswell as information about the error using .catch()
In this example I log the error type and description
member.send(...).catch(error => {
console.error(`${error.name} :\n${error}`)
message.channel.send('There was an error when trying to DM this member')
})

discord.js Greeting message not sending

I was following the discord.js docs and when I tried to test the greeting thing the message didn't send. The channel is right, I even tried doing it with the channel ID (with different code), I also tried just sending a direct message. No error appears, the console is just empty and the message doesn't appear.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.cache.find(ch => ch.name === 'member-log');
if (!channel) return;
message.channel.send(`Welcome to the server, ${member}!`);
});
There is no need for "cache" in guildMemberAdd, that's why the channel was not found. The message variable was also not defined.
client.on('guildMemberAdd', member => {
const channel = member.guild.channels.find(ch => ch.name === 'member-log');
if (!channel) return;
channel.send(`Welcome to the server, ${member}!`);
});
I had this same exact problem and for me it wasn't a problem in the code itself, I just gave the bot every single permission on the category of the welcome channel as well as the welcome channel itself.
It could also be that you have something else as the const name instead of 'client'.

How to fix "Cannot read property 'first' of null" in javascript, discord bot making

So I was developing Discord Bot for my customer and he wanted from me to make a bot that could send an events in his members DMs. I've made the code. Bot executes the function and does send DM to all the members. However, bot stops due an error "Cannot read property 'first' of null".
I tried a lot of things, such as catching console errors etc. But I still do not understand why does my bot stops and writes that console error after me adding that DM code. Console recognize some kind of problem at a line of code that has no actual connections with the Private Message command. It is not even under the same 'bot.on' ... Here is the problem:
if (msg.guild && msg.content.startsWith('!private')) {
let text = msg.content.slice('!private'.length);
msg.guild.members.forEach(member => {
if (member.id != bot.user.id && !member.user.bot) member.send(text).catch(err => {
message.reply('I was unable to kick the member');
console.log(err);
});
})
}
});
**//This right here is a code that can execute the function i wanted to make.^**
bot.on('message', message=> {
const member = message.mentions.members.first(); // <-- **Console says this property'first' cannot be read (Cannot read property 'first' of null)**
let args = message.content.substring(PREFIX.length).split(" ");
const user = message.mentions.users.first();
switch(args[0]) {
case 'ping':
message.channel.sendMessage('pong!');
break;
//**Above is a part of the code that has a console error after I added the first code above. Before I added first code there was no such errors and everything worked perfectly.**
I expected Bot to execute function and send everyone in the server private message (Event) and continue working.
But instead it executes the function sending everyone desired message but the bot stops as it has an console error.

Cant edit messages with discord bot (UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot edit a message authored by another user)

Ive got my bot running with some new code but it cant edit any messages using message.edit() throws a DiscordAPIError Any help would be appreciated.
Heres my code for my super simple bot
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === 'lenny') {
message.edit('( ͡° ͜ʖ ͡°)');
}
});
client.login('Censored to protect identity');
This is the console output whenever someone says 'lenny' in a text channel.
(node:6672) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot edit a message authored by another user
at C:\Users\Terra Byte\node_modules\discord.js\src\client\rest\RequestHandlers\Sequential.js:85:15
at C:\Users\Terra Byte\node_modules\snekfetch\src\index.js:215:21
at processTicksAndRejections (internal/process/task_queues.js:89:5)
(node:6672) 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: 6)
I have tried giving the role administrator on the server, but it still throws the same DiscordAPIError error.
The reason that error is being thrown is because your trying to edit another users message.
client.on('message', message => {
if (message.content === 'lenny') {
message.edit('( ͡° ͜ʖ ͡°)'); // <-- Here you are editing another users message.
}
});
The message you are trying to edit belongs to the person who authored the message, and you cannot edit other users messages.
As you stated above, you wanted it to delete the message, so I'll implement that below.
client.on('message', message => {
if (message.content === 'lenny') {
message.delete() //This is the original message that triggered the message event.
message.channel.send("( ͡° ͜ʖ ͡°)") //Send a lenny face in response to the user saying "lenny"
}
});
You don't need to search for it, just use the definition of message in your message event.
As an alternative option to what you're asking for but can't do, you can have the bot post a new message when someone posts "!lenny", through message.channel.send(). Or you can make it even easier and create a custom Emoji for your server that shows a lenny face in the place of :lenny:, something like this: https://discordemoji.com/emoji/Lenny
Messages from other users can not be edited in discord at all, even/especially using the API.

Categories

Resources