我正在制造一个不和谐的谋杀神秘机器人。
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("now done");
}
});
client.login('my token');
我将在代码中添加些什么,以便在被标记的人员到达那里之后,角色从活着变成死人?
答案 0 :(得分:1)
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.member(mention);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
/*
client.on("message", async (message) => {
// ...
try {
await Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.error);
Promise.all
意味着添加和删除角色的承诺是同时开始的。一个promise是一个对象,可以解析为一个值或拒绝一个错误,因此.catch(console.error)
记录所有错误。我建议您也处理message.delete()
,mention.send('you are dead')
和message.channel.send("now done")
的错误。
有关member.roles.remove()
和member.roles.add()
的更多信息,请参见the documentation for GuildMemberRoleManager
。