简体   繁体   中英

How to a send message in a channel when the bot is ready?

I was trying to modify the "ping pong" sample code in discord.js.
Instead of logging in the console, I wanted to send a message in a specific channel in Discord. I have tried using the code below to do it but it keeps showing me this error:

(node:10192) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'channels' of undefined
    at Client.<anonymous> (D:\GAMES\DiscordBot\index.js:7:12)

This is the code I'm using:

const Discord = require('discord.js');
const client = new Discord.Client();

console.log(client);

client.on('ready', client => {
  client.channels.get('787667808777998851').send('Hello here!');
});

client.on('message', msg => {
  if (msg.content === 'ping') {
    msg.reply('pong');
  }
});

client.login('auth-token');

Simple mistake! You are declaring an new client variable which is undefined since the ready event doesn't callback with any values. Also .get isn't a function. What you're looking for is .fetch and this function returns a promise that resolves to a channel. Here is your new ready event.

client.on('ready', () => {
    client.channels.fetch('787667808777998851')
    .then(channel => {
        channel.send("Hello here!");
    })
});

Also, try not to post your bot token in your question. It's very dangerous and gives anyone access to your bot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM