2
votes

Every time a message is sent in a specific channel, I want to print it to the console (with console.log). I am also going to color it with npm install colors. I go everywhere, even on Stack Overflow, but I cannot seem to find any information. I am coding a Scholastic Bowl-helping bot. Below is the code I have tried (I found this on Stack Overflow.)

message.fetch({ limit: 1 }).then(messages => {
  let lastMessage = message.first();
    if (message.channel.lastMessage = 'channel-id'){
      console.log(lastMessage.red);
  }
}) 

(Note that when I say 'channel-id' I mean the actual ID of the channel.)

The error I am getting is that message.first is not a thing.

How do I fix this error, and how can I get the most recent message in discord.js?

Edit: The exact error I got is this:

(node:12352) UnhandledPromiseRejectionWarning: TypeError: messages.first is not a function
    at C:\Users\[user redacted]\Desktop\SchoBot\index.js:57:32
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:12352) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12352) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Below is the edit for the 3rd comment on this question (sorted by oldest):

  message.channel.fetch({ limit: 1 }).then(messages => {
    let lastMessage = message.channel.first();
      if (message.channel.lastMessage = 'channel-id'){
        console.log(lastMessage.red);
    }
})
2

2 Answers

1
votes

Use message.channel.messages.fetch() instead of message.channel.fetch().

I didn't find the message.first function in the discord.js documentation, so I am not sure if it works. But you don't really need that function to fetch a message. The fetch function already did that for you.

In your case, the option limit: 1 will only return the most recent message, which is the command you use to trigger the fetch. If you want to fetch the most recent message but not your command, you should use limit: 2 instead and remove your command in the object later. The fetch function will return an object containing message id and the content.

0
votes

I assume that message.fetch needs to be message.channel.fetch