I made a discord bot called YES, and I have a text channel for images only, and I am trying to make it that if there is a text message the bot will delete it and reply "You cannot send text messages". I also made a whitelist for the bot because I want him to be able to send text messages.
client.on("message", async message => {
var usernames = ["YES"]
if (usernames.includes(message.author.username)) {
if (message.attachments.size > 0) {
message.delete();
client.channels.cache.get("841260660960395287").send(message.author.username + ", you cannot send text")
}
}
})
This doesn't work at all and it doesn't show any errors.
Your if statement if (message.attachments.size > 0) is checking, if the attachments collection's size is bigger than 0. So it will only execute the code in it, if the message has at least one attachment.
You can apply this:
if (message.attachments.size)
If the message has no attachments, the collection "attachments" should be empty, and in this case, you want to delete this message.¹
You should await the <message>.delete()> function, since it returns a promise:
await message.delete();
// Further code
OR²
message.delete()
.then(msg => console.log(`Deleted message from ${msg.author.username}`))
.catch(error => console.log(error))
You don't have to use all the '+' if you want to use variables inside a string. A simpler and way faster solution would be replacing ' with ` and then wrap your variable in ${}. In your code it would look like this:
client.channels.cache.get("841260660960395287").send(`${message.author.username}, you cannot send text`)
Your fixed code should now look like this:
client.on('message', async message => {
var usernames = ['YES'];
if (usernames.includes(message.author.username)) {
if (message.attachments.size) {
await message.delete();
client.channels.cache.get('841260660960395287').send(`${message.author.username}, you cannot send text`);
}
}
});
The issue here is with your if statement logic. It's checking if the message has more than one attachment, then deletes it. That's the issue, so by checking if the size of the collection is 0 (=== 0), your program will run successfully.