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

如何检测Discord.js机器人被添加至Guild并实现问候功能?

使用Discord.js实现机器人入服问候功能

要实现机器人被添加到Discord服务器时自动发送问候,核心是利用Discord.js的guildCreate事件,以下是具体步骤和代码示例:

1. 基础设置与事件监听

首先确保你已安装Discord.js(推荐v14版本),然后创建客户端实例并监听guildCreate事件——该事件会在机器人成功加入服务器时触发。

const { Client, GatewayIntentBits, ChannelType } = require('discord.js');
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,          // 必须,用于获取服务器相关事件
    GatewayIntentBits.GuildMessages,   // 用于发送频道消息
    GatewayIntentBits.MessageContent   // 若需要读取消息内容则添加
  ]
});

// 监听机器人加入服务器事件
client.on('guildCreate', async (guild) => {
  // 问候逻辑写在这里
});

// 登录机器人
client.login('你的机器人令牌');

2. 定位可发送消息的频道

机器人需要找到一个有权限发送消息的频道,优先选择服务器设置的系统消息频道(通常是默认的欢迎频道),如果没有则自动查找第一个符合条件的文本频道:

client.on('guildCreate', async (guild) => {
  // 尝试获取服务器系统频道
  let targetChannel = guild.systemChannel;

  // 若没有系统频道,查找第一个可发送消息的文本频道
  if (!targetChannel) {
    targetChannel = guild.channels.cache.find(channel => 
      channel.type === ChannelType.GuildText &&
      channel.permissionsFor(guild.members.me).has('SendMessages')
    );
  }

  // 无可用频道则终止
  if (!targetChannel) return;

  // 发送问候消息
  try {
    await targetChannel.send(`嗨!感谢邀请我加入${guild.name}服务器!有任何需求都可以随时召唤我哦~`);
  } catch (err) {
    console.error('发送问候失败:', err);
  }
});

关键注意事项

  • 权限与Intents:在Discord开发者门户的机器人设置中,确保已启用Guilds等必要的Gateway Intents;同时机器人在目标服务器需要拥有发送消息的权限。
  • 版本兼容:如果使用Discord.js v13及以下版本,GatewayIntentBits需要替换为Intents.FLAGS,频道类型常量也需对应调整(如'GUILD_TEXT')。
  • 错误处理:添加try/catch捕获发送消息时的异常(比如权限不足、频道被删除等情况),避免机器人崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:51:03