Send message to specific channel with typescript

六眼飞鱼酱① 提交于 2020-01-02 09:55:15

问题


I want to send a greeting message to an "welcome" text channel, whenever a new user joins the server (guild).

The problem I'm facing is that, when I find the wanted channel, I will receive the channel with the type GuildChannel.

Since GuildChannel has no send() function, I'm not able to send the message. But I can't find a way to find the TextChannel, so I'm stuck here.

How can I get to the TextChannel so that I'm able to use the send() message? Below the code I'm using by now:

// Get the log channel (change to your liking) 
const logChannel = guild.channels.find(123456); 
if (!logChannel) return;

// A real basic message with the information we need. 
logChannel.send('Hello there!'); // Property 'send' does not exist on type 'GuildChannel'

I'm using version 11.3.0 of discord.js


回答1:


Thanks to this GitHub issue I've found the solution to my problem.

I need to use a Type Guard to narrow down the correct type.

My code now is this:

// Get the log channel
const logChannel = member.guild.channels.find(channel => channel.id == 123456);

if (!logChannel) return;

// Using a type guard to narrow down the correct type
if (!((logChannel): logChannel is TextChannel => logChannel.type === 'text')(logChannel)) return;

logChannel.send(`Hello there! ${member} joined the server.`);



回答2:


I do this:

let channel = client.guilds.get('your-guild-id').channels.get('your-channel-id');
channel.send("it worked");

(client is the discord client). your code should work if you change find to get and put the channel id in some single quotes. Well, it works for me.




回答3:


Maybe this can help you?

Code:

client.on('guildMemberAdd', member => {
    let channel = member.guild.channels.find('name', 'welcome');
    let memberavatar = member.user.avatarURL
        if (!channel) return;
        let embed = new Discord.RichEmbed()
            .setColor('RANDOM')
            .setThumbnail(memberavatar)
            .addField(':bust_in_silhouette: | name : ', `${member}`)
            .addField(':microphone2: | Welcome!', `Welcome to the server, ${member}`)
            .addField(':id: | User :', "**[" + `${member.id}` + "]**")
            .addField(':family_mwgb: | Your are the member', `${member.guild.memberCount}`)
            .addField("Name", `<@` + `${member.id}` + `>`, true)
            .addField('Server', `${member.guild.name}`, true )
            .setFooter(`**${member.guild.name}**`)
            .setTimestamp()
        channel.sendEmbed(embed);
});



回答4:


Maybe for latecomers who are still looking for an answer this worked for me

let channel = client.channels.get("channelid") as Discord.TextChannel;
channel.send("what you want to send to that channel");


来源:https://stackoverflow.com/questions/53563862/send-message-to-specific-channel-with-typescript

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