Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

javascript - Discord.js. CronJob not working with command handling

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.

question from:https://stackoverflow.com/questions/66055975/discord-js-cronjob-not-working-with-command-handling

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...