Home > other >  How can I send a random message everyday from an array at a specific hour on discord.js?
How can I send a random message everyday from an array at a specific hour on discord.js?

Time:03-23

I'm trying to make a bot that will send a random message from an array using cron.

Here is my code:

const cron = require('cron');

module.exports = {
    name: 'pesanrandom',
    description: "random message every day",
    execute(message, args, cmd, client, Discord){
      let scheduledMessage = new cron.CronJob('00 54 16 * * *', () => {
        //
        var listPesan = [
          'Met siang guys, dah pada mam siang blum?',
          'Siapa yang tadi pagi mimpiin cowo atau cewe kpopnya',
          'Siang-siang enaknya...',
          'Dor kaget ga',
          'Laper dah',
        ];

        var pesanRandom = listPesan[Math.floor(Math.random() * listPesan.length)];

        const pesanEmbed = new Discord.MessageEmbed()
              .setColor('#50C878')
              .setTitle('vermillion#3039')
              .setDescription(pesanRandom)
              .setFooter('© Vermillion')

        client.channels.cache.get('927589065925214239').send(pesanEmbed);
        //
      });

      scheduledMessage.start()
    }
}

I already try the code and it works but it can only randomize the message one time. How to make it randomize the message everytime the message is sent?

CodePudding user response:

So the easiest way to do this requires two files. One file we are going to call listPesan.json and in that file we will have this text:

[
    "Met siang guys, dah pada mam siang blum?",
    "Siapa yang tadi pagi mimpiin cowo atau cewe kpopnya",
    "Siang-siang enaknya...",
    "Dor kaget ga",
    "Laper dah"
]

The second file is your main.js bot file and somewhere (doesn't matter where so long as it is not under an event (.on('messageCreate'), .on('guildMemberAdd'), etc.)

This stands alone all by itself (you can put your const stuff together if you want) and we are going to use node-cron, it's "better" supposedly, idk, I've just always used it.

const cron = require('node-cron')
const listPesan = require('./listPesan.json') // or where ever you put the file we just made above

cron.schedule('00 54 16 * * *', () => {

const pesanRandom = listPesan[Math.floor(Math.random() * listPesan.length)]

const pesanEmbed = new Discord.MessageEmbed()
    .setColor('#50c878')
    .setTitle('vermillion#3039')
    .setDescription(pesanRandom)
    .setFooter('© Vermillion')
    
    
    // if using discord v12
    client.channels.cache.get('927589065925214239').send(pesanEmbed)
    
    // if using discord v13
    client.channels.cache.get('927589065925214239').send({
        embeds: [pesanEmbed]
    })
}
  • Related