Discord.js(djs)如何从message.content获取消息ID 附使用示例
解决方法
场景1:获取触发指令的用户原消息ID
Discord.js 的Message实例自带id属性,直接取值即可,修改后的代码如下:
if(message.content === "msgid"){ const messageid = message.id; message.channel.send(`你的消息ID是 ${messageid}`) }
场景2:获取机器人发送的回复消息的ID
message.channel.send()是异步方法,返回值为解析后携带消息实例的Promise,需要等待异步执行完成后从返回的消息实例中取ID,示例代码如下:
// 外层消息监听回调需要添加async修饰,示例:client.on('messageCreate', async (message) => { ... }) if(message.content === "msgid"){ // 等待消息发送完成,获取发送成功的消息实例 const sentMsg = await message.channel.send(`你的触发消息ID是 ${message.id}`); // 取机器人发送的这条消息的ID const botMsgId = sentMsg.id; // 后续可按需使用该ID console.log('机器人发送的消息ID:', botMsgId); }
Webhook场景特殊说明
如果你是通过webhook发送消息,webhook.send()方法同样返回携带消息实例的Promise,按相同方式取值即可:
const webhookSentMsg = await webhook.send({ content: '通过webhook发送的消息' }); const webhookMsgId = webhookSentMsg.id;
内容的提问来源于stack exchange,提问作者IHZAQ
相关产品推荐
相关产品推荐

