Discord.js 新人欢迎Bot失效求助:无法@用户发送问候
Fixing Your Discord.js Welcome Bot Issues
Let's walk through the problems in your code and fix them step by step:
- Variable name typo: You initialized
const newUser = new Discord.Collection();but usednewUserslater in theguildMemberAddevent. This mismatch breaks the collection's functionality entirely. - Client instance mix-up: You created your bot with
var bot = new Discord.Client();but tried to listen for events onclient(which doesn't exist). Swap that tobot.on("guildMemberAdd", ...)(or rename your bot instance toclientfor consistency). - Outdated channel fetching: In Discord.js v12+,
guild.channels.find()is replaced withguild.channels.cache.find()—channels are stored in a cache now, so the old method won't work. - Missing Gateway Intents (v13+): If you're using Discord.js v13 or higher, you need to enable the
GuildMembersintent in your Discord Developer Portal and pass it when initializing the client. Without this, theguildMemberAddevent won't fire at all. - Extra closing bracket: There's an extra
});beforebot.login(TOKEN);that will throw a syntax error.
Here's the corrected, working version of your code:
const Discord = require("discord.js"); const TOKEN = "private"; const PREFIX = "!"; // Fixed variable name to match usage later const newUsers = new Discord.Collection(); const talkedRecently = new Set(); // For Discord.js v13+, include required intents const client = new Discord.Client({ intents: [ Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MEMBERS ] }); var fortunes = [ "Yes", "No", "Maybe", "IDK" ]; client.on("ready", () => { console.log("Bot is online and ready!"); // Confirm bot is running }); client.on("guildMemberAdd", (member) => { const guild = member.guild; newUsers.set(member.id, member.user); if (newUsers.size > 0) { // Use cache to find a channel the bot can send messages to const defaultChannel = guild.channels.cache.find(c => c.permissionsFor(guild.me).has("SEND_MESSAGES")); const userlist = newUsers.map(u => u.toString()).join(" "); // Clean up line break formatting defaultChannel.send(`Hello Creativistian!\n${userlist}`); newUsers.clear(); } }); client.login(TOKEN);
Quick Extra Tips:
- Don't forget to enable the Server Members Intent in your Discord Developer Portal under your bot's "Privileged Gateway Intents" section—this is mandatory for the
guildMemberAddevent to trigger in v13+. - If you're using an older Discord.js version (v11 or lower), remove the intents block and switch back to
guild.channels.find(). - The
user.toString()method automatically turns the user object into a mention, so once the rest of the code works, the @mention feature will too.
内容的提问来源于stack exchange,提问作者GrowZHax
相关产品推荐
相关产品推荐

