我有一个命令允许用户让机器人说出一条消息,但我希望它能够在发送消息之前检查用户是否能够在该频道中发送消息。目前,我只是将其锁定为“管理消息”权限。
代码如下:
if (message.member.hasPermission("MANAGE_MESSAGES")) {
let msg;
let textChannel = message.mentions.channels.first();
message.delete();
if (textChannel) {
msg = args.slice(1).join(" ");
if (msg === "") {
message.channel.send("Please input a valid sentence/word.")
} else {
textChannel.send(`**Message from ${message.author.tag}:** ${msg}`)
}
} else {
msg = args.join(" ");
if (msg === "") {
message.channel.send("Please input a valid sentence/word.")
} else {
message.channel.send(`**Message from ${message.author.tag}:** ${msg}`)
}
}
} else {
message.reply('You lack the required permissions to do that. (Required Permissions: ``MANAGE_MESSAGES``)')
}
我已经搜索过但找不到太多关于此的任何帮助不胜感激
答案 0 :(得分:2)
我不确定我是否正确理解了您的问题。您可以使用 channel.permissionFor(member).has('PERMISSION_NAME')
检查该成员是否在某个频道中拥有权限。我不确定您是否真的希望用户拥有 MANAGE_MESSAGES
权限,我认为 SEND_MESSAGES
应该足够了,所以我在下面的代码中使用了它。我还把它弄得更干净一点,并添加了一些评论:
const mentionedChannel = message.mentions.channels.first();
// if there is no mentioned channel, channel will be the current one
const channel = mentionedChannel || message.channel;
message.delete();
// returns true if the message author has SEND_MESSAGES permission
// in the channel (the mentioned channel if they mentioned one)
const hasPermissionInChannel = channel
.permissionsFor(message.member)
.has('SEND_MESSAGES', false);
// if the user has no permission, just send an error message and return
// so the rest of the code is ignored
if (!hasPermissionInChannel) {
return message.reply(
`You can't send messages in ${mentionedChannel}. You don't have the required permission: \`SEND_MESSAGES\``,
);
}
const msg = mentionedChannel ? args.slice(1).join(' ') : args.join(' ');
if (!msg) {
// send an error message in the same channel the command was coming
// from and return
return message.reply('Please input a valid sentence/word.');
}
// if the user has permission and has a message to post send it to the
// mentioned or current channel
channel.send(`**Message from ${message.author.tag}:** ${msg}`);