当用户加入服务器时,该漫游器会发送一条欢迎消息,我要获取该欢迎消息的ID,如果用户加入后离开,则该漫游器会将其删除。我试图将消息的ID保存在变量中,并让bot在用户离开但没有成功时删除消息。我已经看过文档了,但是我真的不明白如何制作。
答案 0 :(得分:1)
要执行此操作,您将必须存储欢迎消息的ID及其绑定的用户(最好将其放入对象中)。当用户离开时,您将使用这些值删除该消息。
示例代码:
const Discord = require('discord.js');
const client = new Discord.Client();
const welcomeChannel = client.channels.find("name","welcome"); // Welcome is just an example
let welcomes = [];
client.on('message', (message) => {
if(message.channel.name === 'welcome') {
const welcomeObj = { id: message.id, user: message.mentions.users.first().username };
welcomes.push(welcomeObj);
}
});
client.on('guildMemberRemove', (member) => {
welcomes.forEach(welcome, () => {
if(welcome.user === member.user.username) {
welcomeChannel.fetchMessage(welcome.id).delete();
}
});
});
这仅在欢迎消息中包含对用户的提及时才有效,因此请确保在欢迎消息中。
此外,我目前无法自己测试此代码,所以如果您遇到任何问题,请告诉我。
答案 1 :(得分:1)
示例设置:
const welcomeMessages = {};
client.on('guildMemberAdd', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.send(`Welcome, ${member}.`);
if (!welcomeMessages[member.guild.id]) welcomeMessages[member.guild.id] = {};
welcomeMessages[member.guild.id][member.id] = message.id;
} catch(err) {
console.error('Error while sending welcome message...\n', err);
}
});
client.on('guildMemberRemove', async member => {
const welcomeChannel = client.channels.get('channelIDHere');
if (!welcomeChannel) return console.error('Unable to find welcome channel.');
try {
const message = await welcomeChannel.fetchMessage(welcomeMessages[member.guild.id][member.id]);
if (!message) return;
await message.delete();
delete welcomeMessages[member.guild.id][member.id];
} catch(err) {
console.error('Error while deleting existing welcome message...\n', err);
}
});