Reputation: 47
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?
Upvotes: 0
Views: 284
Reputation: 23189
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);
}
},
};
Upvotes: 1