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

Discord.js机器人入群欢迎/退群欢送功能脚本报错,寻求解决方案

Discord.js 入群/退群消息功能错误修复方案

存在的问题

  • 重复覆盖module.exports:同一个文件内两次为module.exports赋值,后定义的退群事件逻辑会完全覆盖先定义的入群事件逻辑,最终只有退群事件会被注册。
  • 未正确获取频道实例:代码直接将频道ID字符串赋值给channel变量,字符串没有send方法,调用时直接抛出类型错误,需要从客户端或者服务器的频道缓存中获取对应ID的频道对象才能调用发消息方法。
  • 版本适配要求:Discord.js v13及以上版本需要额外开启GUILD_MEMBERS网关意图,同时要在Discord开发者后台的应用设置中开启「服务器成员权限」开关,否则两个成员事件都不会触发。

修正后代码

module.exports = (client) => {
    // 入群欢迎逻辑
    const channelIdA = '718596514305277972'
    client.on('guildMemberAdd', async (member) => {
        console.log("Someone joined the server")
        const messageA = `欢迎${member.user}入群`
        // 从客户端缓存获取频道
        const channel = await client.channels.fetch(channelIdA).catch(err => console.error('获取欢迎频道失败', err))
        if(channel) channel.send(messageA).catch(err => console.error('发送欢迎消息失败', err))
    })

    // 退群欢送逻辑
    const channelIdB = '890891192995303424'
    client.on('guildMemberRemove', async (member) => {
        console.log("Someone left the server")
        const messageB = `${member.user.tag} 离开了服务器`
        const channel = await client.channels.fetch(channelIdB).catch(err => console.error('获取欢送频道失败', err))
        if(channel) channel.send(messageB).catch(err => console.error('发送欢送消息失败', err))
    })
}

额外注意事项

  • 确保机器人对应频道有「发送消息」、「查看频道」的权限,否则发消息会被拒绝。
  • 如果你的机器人在多服务器部署,建议从当前事件触发的member.guild.channels中获取频道,避免跨服务器调用错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 08:45:04