【问题标题】:Check if a user can send message in a mentioned channel discord.js检查用户是否可以在提到的频道 discord.js 中发送消息
【发布时间】:2023-03-11 11:54:01
【问题描述】:
我有一个命令允许用户让机器人说出一条消息,但我希望它能够在发送消息之前检查用户是否能够在该频道中发送消息。目前,我只是将其锁定为MANAGE_MESSAGES 权限。
代码如下:
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``)')
}
我已经搜索并找不到太多关于此的信息,感谢任何帮助
【问题讨论】:
标签:
javascript
node.js
discord
discord.js
【解决方案1】:
我不确定我是否正确理解了您的问题。您可以使用channel.permissionFor(member).has('PERMISSION_NAME')检查该成员是否在某个频道中具有权限。我不确定您是否真的希望用户拥有MANAGE_MESSAGES 权限,我认为SEND_MESSAGES 应该足够了,所以我在下面的代码中使用了它。我还让它更干净一些,并添加了一些 cmets:
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}`);