繁体   English   中英

检查用户是否可以在特定频道 discord.js 中发送消息

[英]Check if a user can send message in a specific channel discord.js

我有一个命令允许用户让机器人说出一条消息,但我希望它能够在发送消息之前检查用户是否能够在该频道中发送消息。 目前,我只是将其锁定为“管理消息”权限。

这是代码:

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``)')
}

我已经搜索并找不到太多关于此的信息,感谢任何帮助

我不确定我是否正确理解了您的问题。 您可以使用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}`);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM