1

I'm new to writing discord.js and first I don't know if this is a stupid question, but the question is I want to make a bot so that the first section is greeting:

//greetings
const random_greeting = () =>{
    return Math.floor(Math.random() * 5);
  }
  
  client.on('messageCreate', msg=>{
    if(msg.author == client.user) return;
    let greeting = ['Hi', 'Yo', 'Hello', '', 'Ok...',]
    if (msg.content === 'hi'){
      msg.reply(greeting[random_greeting()])}
    if (msg.content === 'hello'){
      msg.reply(greeting[random_greeting()])}
    if (msg.content === 'yo'){
      msg.reply(greeting[random_greeting()])}
    if (msg.content === 'sup'){
      msg.reply(greeting[random_greeting()])}
    if (msg.content === 'wassup'){
      msg.reply(greeting[random_greeting()])}
    if (msg.content === 'yo'){
      msg.reply(greeting[random_greeting()])}
  })

As you can see i need to write:

if (msg.content === 'hello'){
      msg.reply(greeting[random_greeting()])}

and keep spamming it like 6 times, so my question is there any way to do this short or faster?

I have tried something like adding greetinganswer variable:

let greetingAns = ['hi', 'hello']

but when i used

const random_greeting = () =>{
    return Math.floor(Math.random() * 5);
  }

  client.on('messageCreate', msg=>{
    if(msg.author == client.user) return;
    let greeting = ['Hi', 'Yo', 'Hello', '', 'Ok...',]
    let greetingAns = ['hi', 'hello']
    if (msg.content === greetingAns()){
      msg.reply(greeting[random_greeting()])}

I think it should work but it doesn't. So is msg.content === a variable?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
  • Does this answer your question? [How do I check if an array includes a value in JavaScript?](https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-a-value-in-javascript) – MrMythical Jan 25 '22 at 12:44

1 Answers1

2

Yes, you can do that and you will need to use an array of strings as you already did. So to check if the message content is found in the array it will be needed the includes() javascript method.

Like this:

if (greetingAns.includes(msg.content)) {
    msg.reply(greeting[random_greeting()]);
}
spect423
  • 215
  • 3
  • 8