Sagar Dhawan
Sagar Dhawan

Reputation: 47

Discord.js Send message to a specific channel using a bot

I have been trying to send message to a specific channel using the discord bot and i have tried a lot of online examples that are present online but none of them works and gives the same error everytime.
The following is the code implementation:

client.on('ready', () => {
  console.log('Bot is now connected')
  try {
    client.channels.find('test').send("Hello there!");
  } catch (e) {
    console.log('[ERROR:]',e);
  }
});

But everytime the same error message appears:

[ERROR:] TypeError: client.channels.find is not a function
    at Client.client.on (/Users/Kartikeya 1/discordBot/index.js:9:34)
    at Client.emit (events.js:198:13)
    at WebSocketManager.triggerClientReady (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:433:17)
    at WebSocketManager.checkShardsReady (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:417:10)
    at WebSocketShard.shard.on.unavailableGuilds (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketManager.js:199:14)
    at WebSocketShard.emit (events.js:198:13)
    at WebSocketShard.checkReady (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:466:12)
    at WebSocketShard.onPacket (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:438:16)
    at WebSocketShard.onMessage (/Users/Kartikeya 1/discordBot/node_modules/discord.js/src/client/websocket/WebSocketShard.js:293:10)
    at WebSocket.onMessage (/Users/Kartikeya 1/discordBot/node_modules/ws/lib/event-target.js:120:16)

Could anyone please let me know what step is missing or not handled.
I am using the following node version : v10.16.3

Upvotes: 1

Views: 5247

Answers (1)

Cipher
Cipher

Reputation: 2722

Discord channels have many parameters, so you need to specify what the test parameter is.

I recommend that you never search for channels by name, it's better to use ID. Like

client.channels.get('ID') or client.channels.cache.get('ID')

    client.on('ready', () => {
      console.log('Bot is now connected')
        client.channels.find(channel => channel.name === 'test').send("Hello there!"); // for discord v11
        client.channels.cache.find(channel => channel.name === 'test').send("Hello there!"); // for discord v12
    });

You can use npm list discord.js for check your discord.js version

For list of channels

let channelsList = ['ID1', 'ID2', 'ID3']
channelsList.forEach(channel => {
    let targetChannel = client.channels.get(channel)
    if (targetChannel) {
        targetChannel.send('TEXT').then(() => {
            console.log(`succes send message to channel ${targetChannel.name}`)
        }).catch(err => console.error)
    }
})

Upvotes: 1

Related Questions