Cristian Muscalu
Cristian Muscalu

Reputation: 9895

How to send a message to a channel

I've spent 3 hours building and tweaking a Node.js web scraper and over 4 hours trying to find a freaking way to broadcast a message to a channel on Discord. I have lost all hope at this time...

This is the code I have, and some parts work, like replying to a message. But I can't find any possible way to just send a message, without that message being a reply.

const discord = require('discord.js');
const bot = new discord.Client();
const cfg = require('./config.json')

bot.on('ready', () => {//this works
  console.log(`Logged in as ${bot.user.tag}(${bot.user.id}) on ${bot.guilds.size} servers`)
});

bot.on('message', (msg) => {
  switch (msg.content) {
    case '/epicinfo':
      msg.channel.send('w00t'); //this works
  }
});

console.log(bot.users.get("id", "504658757419270144")) //undefined
console.log(bot.channels.get("name", "testbot")) //undefined
console.log(bot.users.find("id", "504658757419270144")) //undefined
console.log(bot.channels.find("name", "testbot")) //undefined
console.log(bot.guilds.get("504658757419270144")); //undefined
console.log(bot.channels.get(504658757419270144)) //undefined
bot.send((discord.Object(id = '504658757419270144'), 'Hello')) //discord.Object is not a function

bot.login(cfg.token);

Upvotes: 1

Views: 186

Answers (2)

Max
Max

Reputation: 170

Try:

bot.channels.find(channel => channel.id === '504658757419270144').send('Your-message');

also, if the channel you are trying to send the message to is in the bots guild, you can use:

bot.on('message' (msg) => {
    msg.guild.channels.find(channel => channel.name === 'your-channel-name').send('your-message');
});

Upvotes: 0

Federico Grandi
Federico Grandi

Reputation: 6816

That might be caused by the fact that you're running your code before the bot is logged in.
Every action has to be made after the bot has emitted the ready event, the only thing you can do outside the ready event is defining other event listeners.

Try putting that part of your code inside the ready event listener, or inside a function called by that event:

client.on('ready', () => {
  console.log("Your stuff...");
});

// OR

function partA () {...}
function partB () {...}
client.on('ready', () => {
  partA();
  console.log("Your stuff...");
  partB();
});

// OR

function load() {...}
client.on('ready', load);

In your situation:

client.on('ready', () => { // once the client is ready...
  let guild = client.guilds.get('guild id here'); // ...get the guild.
  if (!guild) throw new Error("The guild does not exist.");  // if the guild doesn't exist, exit.

  let channel = guild.channels.get('channel id here'); // if it does, get the channel
  if (!channel) throw new Error("That channel does not exist in this guild."); // if it doesn't exist, exit.

  channel.send("Your message here.") // if it does, send the message.
});

client.login('your token here')

Upvotes: 1

Related Questions