'I want my discord bot to send a random message to a text room given by user [by channel id or channel name]

so what I am trying to do is when a user write a command such as

!setchannel #test or !setchannel 86xxxxxxxxxxxxxxx

then the bot will send the random messages to that channel every certain time.

Note that I did the random messages code but I still stuck on creating the !setchannel command.

I am using discord.js v12.5.3


index.js main file

require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
require('discord-buttons')(client);
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const { permission, permissionError } = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')
const logo =
  'URL HERE'


const db = require(`quick.db`)
let cid;
const { prefix } = config



client.on('ready', async () => {

  await mongo().then((mongoose) => {
    try {
      console.log('Connected to mongo!')
    } finally {
      mongoose.connection.close()
    }
  })
  console.log(`${client.user.tag} is online`);
  console.log(`${client.guilds.cache.size} Servers`);
  console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);





  loadCommands(client)
  cid = db.get(`${message.guild.id}_channel_`)


 
  cron.schedule('*/10 * * * * *', () => {
    const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
    const zkrEmbed = new Discord.MessageEmbed()


      .setDescription(zkrRandom)
      .setAuthor('xx', logo)
      .setColor('#447a88')




    client.channels.cache.get(cid).send(zkrEmbed);
  })

  client.on("message", async message => {




    if (message.author.bot) {
      return
    }
    try {if (!message.member.hasPermission('ADMINISTRATOR') && message.content.startsWith('!s')) return message.reply('you do not have the required permission') } catch (err) {console.log(err)}
    if (!message.content.startsWith(prefix)) return;


    const args = message.content.slice(prefix.length).trim().split(/ +/g)
    const cmd = args[0]
    if (cmd === "s") {
      let c_id = args[1]
      if (!c_id) return message.reply("you need to mention the text channel")
      c_id = c_id.replace(/[<#>]/g, '')
      const channelObject = message.guild.channels.cache.get(c_id);

      


      if (client.channels.cache.get(c_id) === client.channels.cache.get(cid)) return message.reply(`we already sending to the mentioned text channel`);
      if (client.channels.cache.get(c_id)) {


       
        await db.set(`${message.guild.id}_channel_`, c_id); //Set in the database
        console.log(db.set(`${message.guild.id}_channel_`))

        message.reply(`sending to ${message.guild.channels.cache.get(c_id)}`);
        cid = db.get(`${message.guild.id}_channel_`)



        const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
        const zkrEmbed = new Discord.MessageEmbed()


          .setDescription(zkrRandom)
          .setAuthor('xx', logo)
          .setColor('#447a88')




        client.channels.cache.get(cid).send(zkrEmbed);



      } else {
        return message.reply("Error")
      }


    }
  })
})




client.login(config.token)

zkr.json json file

[
   "message 1",
   "message 2",
   "message 3"

]


Solution 1:[1]

You'll have to use a database to achieve what you're trying to do

An example using quick.db

const db = require(`quick.db`)
const prefix = "!"
client.on("message", async message => {
    if (!message.content.startsWith(prefix)) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/g)
    const cmd = args[0]
    if (cmd === "setchannel") {
        let c_id = args[1]
        if (!c_id) return message.reply("You need to mention a channel/provide id")
        c_id = c_id.replace(/[<#>]/g, '')
        if (client.channels.cache.get(c_id)) {
            await db.set(`_channel_`, c_id) //Set in the database
        } else {
            return message.reply("Not a valid channel")
        }


    }
})

Changes to make in your code

client.on('ready', async () => {
       let c_id = await db.get(`_channel_`)
        
        cron.schedule('*/10 * * * * *', () => {
        const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
        const zkrEmbed = new Discord.MessageEmbed()
        
              .setTitle('xx')
              .setDescription(zkrRandom)
              .setFooter("xx")
              .setColor('#447a88')
              .setAuthor('xx#8752')
        
        
            
            client.channels.cache.get(c_id).send(zkrEmbed)
          })
        })

The above sample of quick.db is just an example

If you're using repl.it, I recommend you to use quickreplit

Edit

require('events').EventEmitter.prototype._maxListeners = 30;
const Discord = require('discord.js')
const client = new Discord.Client()
const ytdl = require('ytdl-core');
const config = require('./config.json')
const mongo = require('./mongo')
const command = require('./command')
const loadCommands = require('./commands/load-commands')
const commandBase = require('./commands/command-base')
const cron = require('node-cron')
const zkrList = require('./zkr.json')

const db = require(`quick.db`)
const prefix = "!"
let cid;
client.on('ready', async () => {
    await mongo().then((mongoose) => {
      try {
        console.log('Connected to mongo!')
      } finally {
        mongoose.connection.close()
      }
    })
    console.log(`${client.user.tag} is online`);
    console.log(`${client.guilds.cache.size} Servers`);
    console.log(`Server Names:\n[ ${client.guilds.cache.map(g => g.name).join(", \n ")} ]`);    
    
    
    cid = db.get('_channel_')
   
    loadCommands(client)
    //commandBase.listen(client);
   
  })

   
   
  cron.schedule('*/10 * * * * *', () => {
    const zkrRandom = zkrList[Math.floor(Math.random() * zkrList.length)]
    const zkrEmbed = new Discord.MessageEmbed()
 
      .setTitle('xx')
      .setDescription(zkrRandom)
      .setFooter("xx")
      .setColor('#447a88')
      .setAuthor('xx#8752')
 
 
 
     client.channels.cache.get(cid).send(zkrEmbed);
  })
   
  client.on("message", async message => {
     
    console.log(db.get('_channel_'))
    if (!message.content.startsWith(prefix)) return;
    const args = message.content.slice(prefix.length).trim().split(/ +/g)
    const cmd = args[0]
    if (cmd === "s") {
      let c_id = args[1]
      if (!c_id) return message.reply("You need to mention a channel/provide id")
      c_id = c_id.replace(/[<#>]/g, '')
      if (client.channels.cache.get(c_id)) {
        console.log('old channel')
        console.log(db.get('_channel_'))
        
        await db.set(`_channel_`, c_id); //Set in the database
 
        message.reply(`sending in this channel ${message.guild.channels.cache.get(c_id)}`);
 
       
      } else {
        return message.reply("Not a valid channel")
      }
 
 
    }
  })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1