简体   繁体   中英

discord.js v12 send message to first channel

Hi how can i send message to first channel where bot can send messages in Discord.js v12. Please help me. This didnt work for me:

client.on("guildCreate", guild => {
    let channelID;
    let channels = guild.channels;
    channelLoop:
    for (let c of channels) {
        let channelType = c[1].type;
        if (channelType === "text") {
            channelID = c[0];
            break channelLoop;
        }
    }


    let channel = client.channels.get(guild.systemChannelID || channelID);
    channel.send(`Thanks for inviting me into this server!`);
});

You can do it like this.

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("guildCreate", (guild) => {
  const channel = guild.channels.cache.find(
    (c) => c.type === "text" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
  );
  if (channel) {
    channel.send(`Thanks for inviting me into this server!`);
  } else {
    console.log(`can\`t send welcome message in guild ${guild.name}`);
  }
});

Updated for Discord v13

Note the c.type has been changed from text to GUILD_TEXT

const Discord = require("discord.js");
const client = new Discord.Client();

client.on("guildCreate", (guild) => {
  const channel = guild.channels.cache.find(
    (c) => c.type === "GUILD_TEXT" && c.permissionsFor(guild.me).has("SEND_MESSAGES")
  );
  // Do something with the channel
});

Update for from v13 to v14

on event of guildCreate is now Events.GuildCreate

c.type changed from GUILD_TEXT to ChannelType.GuildText

guild.me is now guild.members.me

const { Events, ChannelType } = require('discord.js')

const client = new Client({
//your intents here
intents: []
})

client.on(Events.GuildCreate, guild => {
    const channel = guild.channels.cache.find(c =>
        c.type === ChannelType.GuildText &&
        c.permissionsFor(guild.members.me).has('SEND_MESSAGES')
    )
    //do stuff with the channel
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM