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

如何用Discord.js v14获取Discord服务器文本频道名并生成HTML选择框

使用Discord.js v14获取服务器文本频道并生成HTML选择框选项

一、后端(Discord.js 实现)

先确保机器人拥有ViewChannel权限,且已开启Guilds和GuildChannels意图,以下是获取频道数据的核心代码:

const { Client, GatewayIntentBits, ChannelType } = require('discord.js');
const client = new Client({ 
  intents: [
    GatewayIntentBits.Guilds, 
    GatewayIntentBits.GuildChannels
  ] 
});

client.on('ready', async () => {
  // 替换为目标服务器ID
  const targetGuildId = '你的服务器ID';
  const guild = client.guilds.cache.get(targetGuildId);
  
  if (!guild) {
    console.error('无法定位目标服务器');
    return;
  }

  // 过滤出所有文本频道
  const textChannels = guild.channels.cache.filter(channel => 
    channel.type === ChannelType.GuildText
  );

  // 整理成ID+名称的结构,方便前端调用
  const channelData = textChannels.map(channel => ({
    id: channel.id,
    name: channel.name
  }));

  // 这里通过接口、模板渲染等方式把channelData传给前端即可
  console.log(channelData);
});

client.login('你的机器人Token');

二、前端(生成选择框选项)

假设已从后端拿到channelData数组,直接用JS动态生成选项插入到你已有的选择框中:

<!-- 你已准备好的选择框 -->
<select id="channelSelect"></select>

<script>
// 示例数据,实际从后端获取
const channelData = [
  { id: '123456789', name: 'general' },
  { id: '987654321', name: 'announcements' }
];

const selectBox = document.getElementById('channelSelect');

// 循环生成选项
channelData.forEach(channel => {
  const option = document.createElement('option');
  option.value = channel.id; // 存频道ID,方便后续业务调用
  option.textContent = channel.name; // 显示频道名称
  selectBox.appendChild(option);
});
</script>

额外注意

  • 私有频道需要机器人拥有对应频道的访问权限才能被获取到
  • 如果要按频道类别分组,可以在后端额外获取频道的父分类信息,前端用<optgroup>标签实现分组展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 12:30:05