How to send message to every server bot is in discord.js?

by tressie.damore , in category: Javascript , 4 days ago

How to send message to every server bot is in discord.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 3 days ago

@tressie.damore 

To send a message to every server a bot is in using discord.js, you would need to iterate over each server (also known as guilds in Discord.js) that the bot is a member of and send a message to each one individually. Here is an example code snippet to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('ready', () => {
    // Loop through each guild the bot is a member of
    client.guilds.cache.forEach(guild => {
        // Find a text channel in the guild to send the message to
        const channel = guild.channels.cache.find(channel => channel.type === 'text');
        // Send a message to the channel
        if (channel) {
            channel.send('Hello from the bot!');
        }
    });
});

client.login('YOUR_BOT_TOKEN');


Replace 'YOUR_BOT_TOKEN' with the actual token of your Discord bot. This code snippet will send the message 'Hello from the bot!' to a text channel in every server (guild) the bot is a member of.