Issue
As said in the title I have a problem when i need to export a schedule made with CronJob. The error I get is:
TypeError: Cannot read property 'send' of undefined
Inside of Cron.js
I have:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
const cron = require("cron")
const test = new cron.CronJob("00 00 13 * * 5", () =>{
client.channels.fetch("768752722743918614")
let testmsg = client.channels.cache.get("768752722743918614")
testmsg.send("test")
})
module.exports = test
Inside of bot.js
:
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
const cron = require("cron")
const test = require("./commands/autocode")
test.start()
That schedule works without problems inside bot.js
, but I don't want to make it untidy.
Solution
It seems client.channels.cache.get
returns undefined. I think you could just pass the client
down to your cron job to use the same client instance. You can return a function that returns the cron job you want to .start()
:
const cron = require("cron");
const test = (client) => new cron.CronJob("00 00 13 * * 5", () => {
client.channels.fetch("768752722743918614");
let testmsg = client.channels.cache.get("768752722743918614");
testmsg.send("test");
})
module.exports = test;
bot.js
const Discord = require('discord.js');
const fs = require("fs");
const client = new Discord.Client();
const { prefix, token } = require("../config.json");
const cron = require("cron");
const test = require("./commands/autocode")(client);
test.start();
Answered By - Zsolt Meszaros Answer Checked By - Marie Seifert (WPSolving Admin)