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

Discord.js v12 中 guildMemberAdd 事件无法正常运行问题求助

问题排查方向

  • 先验证事件是否触发:首先看控制台有没有输出mudda,如果没有输出,说明guildMemberAdd事件根本没有被触发,优先检查特权意图配置:
    1. 前往Discord开发者平台对应机器人的管理页,找到「Privileged Gateway Intents」板块,开启Server Members Intent
    2. 初始化客户端时必须声明对应意图,示例初始化代码:
    const client = new Discord.Client({
      intents: ['GUILDS', 'GUILD_MEMBERS']
    })
    
  • 如果控制台能输出mudda,说明事件已经触发,问题出在后续逻辑,排查以下几点:
    1. 文件读取路径问题:fs.readFile默认使用运行命令时的工作目录作为相对路径基准,如果你启动脚本的目录和代码文件存储目录不一致,会找不到txt文件报错,建议改为绝对路径,需要先引入path模块:
    const path = require('path')
    // 读文件时替换路径写法
    fs.readFile(path.join(__dirname, 'welcomemessage.txt'), 'utf8', (err, welcomemessage) => {
    
    1. 频道名称匹配失败:读取的welcomechannel内容可能带换行、空格等不可见字符,导致找不到对应频道,建议先做修剪,同时加空值判断避免报错:
    const channel = client.channels.cache.find(channel => channel.name === welcomechannel.trim())
    if (!channel) return console.log('未找到对应欢迎频道')
    
    1. 权限校验:确认机器人在目标欢迎频道拥有「查看频道」「发送消息」权限,否则会发送失败。

修正后参考代码

const fs = require('fs')
const path = require('path')

client.on("guildMemberAdd", member => {
  console.log("mudda")
  fs.readFile(path.join(__dirname, 'welcomemessage.txt'), 'utf8' , (err, welcomemessage) => {
    if (err) {
      console.error('读取欢迎消息文件失败:', err)
      return
    }
    fs.readFile(path.join(__dirname, 'welcomemessagechannel.txt'), 'utf8' , (err, welcomechannel) => {
      if (err) {
        console.error('读取频道配置文件失败:', err)
        return
      }
      const channel = client.channels.cache.find(channel => channel.name === welcomechannel.trim())
      if (!channel) return console.log('未找到匹配的欢迎频道')
      channel.send(welcomemessage).catch(err => console.error('发送欢迎消息失败:', err))
    })
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:08