Sending a message into all servers where bot is - node.js

How do I send one message per guild that my bot is in? It doesn't matter which channel it will be, but I don't know how to code it.
I finally came up with that idea:
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
but it doesn't work.
I'm working with commands handler so it has to be done with module.exports:
module.exports = {
name: "informacja",
aliases: [],
description: "informacja",
async execute(message) {
client.guilds.cache.forEach(guild => {
const Embed = new discord.MessageEmbed();
const Channels = guild.channels.cache.map(channel => `${channel.id} | ${channel.name}`).join(", ")
Embed.setTitle(`Channels for ${guild.name}`);
Embed.setDescription(Channels);
message.channel.send(Embed);
});
};
My code is not working at all
When I run it - nothing happens, no errors, no messages, just nothing.
tried to logged everything, but still nothing came up.
I also tried to log everything using console.log() but nothing is working
I remind: I need to send one message to all servers where my bot is, but only one channel

You could find a channel on each server where the client can send a message then send:
client.guilds.cache.forEach(guild => {
const channel = guild.channels.cache.find(c => c.type === 'text' && c.permissionFor(client.user.id).has('SEND_MESSAGES'))
if(channel) channel.send('MSG')
.then(() => console.log('Sent on ' + channel.name))
.catch(console.error)
else console.log('On guild ' + guild.name + ' I could not find a channel where I can type.')
})

This is a very simple boilerplate to start with, you can later check channel with id, or smth like that
client.channels.cache.forEach(channel => {
if(channel.type === 'text') channel.send('MSG').then('sent').catch(console.error)
})

v13 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "GUILD_TEXT" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}
v12 code
const Discord = require('discord.js')
const {
MessageEmbed
} = require('discord.js')
const fs = require('fs')
module.exports = {
name: "send",
description: "Send message to all guilds bot joined",
usage: `!send <text>`,
category: "dev",
run: async (client, message, args) => {
client.guilds.cache.map((guild) => {
const channel = guild.channels.cache.find(
(c) => c.type === "text" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
);
channel.send('your_text')
})
}}

Related

Trying to catch response but why wont it send?

I am currently working on a command right now that I would like the server owner to use. When done it sends the embed and will wait for the server owner to paste we will say the channel id. I want to label this to call in another command but at the moment it sends the embed but when I send a channel ID nothing happens. No message is sent but it also does not break the bot. I am still able to send the command again and again.
Please do not mind the slop, I am new to all this and trying to learn as I go any tips would be appreciated!
EDIT: I am using version 12 (12.5.3)
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'setchannel',
description: 'command to assign bot to channel',
execute(message, args) {
if(message.channel.type == "dm") {
const keepinservercommandembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('**Im Sorry!**')
.addFields(
{ name: `**Can` + `'t accept: ${prefix}setchannel**`, value: 'Please keep this command to the server!' },
)
message.channel.send(keepinservercommandembed);
}
else {
const messagesender = message.member.id;
const serverowner = message.guild.owner.id;
const setchannelembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Let's get searching!**`, value: `Hello ${message.guild.owner}, what channel would you like me to post group finding results?` },
)
const notownerembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Whoops!**`, value: `Sorry only ${message.guild.owner} can use this command.` },
)
if(messagesender == serverowner) {
message.delete ();
const filter = m => m.content.message;
const collector = message.channel.createMessageCollector(filter, { time: 15000 });
message.channel.send(setchannelembed).then(() => {
collector.on('collect', m => {
message.channel.send(`${m.content}`)
});
});
}
else {
message.delete ();
message.channel.send(notownerembed);
}
}
}
}
After comparing your code to my similiar discord.js v13 code and checking out the v12 docs, I think I found the problem.
I don't think m.content.message is a function. If your aim is for someone to paste the channel ID, the filter code would be:
const filter = m => m.author.id === message.guild.owner.id;
To filter out other people who may be entering an ID (assuming the input is valid).
Use the filter as follows:
message.channel.createMessageCollector({filter: filter, time: 15000 });
To filter out invalid inputs:
collector.on('collect', m => {
if (isNaN(m)) return; //all channel id's in discord are integers (numbers)
else message.channel.send(`${m.content}`);
});

So, I got a question. Is it possible to have a embed welcome message in a Discord bot that gets deleted after a few seconds?

var TOKEN = ""
const client = ("TOKEN");
const { Client, MessageEmbed } = require('discord.js');
const channel = ("CHANNELID");
const embed = new MessageEmbed()
('guildMemberAdd', member => {
const embed = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(`Welcome ${member}! You are the ${membercount}th member!`)
.setImage(member.user.avatarURL)
})
That is my current code for this but, I'm unsure because there are some errors to it.
Yes it is possible.
Please don't use this code, it will not work based on how you have it coded now
var TOKEN = ""
const client = ("TOKEN");
const { Client, MessageEmbed } = require('discord.js');
const channel = ("CHANNELID");
const embed = new MessageEmbed()
('guildMemberAdd', member => {
const embed = new Discord.RichEmbed()
.setColor('#0099ff')
.setDescription(`Welcome ${member}! You are the ${membercount}th member!`)
.setImage(member.user.avatarURL)
})
Please use the code below:
// var TOKEN = "" //token is never a variable
// const client = ("TOKEN"); //please find a different way to code this as this will cause confusion later on
const TOKEN = ""
const { Client, MessageEmbed } = require('discord.js');
const client = new Client({
intents: [], // pick the intents you need here https://discord.com/developers/docs/topics/gateway#list-of-intents
})
client.login(TOKEN)
client.on('guildMemberAdd', member => {
const welcomeChannel = client.channels.cache.get("channel_id")
const membercount = member.guild.members.cache.filter(member => !member.user.bot).size
const timeout = 30 * 1000 //30 being how many seconds till the message is deleted.
const embed = new MessageEmbed()
.setColor('#0099ff')
.setTitle(`${member.displayName} has joined us!`)
.setDescription(`Welcome ${member}!\nYou are member number ${membercount}!`)
.setThumbnail(member.displayAvatarURL())
welcomeChannel.send({
embeds: [embed]
}).then((message) => {
setTimeout(() => {
message.delete()
}, timeout);
})
})
Yes, you can!
just use
.then(msg => {
setTimeout(() => {
msg.delete().catch(() => null)
}, 5000)
})

Discord.js Bot doesn't ping a user or role when mentioned

Have this simple slash command which includes pinging/mentioning <#!${interaction.member.id}> but it doesn't ping the mentioned user/role at all. I did enabled Mention #everyone, #here, and All Roles and tried to mention different users and roles still, it's not working.
This is the code:
run: async (client, interaction, args) => {
if(!interaction.member.permissions.has('MANAGE_CHANNELS')) {
return interaction.followUp({content: 'You don\'t have the required permission!'}).then(msg => {
setTimeout(() => {
msg.delete()
}, 3000)
})
}
const [subcommand] = args;
const embedevent = new MessageEmbed()
if(subcommand === 'create'){
const eventname = args[1]
const prize = args[2]
const sponsor = args[3]
embedevent.setDescription(`__**Event**__ <a:w_right_arrow:945334672987127869> ${eventname}\n__**Prize**__ <a:w_right_arrow:945334672987127869> ${prize}\n__**Donor**__ <a:w_right_arrow:945334672987127869> ${sponsor}`)
embedevent.setFooter(`${interaction.guild.name}`, `${interaction.guild.iconURL({ format: 'png', dynamic: true })}`)
embedevent.setTimestamp()
}
return interaction.followUp({content: `<#!${interaction.member.id}>`, embeds: [embedevent]})
}
}
The command is working just fine but the only problem is the pinging/mentioning.
I'm not into interactions, but based on my experience doing bot, you should add the code first
const pingmember = interaction.mentions.members.first()
then you can do now
return interaction.followUp({content: `${pingmember}`, embeds: [embedevent]})
or
const pingmember = interaction.mentions.members.first()
if(pingmember) {
//your code here
}

