如果我提到一个用户,当它期望一个角色时,discord.js Bot就会退出



我正在制作一个命令,机器人可以通过命令更改角色的颜色

var red = ['#ff0000']

client.on('message', message => {
var colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(role => role.name === args[0].join(" "));
if(message.content.startsWith === 'grimm!change red'){
colorRole.edit({
color: red[0]
});
}})

我遇到了一个问题,如果我键入命令,然后提到角色,它不会改变角色的颜色,也不会在命令提示符中显示任何内容,而且我一直在重新排列代码。

我也有问题的另一种代码以及

client.on('message', message => {   
if (message.content.startsWith('grimm!test')) {
let colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(role => role.name === args[0].join(" "));
message.channel.send(`${colorRole}`);

const roleEmbed = new Discord.MessageEmbed()
.setColor('#ff6700')
.setAuthor(colorRole)

message.channel.send(roleEmbed);
}
})

这段代码是我用来测试我的机器人是否能识别角色的,它很有效,但每次我不小心提到某人,机器人都会给我一个错误,机器人就会退出,有办法解决这两个问题吗?我只是希望代码能够更改所提到的角色的颜色,如果我提到一个人,它不会退出机器人。谢谢大家!

要解决崩溃问题,是因为当您标记用户时。您正在搜索他们作为角色的用户名。因此,您的支票将返回undefined&您没有处理此错误,因此机器人程序无法继续其操作,因此将锁定。

我对你的例子做了轻微的修改,评论应该会澄清的变化

const colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(R => R.name === args.join(" "));
if (!colorRole) return;   // Check if color role is undefined, if it is. Then Return aka do nothing. 
const roleEmbed = new Discord.MessageEmbed()
.setColor(`#ff6700`)
.addFields(
{name:"Role Name",value:colorRole.name, inline:true},
{name:"Role ID",value:colorRole.id,inline:true},
{name:"Role Positon", value:colorRole.rawPosition, inline:false}
)
message.channel.send(roleEmbed);

修改了嵌入,使其明确指示已找到正确的角色。请记住,由于角色层次结构不一致,rawPosition在未来的错误处理中可能很有用。

关于更新角色颜色的第二个问题,我添加了两个复选框。

  1. 检查colorRole是否为对象且未定义
  2. 检查机器人是否具有编辑角色的权限

如果这两个检查中的任何一个失败,机器人程序将优雅地返回并停止执行命令&实际更新的脚本是

const colorRole = message.mentions.roles.first() || message.guild.roles.cache.find(R => R.name === args.join(" "));
if (!colorRole) return;   // Check if color role is undefined, if it is. Then Return aka do nothing.
if (!message.guild.me.hasPermission('MANAGE_ROLES')) return // Bot needs this position to perform this action 
colorRole.edit({
color:'#ff6700'
})
.then(message.channel.send("Successfully Updated Role Color"))
.catch(Err=> console.log(Err));

最新更新