Discord.js v13机器人:存储频道ID及限定频道指令的代码示例
Discord.js v13 频道权限指令实现方案
核心逻辑
- 用内存数组(或数据库)存储允许执行特定指令的频道ID
- 第一个指令用于将当前频道ID加入授权列表
- 第二个指令添加前置校验,仅在授权频道内触发
代码示例
const { Client, Intents } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }); // 存储授权频道ID的数组(重启机器人会丢失,生产环境建议用数据库持久化) let authorizedChannels = []; const PREFIX = '!'; client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); }); client.on('messageCreate', async message => { if (message.author.bot) return; if (!message.content.startsWith(PREFIX)) return; const args = message.content.slice(PREFIX.length).trim().split(/ +/); const command = args.shift().toLowerCase(); // 指令1:设置授权频道(仅管理员可执行) if (command === 'setchannel') { if (!message.member.permissions.has('ADMINISTRATOR')) { return message.reply('你没有权限执行此指令!'); } const channelId = message.channel.id; if (!authorizedChannels.includes(channelId)) { authorizedChannels.push(channelId); message.reply(`已将频道 <#${channelId}> 加入授权列表!`); } else { message.reply('该频道已在授权列表中!'); } } // 指令2:仅授权频道可用的受限指令 else if (command === 'restrictedcmd') { if (!authorizedChannels.includes(message.channel.id)) { return message.reply('此指令仅能在授权频道中使用!'); } // 这里写入受限指令的具体功能逻辑 message.reply('你在授权频道中成功执行了受限指令!'); } }); // 替换为你的机器人Token client.login('YOUR_BOT_TOKEN');
补充说明
- 内存存储的
authorizedChannels会在机器人重启后清空,生产环境推荐使用SQLite、MongoDB等数据库持久化数据 - 可根据需求调整
!setchannel的权限要求,比如改为仅服务器所有者可用 - 可扩展指令集,例如添加
!removechannel移除授权频道、!listchannels查看所有授权频道
内容的提问来源于stack exchange,提问作者GEYO 5
相关产品推荐
相关产品推荐

