简体   繁体   中英

Checking message length with Discord.js

I am trying to determine the length of a message in a channel. I can't find what to put for the message length, I tried this on a channel that isn't mine, and it didn't seem to work, no error code were thrown, it just doesn't work.


This is my code so far:

const Discord = require('discord.js')
const bot = new Discord.Client()

bot.on('ready', () => {
  console.log("connected");
});

bot.on('message', (message) => {
  if(message.channel.id === '549389103071969869') {
    if(message.length !== '4') {
      message.delete()
    }
  }
});

The message parameter is the entire message object. For example, message.author , message.id , etc.

What you are looking for is message.content , the actual text in the message.

Also, make sure the number you're comparing the length property to is a Number , not a String as it is now.

if (message.content.length !== 4) { // 4, not "4"

截屏

What you want to do is use message.content.length . message.length will return undefined as .length doesn't work on an object property.


在此处输入图片说明


What you want to use is message.content.length to find the length of message.content .


在此处输入图片说明


在此处输入图片说明


As you can see in the first picture, it returned undefined . And then in the second picture, it shows the content of the message, which is what we wanted, and lastly the third one (for eval purposes i used message.channel.messages.cache.get() to get the exact message in the second picture) is the message content's length.


For your code, the answer will be as such:

const Discord = require('discord.js')
const bot = new Discord.Client()

bot.on('ready', () => {
  console.log("connected");
});

bot.on('message', (message) => {
  if(message.channel.id === '549389103071969869') {
    
    // Use `message.content.length`
    if(message.content.length !== 4) {
    // Do mind that '4' is a string, and what you want is the length (a number), so you shouldn't put quotes around it.

      // If the message length isn't 4, then delete it.
      message.delete()
    }
  }
});

For more information, visit the links below:

These are the docs on how I used message.channel.messages.cache.get() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM