使用打字稿向特定频道发送消息 [英] Send message to specific channel with typescript

查看:16
本文介绍了使用打字稿向特定频道发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当有新用户加入服务器(公会)时,我想向欢迎"文本频道发送问候消息.

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

我面临的问题是,当我找到想要的频道时,我会收到类型为 GuildChannel 的频道.

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

由于 GuildChannel 没有 send() 函数,我无法发送消息.但是我找不到TextChannel的方法,所以卡在这里.

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.

如何访问 TextChannel 以便能够使用 send() 消息?在我现在使用的代码下方:

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'

我正在使用 11.3.0 版的 discord.js

I'm using version 11.3.0 of discord.js

推荐答案

感谢这个 GitHub问题 我找到了解决问题的方法.

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

我需要使用 Type Guard 来缩小正确范围输入.

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.`);

这篇关于使用打字稿向特定频道发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