node.js - 使用 typescript 将消息发送到特定 channel

标签 node.js typescript discord.js

每当有新用户加入服务器(公会)时,我想向“欢迎”文本 channel 发送问候消息。

我面临的问题是,当我找到想要的 channel 时,我将收到类型为 GuildChannel 的 channel 。

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

我怎样才能到达 TextChannel 以便我能够使用 send() 消息?在我现在使用的代码下方:

// 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'

我使用的是 discord.js 11.3.0 版

最佳答案

多亏了这个 GitHub issue,我找到了解决问题的方法。

我需要使用 Type Guard 来缩小正确类型的范围。

我现在的代码是这样的:

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

关于node.js - 使用 typescript 将消息发送到特定 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53563862/

相关文章:

node.js - 如何使用 next.js 的 getInitialProps 方法获取 cookie?

javascript - 给定值数组时从 json 中提取单个属性

javascript - 空 Node js的"cannot read property "id"

javascript - discord.js 未处理的PromiseRejectionWarning : TypeError: Cannot read property 'kickable' of undefined

javascript - 如何向discord.js 中的特定 channel 发送消息?

javascript - 如何使用 sinon 正确地 stub 和测试函数

javascript - native 代码 typescript 编译器

typescript - 带有 Typescript 导入 Assets 错误的 Gatsby (ts2307)

reactjs - 如何使用 fabric ui react 创建密码输入?

javascript - 如何返回一个对象与两个 Mongoose 模型相结合