Sending a message the first channel with discord.js

耗尽温柔 提交于 2019-12-11 05:19:32

问题


I've seen a lot of bots that have a greeting message when they join. Its usually sent to the first channel of the server.

For example:

bot joins the guild

Bot: Hey! Thanks for inviting me!

The code i have right now is really simple:

client.on("guildCreate", guild => {
    the code goes here
});

I dont know how to send a message to a random (first) channel though. If anyone could please tell me how the other bots do it I would be really greatful.


回答1:


I'm using Discord.js version 11.4.2, and I was able to use the following code to send a default message to the #general channel. Replace bot below with whatever your client's name is.

const Discord = require('discord.js');
const bot = new Discord.Client();

bot.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 = bot.channels.get(guild.systemChannelID || channelID);
    channel.send(`Thanks for inviting me into this server!`);
});

Edit: I've found that the guild.systemChannelID can be null so I've updated the code to search for the first text channel and use that for the initial message.




回答2:


To be quite frank there is no "good way" todo this... There used to be until discord removed it. (used to be: guild.defaultChannel)
Now days bot devs do some tests to find out where they send the message...

There are multiple ways todo find a good channel (here's a few):

A: Find a channel called welcome or general whichever you prefer the bot to send it to.

guild.channels.find(`name`,`welcome`).send(`Thx for invite`);

B: Send to the first channel the bot is allowed to send to. (this works well unless bot is given admin);

guild.channels.sort(function(chan1,chan2){
    if(chan1.type!==`text`) return 1;
    if(!chan1.permissionsFor(guild.me).has(`SEND_MESSAGES`)) return -1;
    return chan1.position < chan2.position ? -1 : 1;
}).first().send(`Thx! for invite`);

The above code does this:

  1. grab all the channels and lets sort them
  2. if it's not a text channel return -1
  3. if the bot is DIS-ALLOWED to send return -1
  4. then sort the channels based on their position

C: Try other ways:

Find a channel most members in the server can send to
Find a channel the role @everyone can send to guild.roles.first()
Find a channel that gets the most activity
(check for channel with most messages sent in the past 5-10 minutes)



来源:https://stackoverflow.com/questions/51447954/sending-a-message-the-first-channel-with-discord-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!