Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete text messages in an image-only channel?

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.

like image 588
Uriyah Liberman Avatar asked Dec 09 '25 18:12

Uriyah Liberman


1 Answers

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.¹

Also

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))

Nice to know:

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`);
        }
    }
});    

References

  • ¹Expressions and operators
  • ².then()
like image 90
Toasty Avatar answered Dec 12 '25 07:12

Toasty



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!