Cannot read property 'send' of underfined

陌路散爱 提交于 2020-11-30 00:22:12

问题


const mudaeon = require('./mudaetime.json');
const cron = require('cron');
const Discord = require('discord.js');
const client = new Discord.Client();

module.exports = {
 name: 'mudaetime',
 description: '...',
 execute(message, args) {
  if (mudaeon) {
   const channel = client.channels.cache.get('id');
   let scheduledMessage = new cron.CronJob(
    '* * * * *',
    () => {
     scheduledMessage.start();
    },
    message.react('✅'),
    channel.send('check $tu ! <@&id')
   );
  } else !mudaeon;
  {
   cancel();
  }
 },
};

Please help find the error in my code! I wanted to make a bot that sends a message in a specific channel every ten minutes (although in this case, I put it for every minute so I can see if it works)


回答1:


The problem is that you are creating a new Discord.Client() instance, which does not share the same channels, members, roles, etc. as the original. Instead of creating a new Discord.Client(), you should pass the original one as an argument to your execute() function.

For example, you could change async execute(message, args){ to async execute(message, args, client){. Then, in your command handler, change command.execute(message, args) to command.execute(message, args, client)

However, there is an even easier way. client is actually a valid property of the message object, referring to:

The client that instantiated the message

(Message#client docs)

So, instead of writing:

const channel = client.channels.cache.get('id');

You could write:

const channel = message.client.channels.cache.get('id')

And it will work perfectly!




回答2:


You should not use the cache to access the channels but the (async) .fetch method:


module.exports = {
    name: 'mudaetime',
    description: '...',
    async execute(message, args){
        if(mudaeon){
            const channel = await client.channels.fetch('222109930545610754')
            let scheduledMessage = new cron.CronJob("* * * * *", () => {
                scheduledMessage.start()},
                message.react('✅'),
                channel.send("check $tu ! <@&id"))
        } else(!mudaeon);{
            cancel();
        }
    }
}; 

This should work better, a lot of methods are async in discord.js so becareful to properly await the values when calling such methods :)

https://discord.js.org/#/docs/main/stable/class/ChannelManager?scrollTo=fetch



来源:https://stackoverflow.com/questions/63666855/cannot-read-property-send-of-underfined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!