Reputation: 403
I'm trying to send message with bot upon joining with statement.
//Will post message when bot joined new server because system channel exists.
if(guild.systemChannelId != null) return guild.systemChannel.send("Thank you for invite!"), console.log('Bot Joined new server!')
//Send post join message when there is no system channel on the server to possible channel (not working)
client.guilds.cache.forEach((channel) => {
if(channel.type == "text") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
channel.send("Thanks for inviting me")
console.log('Bot Joined new server!')
}
}
})
guild.systemChannel.send("Thank you for invite!")
This one works and will send message to the "default system channel". Problem is if server has no system channel, this will appear as error. So i had to create statement above and use this request only when system channel exists.
Error: Unhandled rejection TypeError: Cannot read property 'send' of null
-> error will appear when using only guild.systemChannel.send("Thank you for invite!")
in the code without statement.
How to send message to the first channel possible if system channel does not exist on the server?
Upvotes: 1
Views: 3518
Reputation: 1477
The easiest way is to forEach through each channel in the cache, and stop once you find one:
bot.on('guildCreate', guild => {
let found = false;
guild.channels.cache.forEach((channel) => {
if(found) return;
if(channel.type === "text" && channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
channel.send("Thank you for inviting me!");
found = true;
}
})
});
Upvotes: 0
Reputation: 2286
You simply need to access the first cached text channel you can achieve this by accessing the cache and filtering for text channels bot has permissions to send messages to like so:
client.on('guildCreate', (g) => {
const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
channel.send("Thank you for inviting me!")
})
Upvotes: 2