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

如何用Discord.js给新加入服务器的用户发送私信?代码失效求助

解决Discord.js机器人无法给新成员发送私信的问题

你的代码存在几处问题,同时需要适配Discord.js的版本要求,以下是具体修复方案:

1. 修正未定义变量的错误

原代码里使用了未声明的user变量,回调函数的参数是member,要获取用户信息需通过member.user对象:

// 发送带用户名的欢迎消息
await member.send(`Hello, ${member.user.username}!`);
// 或者直接@用户
await member.send(`Hello, ${member}!`);

2. 启用服务器成员意图(Discord.js v14+ 必需)

从Discord.js v14版本开始,监听guildMemberAdd事件必须开启服务器成员意图:

  • 进入Discord开发者后台,找到你的机器人应用,在「Bot」页面的「Privileged Gateway Intents」板块,开启「Server Members Intent」。
  • 初始化客户端时添加对应的意图配置:
const { Client, GatewayIntentBits } = require('discord.js');

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers // 必须添加该意图才能监听成员加入事件
  ]
});

3. 添加错误处理逻辑

用户可能关闭了私信权限,导致消息发送失败,建议用try-catch捕获并处理错误:

client.on('guildMemberAdd', async member => {
  try {
    await member.send(`Hello, ${member.user.username}! Welcome to our server!`);
    console.log(`成功给${member.user.username}发送欢迎私信`);
  } catch (error) {
    console.log(`无法给${member.user.username}发送私信:${error.message}`);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:15:22