如何向特定频道发送消息

How to send a message to a specific channel

我正在尝试使用我的 Discord 机器人向特定频道发送消息,该机器人位于多个服务器中。我希望机器人从一个服务器接收消息并在特定频道中将消息发送到我的个人服务器,但我无法将其发送到 'find' 频道。 API 改变了吗?我也尝试 npm install discord.js 更新。

代码:

if (message.author.id == 'XXXXX' && !mess.includes("Dank") && message.channel.id != 'XXXXX') {
  bot.channels.get('XXXXX').send('memes');
}

我尝试了一些方法,但 none 成功了。

TypeError: Cannot read property 'send' of undefined
    at decideIfMention (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\bot.js:80:45)
    at Client.bot.on (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\bot.js:68:3)
    at emitOne (events.js:116:13)
    at Client.emit (events.js:211:7)
    at MessageCreateHandler.handle (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
    at WebSocketPacketManager.handle (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
    at WebSocketConnection.onPacket (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
    at WebSocketConnection.onMessage (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
    at WebSocket.onMessage (C:\Users\XXXX\Desktop\Coding Crud\Discord Bot 2\node_modules\ws\lib\event-target.js:120:16)
    at emitOne (events.js:116:13)

假设您有 client (which would be an instance of Discord.Client) try finding the desired channel by using Client.find:

const channel = client.channels.cache.find(channel => channel.name === channelName)
channel.send(message)

如果您没有直接 client 但有 message instance, you could always access it from within the Message.client 属性.

嗯,如果你有 Discord.Client() 的“client”实例,那么使用这个:

解决方案已更新 以使用较新的 discordjs 版本

client.channels.cache.get(`channelID`).send(`Text`)

别忘了channeID参数是字符串类型,不是数字。真的很简单也很精确。

如果您使用的是 typescript,则需要在 Channel 上进行类型转换。所以你可以在 TextChannel 中转换它并发送消息

const channel = client.channels.cache.find(ch => ch.name === 'compras');

if (channel.isText() {
    (<TextChannel> channel).send('message')
}