You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在踢出用户前向其发送Embed私信(discord.js)

修改后的黑名单命令(Embed格式版)

下面是把所有普通消息替换为Embed格式的完整代码,适配discord.js v14:

const { EmbedBuilder } = require('discord.js');
const { SlashCommandBuilder } = require('@discordjs/builders');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('blacklist')
    .setDescription('Blacklist someone from the server')
    .addUserOption((option) => option.setName('member')
      .setDescription('Who are you blacklisting?')),
  async execute(interaction) {
    await interaction.deferReply();
    const member = interaction.options.getMember('member');

    // 权限检查(用Embed回复)
    if (!interaction.member.roles.cache.some(r => r.name === "Blacklist perms")) {
      return interaction.editReply({ 
        embeds: [
          new EmbedBuilder()
            .setColor('#ff0000')
            .setTitle('权限不足')
            .setDescription('你没有使用该命令的权限!')
        ]
      });
    }

    // 给被拉黑用户发私信(Embed格式)
    try {
      await member.send({
        embeds: [
          new EmbedBuilder()
            .setColor('#ff0000')
            .setTitle('你已被拉黑')
            .setDescription('你已从服务器被拉黑,无法再进入该服务器。')
        ]
      });
    } catch (err) {
      // 处理私信发送失败(比如用户关闭了服务器私信)
      await interaction.followUp({ 
        content: '无法给该用户发送拉黑通知,对方可能关闭了私信权限。',
        ephemeral: true 
      });
    }

    // 执行拉黑(踢人)操作
    member.kick('被管理员拉黑')
      .then(() => {
        // 成功拉黑后的Embed回复
        interaction.editReply({ 
          embeds: [
            new EmbedBuilder()
              .setColor('#00ff00')
              .setTitle('拉黑成功')
              .setDescription(`${member} 已被成功拉黑!`)
          ]
        });
      })
      .catch(err => {
        // 机器人权限不足的Embed提示
        interaction.editReply({ 
          embeds: [
            new EmbedBuilder()
              .setColor('#ff0000')
              .setTitle('操作失败')
              .setDescription('我没有足够的权限执行此操作,请检查我的角色权限。')
          ]
        });
      });
  },
};

关键修改说明

  • 导入EmbedBuilder:discord.js v14中必须通过这个类创建嵌入式消息,所以要在文件顶部导入。
  • 统一用Embed替换文本消息:所有回复和私信都通过embeds字段传入Embed数组(即使只有一个Embed也要用数组格式)。
  • 增加私信失败处理:用户可能关闭了服务器私信权限,用try/catch捕获错误,避免程序崩溃,同时悄悄通知命令执行者。
  • 颜色区分状态:用红色表示错误/警告,绿色表示成功,让视觉反馈更直观。
  • 优化踢人逻辑:把踢人操作的then/catch分开,确保成功和失败都有对应的Embed提示。

内容的提问来源于stack exchange,提问作者MrBossy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:39:19