如何获取客户端用户的最后一条消息?
How do I Get the Client User's Last Message?
您将如何获取机器人最后一条消息的对象?我尝试做类似的事情:
if (message.content.split(' ')[0] === 'test') {
message.channel.sendMessage('Test')
console.log(client.user.lastMessage.content)
}
如果我触发条件,控制台会给我一个错误:TypeError: Cannot read property 'content' of undefined
client.user.lastmessage
的值为 null
的原因是因为您刚刚启动机器人,并且在您 运行 您的 [=14] 之前它没有发送任何消息=]命令。
为了绕过这个,我会检查它是否为空(以防它不是),如果它 是 ,请使用 MessageCollector 并等待您的消息发送。
if (client.user.lastMessage == null) {
// Set the collector for the same channel
// Ensure the id is the same
var myID = client.user.id;
// Create collector and wait for 5 seconds (overkill but you never know with bad internet/lots of traffic)
const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === myID, { time: 5000 });
collector.on('collect', message => {
console.log(message.content);
collector.stop("Got my message");
});
} else {
console.log(client.user.lastMessage.content);
}
我测试过的确切代码块:
client.on('message', msg => {
if (msg.content === '$ping') {
msg.reply("Pong!")
if (client.user.lastMessage == null) {
const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === client.user.id, { time: 10000 });
collector.on('collect', message => {
console.log(message.content);
collector.stop("Got my message");
})
} else {
console.log(client.user.lastMessage.content);
}
}
}
您将如何获取机器人最后一条消息的对象?我尝试做类似的事情:
if (message.content.split(' ')[0] === 'test') {
message.channel.sendMessage('Test')
console.log(client.user.lastMessage.content)
}
如果我触发条件,控制台会给我一个错误:TypeError: Cannot read property 'content' of undefined
client.user.lastmessage
的值为 null
的原因是因为您刚刚启动机器人,并且在您 运行 您的 [=14] 之前它没有发送任何消息=]命令。
为了绕过这个,我会检查它是否为空(以防它不是),如果它 是 ,请使用 MessageCollector 并等待您的消息发送。
if (client.user.lastMessage == null) {
// Set the collector for the same channel
// Ensure the id is the same
var myID = client.user.id;
// Create collector and wait for 5 seconds (overkill but you never know with bad internet/lots of traffic)
const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === myID, { time: 5000 });
collector.on('collect', message => {
console.log(message.content);
collector.stop("Got my message");
});
} else {
console.log(client.user.lastMessage.content);
}
我测试过的确切代码块:
client.on('message', msg => {
if (msg.content === '$ping') {
msg.reply("Pong!")
if (client.user.lastMessage == null) {
const collector = new Discord.MessageCollector(msg.channel, m => m.author.id === client.user.id, { time: 10000 });
collector.on('collect', message => {
console.log(message.content);
collector.stop("Got my message");
})
} else {
console.log(client.user.lastMessage.content);
}
}
}