简体   繁体   English

如何在 Discord.js 事件“guildCreate”中发送消息

[英]How to send message in Discord.js event "guildCreate"

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.请在这方面帮助我,我不知道它在 Python 中存在,但我不习惯。

Thank you for your help感谢您的帮助

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+更新 discord.js 12+ Discord.JS 现在使用缓存 - 这是 12+ 的相同答案

bot.on("guildCreate", guild => {
    let found = 0;
    guild.channels.cache.map((c) => {
        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");您可以简单地使用guild.author.send("Thanks for inviting my bot");向所有者发送例如一条消息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!");或者,您也可以向特定用户发送消息: client.users.get("USER ID").send("My bot has been invited to a new server!");

I'm not sure if you're using a command handler or not since you seem new to JS I'm going to assume you're not.我不确定您是否正在使用命令处理程序,因为您似乎对 JS 不熟悉,我假设您不是。 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.
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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