Discord频道创建机器人开发:!addclass命令实现及报错解决
Fixing Your Class Channel Creation Discord Bot
Hey there! Let's work through the issues in your code and get that channel creation bot working properly. The main error you're seeing (TypeError: Cannot read property 'create' of undefined) comes from how you're trying to access the guild object, plus a few other logic and timing issues.
Key Issues in Your Current Code
- Invalid Guild Reference: You set
const guild = 'guildToken';which is just a string, not an actual Guild object. You can't callchannels.create()on a string. - Nested Message Listeners: You're adding a new
messageevent listener every time someone runs!addclass—this will cause duplicate handlers and unexpected behavior. - Early Channel Fetch: You try to get
adminchannelbefore the client is ready, so the channel cache isn't populated yet. - No Request Tracking: There's no way to link an admin's
!yes/!noto the specific class request they're responding to, which will break if multiple requests come in.
Corrected Code
Here's a revised version of your bot that fixes all these issues:
const Discord = require('discord.js'); const Client = new Discord.Client(); const token = 'bottoken'; const GUILD_ID = 'guildToken'; // Store guild ID as a constant const ADMIN_CHANNEL_ID = 'adminchanneltoken'; const ADDCLASS_CHANNEL_ID = 'addclasschanneltoken'; const PREFIX = '!'; // Store pending class requests (maps message IDs to class names) const pendingRequests = new Map(); Client.on('ready', () => { console.log('This Client is online!'); }); Client.on('message', async message => { // Ignore bots to prevent loops if (message.author.bot) return; const args = message.content.substring(PREFIX.length).split(' '); const command = args[0].toLowerCase(); // Handle !addclass command if (command === 'addclass') { // Only allow this command in the designated channel if (message.channel.id !== ADDCLASS_CHANNEL_ID) return; const newClassName = args[1]; if (!newClassName) { return message.reply('Please provide a class name! Usage: `!addclass <班级名称>`'); } // Send request to admin channel const adminChannel = Client.channels.cache.get(ADMIN_CHANNEL_ID); if (!adminChannel) { return message.reply('Admin channel not found!'); } const adminMessage = await adminChannel.send( `Someone wants to add "${newClassName}" as a class channel.\nReply with \`!yes\` to approve or \`!no\` to reject.` ); // Store the request linked to the admin message ID pendingRequests.set(adminMessage.id, newClassName); } // Handle admin approval/rejection if (message.channel.id === ADMIN_CHANNEL_ID) { if (command === 'yes' || command === 'no') { // Get the previous message (the request message) const previousMessage = await message.channel.messages.fetch({ limit: 2 }).then(messages => messages.last()); const className = pendingRequests.get(previousMessage.id); if (!className) { return message.reply('This is not linked to any pending class request!'); } if (command === 'yes') { // Get the guild object correctly const guild = Client.guilds.cache.get(GUILD_ID); if (!guild) { return message.reply('Guild not found!'); } // Create the new channel try { await guild.channels.create(newClassName, { // Optional: Set channel type, permissions, etc. type: 'text' // Default is text, you can change to 'voice' if needed }); message.reply(`Successfully created channel "${newClassName}"!`); } catch (error) { console.error(error); message.reply('Failed to create the channel. Check bot permissions!'); } } else if (command === 'no') { message.reply(`Rejected request to create channel "${className}".`); } // Remove the request from pending pendingRequests.delete(previousMessage.id); } } }); Client.login(token);
What Changed?
- Proper Guild Fetch: We now get the actual Guild object using
Client.guilds.cache.get(GUILD_ID), which lets us callchannels.create()correctly. - Single Message Listener: All commands are handled in one
messageevent listener, avoiding duplicate bindings. - Pending Request Tracking: We use a
Mapto link admin request messages to class names, so we know which request an admin is responding to. - Timing Fixes: We fetch channels and messages only when needed (after the client is ready), and add checks to handle cases where channels/guilds aren't found.
- Error Handling: Added try/catch for channel creation and checks for missing arguments or invalid requests.
- Bot Ignore: We ignore messages from bots to prevent the bot from responding to itself.
Make sure your bot has the Manage Channels permission in the guild, otherwise channel creation will fail!
内容的提问来源于stack exchange,提问作者Evan Jones
相关产品推荐
相关产品推荐

