使用打字稿将消息发送到特定频道 [英] Send message to specific channel with typescript
问题描述
每当新用户加入服务器(行会)时,我都想向欢迎文本频道发送问候消息。
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 of 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.
我需要使用< a href = https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html rel = nofollow noreferrer>类型防护以缩小正确的类型。
I need to use a Type Guard to narrow down the correct type.
我的代码现在是这样:
// 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屋!