Setting up chatbot command in discord.js 12

i wanted to make a chatbot command like a example of command
?bsetchatbot [channel name]
heres a syntax of the command and here what code i used
note - i already impoted required modules
const Chat = require("easy-discord-chatbot");
const chat = new Chat({ name: "Blabbermouth" });
if (message.content === "?bsetchatbot") {
channelname = message.mentions.channels.first()
if(!channelname) {
return message.channel.send("Pleease Mention A channel!")
}
if(message.channel.name === `${channelname}` && !message.author.bot) {
let reply = await chat.chat(message.content)
message.channel.send(reply)
}
message.channel.send(`Chat Bot Channel is set as ${channelname}`)
}
The problem is that you don't save the channel where people can chat with the bot. I recommend to save the channel with the ValueSaver package as you can can save it and import it again when your server shut down. Here is an example
const { ValueSaver } = require('valuesaver');
const channels = new ValueSaver();
channels.import(`channels`); // Import the ValueSaver named 'channels' if a save exists with this name
const { Client } = require('discord.js');
const Chat = require('easy-discord-chatbot');
const chat = new Chat({name: 'Blabbermouth'});
const client = new Client();
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag} on ${new Date().toString()}`);
});
client.on('message', async message => {
if(message.author.bot || message.channel.type === `DM`) return;
let args = message.content.substring(1).split(" ");
const _channelid = channels.get(message.guild.id); // Get the channel id
if(_channelid){ // If there has been set a channel
if(message.channel.id === _channelid){ // If the channel is the chat channel
let reply = await chat.chat(encodeURI(message.content));
message.channel.send(reply).catch(console.log)
}
}
if(message.content.startsWith('?')){
switch(args[0].toLowerCase()){
case 'bsetchatbot':
const channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`Please mention a channel to set the chat channel`).catch(console.log);
channels.set(message.guild.id, channel.id); // Access the channel id by the guild id
channels.save(`channels`); // Create a new save with the name 'channels'
break;
}
}
});
client.login('Your Token');
ValueSaver: https://npmjs.com/package/valuesaver

channel.send is not a function? (Discord.JS)

Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}

Resources