【问题标题】:Command to DM the mentioned users命令 DM 提到的用户
【发布时间】:2021-05-24 15:40:01
【问题描述】:

这是我给上述成员的 DM 代码。

const { MessageEmbed } = require("discord.js");

module.exports = {
  name: "dm",
  category: "moderation",
  usage: "DM <@mention> <message>",
  description: "DM server members!",
  run: async (client, message, args) => {
    if (!message.member.hasPermission("MANAGE_ROLES")) {
      return message.channel.send(
        "Access restricted!"
      );
    }

    const targets = message.mentions.members;

    if (!targets) {
      return message.channel.send(
        "Please Mention the person to who you want to DM!"
      );
    }

    if (message.mentions.users.bot) {
      return message.channel.send("You cannot DM bots");
    }

    const reason = args.slice(0).join(" ");

    if (!reason) {
      return message.channel.send(
        "Place provide the message to send!"
      );
    }

    message.channel.send(`DM sent succesfully!`);
      
      let embed = new MessageEmbed()
.setColor('#0099ff')
    .setTitle(`Message from ${message.guild.name}`)
    .setDescription(`${reason}`)
    .setThumbnail('https://i.ibb.co/PCnBZ8w/IMG-20210205-191207.jpg')
    .setFooter(`Sent by ${message.member.user.tag}`)
    
      targets.forEach(target => target.send(embed));
      message.delete();
  }
};

这样使用:prefixdm the message @mention1 @mention2 ...。 但是在用户收到的 DM 中,由于我声明了reason,他们也提到了该命令。我该如何解决这个问题,以便他们看不到消息中的提及?

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    您可以使用正则表达式清理消息。 MessageMentions 有一个 USERS_PATTERN 属性,其中包含匹配用户提及的正则表达式(如 &lt;@82043902196179341&gt;)。您可以将它与 JavaScript 的 .replaceAll() 方法一起使用,以将所有出现的提及替换为空字符串:

    const reason = args
      .slice(0)
      .join(' ')
      .replaceAll(MessageMentions.USERS_PATTERN, '')
      .trim();
    

    别忘了从discord.js导入MessageMentions

    const { MessageEmbed, MessageMentions } = require("discord.js");
    

    更新:您还可以使用.replace() 代替.replaceAll(),因为正则表达式全局匹配用户提及。 Source.

    【讨论】:

    • 我不知道如何替换所有提及。
    • 为什么?我已经提供了上面的代码,它用一个空字符串替换了每个提到的用户。
    • .replaceAll 不是函数
    • 它仅在 Node.js v15+ 中可用。你的节点版本是什么?在终端输入node -v
    • @Anush 你也可以用.replace()代替.replaceAll()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 2021-05-17
    • 2021-09-27
    • 2021-09-15
    • 2021-04-04
    • 2020-10-10
    • 2019-08-22
    相关资源
    最近更新 更多