Delete the latest message of the bot in dms - javascript

I have a command where the bot sends a message to a specific user trough private messages. Now I want that I can delete the last message of the bot in DMs when there is like an error or something.
What I come up with is this:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
execute(message, args) {
const mentionedMember = message.mentions.members.first().id
const User = client.users.fetch(mentionedMember)
try {
if (!mentionedMember) {
return respond('', 'Bitte erwähne einen Nutzer.', message.channel)
}
User.dmChannel.messages.fetch( {limit: 1} )
.then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete()
});
} catch (error) {
console.error('an error has occured', error);
}
}
}
The error that I'm getting now is:
TypeError: Cannot read property 'messages' of undefined
And yes, I have direct messages with the bot.
Anyone knows what I did wrong?

There are a couple of errors. First, users.fetch and dmChannel.messages.fetch both return a promise, so you'll need for them to be resolved.
In your code above, User is a pending Promise that has no dmChannel property. As it has no dmChannel prop (i.e. it's undefined), you can't read its messages property and you will receive TypeError: Cannot read property 'messages' of undefined.
After you fixed these problems with fetch, there could be another error with the dmChannel. Sometimes (or most of the times?), user.dmChannel returns null. To avoid this, you can create a DM channel first using the createDM() method. It also returns a promise, so you will need to resolve it first :)
Check out the working code below:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
async execute(message, args) {
const mentionedUser = message.mentions.users.first();
if (!mentionedUser)
return respond('', 'Bitte erwähne einen Nutzer.', message.channel);
const user = await client.users.fetch(mentionedUser.id);
const dmChannel = user.dmChannel || (await user.createDM());
try {
const messages = await dmChannel.messages.fetch({ limit: 1 });
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete();
} catch (error) {
console.error('an error has occured', error);
}
},
};

Related

Discord.js error : TypeError: Cannot read properties of undefined (reading 'options')

I have this code to unban someone using id (btw if you know how to unban by "ping" a user that is ban I will like to know how to do that). I have an issue with the id that could be a letter and my code was crashing so I try to fix it but know the problem is that the option are undefined.
Here is my code :
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { SnowflakeUtil } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('unban')
.setDescription('Send an id of a discord member and unban them.')
.addStringOption(option =>
option
.setName('target')
.setDescription('The id of the member to unban')
.setRequired(true))
.addStringOption(option =>
option
.setName('reason')
.setDescription('The reason for unbanning'))
.setDefaultMemberPermissions(PermissionFlagsBits.BanMembers)
.setDMPermission(false),
async execute(client, interaction) {
const target = interaction.options.get('target');
if (!target) return interaction.reply({ content: "The 'target' option is missing.", ephemeral: true });
if (!SnowflakeUtil.deconstruct(target).valid) {
return interaction.reply({ content: "The target id is not a valid id.", ephemeral: true });
}
const reason = interaction.options.get('reason') || 'No reason provided';
const user = await client.users.fetch(target);
if (!user) return interaction.reply({ content: "I could not find this user.", ephemeral: true });
await interaction.reply(`Unbanning ${user.tag} for reason: ${reason}`);
await interaction.guild.members.unban(user.id);
},
};
The error is :
TypeError: Cannot read properties of undefined (reading 'options')
It is suppose to unban a user of the discord server.
Parameters is probably execute(interaction, client).
This means you need to change parameters in your command to async execute(interaction, client)
or you can leave it as it is and write interaction where you write client and client where you write interaction. The most appropriate solution would be the first thing I said.

Does fetching embeds through messages from msg.reference.messageID not work?

