最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to send message in Discord.js event "guildCreate" - Stack Overflow

programmeradmin4浏览0评论

I have been wondering how can I send messages when someone invites my bot to their server.

Please help me in this area I can't figure it out it's there in Python but I have not used to it.

Thank you for your help

I have been wondering how can I send messages when someone invites my bot to their server.

Please help me in this area I can't figure it out it's there in Python but I have not used to it.

Thank you for your help

Share Improve this question edited Sep 8, 2018 at 6:43 Sumithran 6,5657 gold badges43 silver badges58 bronze badges asked Sep 8, 2018 at 6:22 discord botdiscord bot 211 gold badge1 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

All the above answers assume you know something about the server and in most cases you do not!

What you need to do is loop through the channels in the guild and find one that you have permission to text in.

You can get the channel cache from the guild. Take the below example:

bot.on("guildCreate", guild => {
  
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
  if(channel.type == "text" && defaultChannel == "") {
    if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
      defaultChannel = channel;
    }
  }
})
//defaultChannel will be the channel object that the bot first finds permissions for
defaultChannel.send('Hello, Im a Bot!')
    
   
});

You can of course do further checks to ensure you can text before texting but this will get you on the right path

Update discord.js 12+ Discord.JS now uses cache - here is the same answer for 12+

bot.on("guildCreate", guild => {
    let found = 0;
    guild.channels.cache.map((channel) => {
        if (found === 0) {
          if (channel.type === "text") {
            if (channel.permissionsFor(bot.user).has("VIEW_CHANNEL") === true) {
              if (channel.permissionsFor(bot.user).has("SEND_MESSAGES") === true) {
                channel.send(`Hello - I'm a Bot!`);
                
                found = 1;
              }
            }
          }
        }
      });
   
  })

You can simply send the owner for example a message using guild.author.send("Thanks for inviting my bot");

Or you can also send a message to a specific user: client.users.get("USER ID").send("My bot has been invited to a new server!");

I'm not sure if you're using a mand handler or not since you seem new to JS I'm going to assume you're not. The following is a code snippet for what you're trying to do:

client.on('guildCreate', (guild) => {
    guild.channels.find(t => t.name == 'general').send('Hey their Im here now!'); // Change where it says 'general' if you wan't to look for a different channel name.
});
发布评论

评论列表(0)

  1. 暂无评论