我对 discord.js 比较陌生,我已经开始构建一个机器人项目,允许用户通过命令创建消息,将该消息存储在我的私人服务器上的隐藏频道中,然后说消息可以通过消息ID提取。
我有写入工作,它返回在隐藏频道中发送的消息的消息 ID,但我完全被 get 命令难住了。我试过在线搜索,但我尝试过的每种方法都会返回错误,例如“无法读取未定义的属性‘fetch’”或“未定义‘通道’”。以下是我尝试过的一些示例,任何帮助将不胜感激。请注意,我的 args 已经准确,“args[0]”是命令后的第一个参数。 “COMMAND_CHANNEL”是执行命令的通道,而“MESSAGE_DATABASE”是存储目标消息的通道。
let msgValue = channel.messages.cache.get(args[0])
client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content)
let msgValue = msg.channel.message.fetch(args[0])
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
我什至尝试使用 node-fetch 来调用 discord API 本身
const api = require("node-fetch")
let msgValue = api(`https://discordapp.com/api/v8/channels/${MESSAGE_DATABASE}/messages/${args[0]}`)
.then(message => client.channels.cache.get(COMMAND_CHANNEL).send(msgValue.content))
.catch(console.error);
是我遗漏了什么还是我犯了某种错误?
编辑:感谢您的帮助!我完成了我的机器人,它只是一个小实验机器人,它允许您创建只能在执行命令时通过其 ID 查看的秘密消息:get_secret_message
命令列表:
:write_secret_message - 写一条秘密消息,执行后机器人会向你发送消息 ID。
:get_secret_message
:invite - 获取机器人邀请链接。
注意:您的 DM 必须开启,否则机器人将无法 DM 任何信息。
我的测试消息ID:800372849155637290
答案 0 :(得分:1)
fetch
将结果作为 promise 返回,因此您需要使用 then
来访问该值,而不是将其分配给变量 (msgValue
)。您还打错了字 (channel.message
-> channel.messages
)。
我建议使用这样的东西:
msg.channel.messages
.fetch(args[0])
.then(message => {
client.channels
.fetch(COMMAND_CHANNEL)
.then(channel => channel.send(message.content))
.catch(console.error)
})
.catch(console.error)
答案 1 :(得分:0)
我认为您发布的第二次尝试非常接近,但是您犯了一个错字,并且您存储获取的消息的方式已关闭。
错字是你写了 msg.channel.message.fetch(args[0])
但它应该是 msg.channel.messages.fetch(args[0])
(错字是 s
之后缺少的 message
)。 See the messages
property of a TextChannel。
其次,但这只是一个猜测,因为我无法确定,因为您没有提供很多代码,当您尝试获取消息时,您是从错误的渠道这样做的。您正在尝试从执行命令的通道(msg.channel
)中获取具有给定 ID 的消息。除非此命令是从“MESSAGE_DATABASE”通道执行的,否则您需要从“MESSAGE_DATABASE”通道而不是 msg.channel
通过 ID 获取消息。
第三,如果您获取消息,则可以在 .then
方法中使用来自 Promise 的响应。您尝试使用 msgValue
将响应分配给变量 let msgValue = msg.channel.message.fetch(args[0])
,但这不会达到您期望的效果。这将实际将整个 Promise 分配给变量。我认为您想要做的只是直接在 .then
方法中使用来自 Promise 的响应。
综上所述,请查看下面的代码片段,灵感来自 MessageManager .fetch
examples。试一试,看看它是否有效。
// We no longer need to store the value of the fetch in a variable since that won't work as you expect it would.
// Also we're now fetching the message from the MESSAGE_DATABASE channel.
client.channels.cache.get(MESSAGE_DATABASE).fetch(args[0])
// The fetched message will be given as a parameter to the .then method.
.then(fetchedMessage => client.channels.cache.get(COMMAND_CHANNEL).send(fetchedMessage.content))
.catch(console.error);