I am coding a discord bot, and I am trying to get the content of embeds through the command user replying to the message and using a prefix. When I try running the command, it says that fetchedMsg.embeds[0] isn't a thing. Is there anything wrong with my code?
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
The error is on the line console.log(fetchedMsg.embeds[0]), and looking at the log from the code before it includes embeds: [ [MessageEmbed] ],.
The error reads TypeError: Cannot read properties of undefined (reading '0'), and when I remove the [0], it's undefined. This whole thing is in a module.exports.run, if that helps.
module.exports.run = async (client, msg, args) => {
const { MessageActionRow, MessageButton, MessageEmbed } = require('discord.js');
if (args.length === 5) {
if (msg.reference) {
const fetchedMsg = await msg.channel.messages.fetch(await msg.reference.messageID)
console.log(fetchedMsg)
console.log(fetchedMsg.embeds[0])
}
//do things with fetchedMsg
You can get the MessageEmbed() same as normal Message using:
const messages = args[0]
if(!messages) return message.reply("Provide an ID for message.")
if(isNaN(messages)) return message.reply("Message ID should be
number, not a letter")
message.channel.messages.fetch(`${messages}`)
.then(msg => {
console.log(msg.content) || console.log(msg.embeds)
})
You can find more here about fetching a message

Discord bot failing to call username of person who calls it

I'm trying to make my bot say a simple message whenever someone tells it 'hello'. Currently, the code of the command itself looks like this:
const { SlashCommandBuilder } = require('#discordjs/builders');
const greeter = "default";
const greetOptions = [
`Hello, ${greeter}. It's very nice to hear from you today.`
]
module.exports = {
data: new SlashCommandBuilder()
.setName('hello')
.setDescription('say hi to Hal!'),
execute(message, args) {
let greeter = message.user.username;
msg.channel.send(greetOptions[Math.floor(Math.random() * greetOptions.length)]);
},
};
The code I am using to manage when commands are typed looks as follows:
let prefix = "hal, ";
client.on('messageCreate', message => {
if (!message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length);
const command = args.toLowerCase();
console.log(`${message.author.tag} called ${command}`);
if (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.channel.send({ content: 'There was an error while executing this command!', ephemeral: true });
}
});
When I run it, it throws the error, "Cannot read properties of undefined (reading 'username').
If You want to mention a user you can do ${message.author}. But if you want to say for ex. Hello, Brandon then you need to do ${message.author.username}. The message ${message.author.tag} does not always function and also I recommend you const user = message.mentions.users.first() || message.author or just const user = message.author for short so then you can do ${user.username}. Maybe this might fix the bot failing to respond otherwise if it doesn't tell me.
Fix the first code and change msg.channel.send to message.channel.send.

Temporary mute command returning error 'Cannot read property 'slice' of undefined'

I am trying to create a temporary mute command, that will unmute the muted user in the given time.
Here's my code:
const Discord = require("discord.js");
const ms = require("ms");
module.exports = {
name: 'mute',
description: 'mute a specific user',
usage: '[tagged user] [mute time]',
async execute(message, embed, args) {
let tomute = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[0]));
if (!tomute) return message.reply("Couldn't find user.");
const reason = args.slice(1).join(' ');
if (tomute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them!");
const muterole = message.guild.roles.cache.find(muterole => muterole.name === "muted");
if (!muterole) {
try {
muterole = await message.guild.roles.create({
name: "muted",
color: "#000000",
permissions: []
})
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.overwritePermissions(muterole, {
SEND_MESSAGES: false,
ADD_REACTIONS: false
});
});
} catch (e) {
console.log(e.stack);
}
}
const mutetime = args.slice(2).join(' ');
//here is the start of the error
await (tomute.roles.add(muterole.id));
message.reply(`<#${tomute.id}> has been muted for ${ms(ms(mutetime))} `);
setTimeout(function() {
tomute.roles.remove(muterole.id);
message.channel.send(`<#${tomute.id}> has been unmuted!`);
}, ms(mutetime));
}
}
Currently getting the following error: Cannot read property 'slice' of undefined
Do you have any idea on how to fix the command?
edit
this after a year and this is for future people who come here
the issue was here
async execute(message, embed, args) {
i never passed embed from my main file so args was undefined
embed part was where the args should have been, I was stupid at that time and was new to coding, but as I now have some experience, I decided to edit this to show what wrong
It means that somewhere in your code, you have a value which is undefined and you try to use the string/array function slice on it but undefined does not have this function : so it is a error.

discord.js UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined

Yesterday I could run this scrip.
Today I get the error
(node:29568) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'kickable' of undefined
I'm running version "discord.js": 12.1.1 - I hope someone can spot what I'm doing wrong here... because it's drive me nuts.
Bellow you can find my kickuser.js - script
+ my index.js script -> https://pastebin.com/7tLkuU5p
const Discord = require("discord.js");
module.exports.run = async (bot, message, args) => {
if (message.member.hasPermission("KICK_MEMBERS")) {
if (!message.mentions.users) return message.reply('You must tag 1 user.');
else {
const channel = message.guild.channels.cache.get(696692048543088691);
const member = message.mentions.members.first();
let reason = message.content.split(" ").slice(2).join(' ');
if (member.kickable == false) return message.channel.send("That user cannot be kicked!")
else {
if (!reason) reason = (`No reason provided.`);
await member.send(`You have been kicked from **${message.guild.name}** with the reason: **${reason}**`)
.catch(err => message.channel.send(`⚠ Unable to contact **${member}**.`));
await member.kick(reason);
const kickEmbed = new MessageEmbed()
.setAuthor(member.user.tag, member.user())
.setThumbnail(member.user.avatarURL())
.setColor("#ee0000")
.setTimestamp()
.addField("Kicked By", message.author.tag)
.addField("Reason", reason);
await channel.send(kickEmbed);
console.log(`${message.author.tag} kicked ${member.user.tag} from '${message.guild.name}' with the reason: '${reason}'.`);
}
}
} else {
message.channel.send("You do not have permission to use kick.");
return;
}
}
module.exports.help = {
name: "kickuser"
}
I hope someone can help me.
Thanks in advance.
message.mentions.users always evaluates to true because it is an object, and to check if the message has any mentions, you can do:
if(!message.mentions.members.first()) return message.reply('You must tag 1 user.');
instead of:
if(!message.mentions.users) ...

Categories

Resources