Discord Bot运行报ReferenceError: client is not defined错误求助
错误原因
你遇到的ReferenceError: client is not defined报错是因为代码中直接调用了client.on方法,但从未提前声明、初始化过client这个Discord Bot客户端实例,程序运行时找不到对应变量就会抛出该错误。
修复操作步骤
- 首先确保项目已安装discord.js依赖,未安装的话在项目根目录运行命令:
npm install discord.js - 在你现有代码的最上方,添加Discord客户端初始化代码(以下为discord.js v14版本写法,是目前主流的稳定版本):
const { Client, GatewayIntentBits } = require('discord.js'); // 初始化客户端并开启必要的权限意图 const client = new Client({ intents: [ GatewayIntentBits.Guilds, // 服务器访问权限 GatewayIntentBits.GuildMessages, // 服务器消息访问权限 GatewayIntentBits.MessageContent, // 消息内容读取权限 GatewayIntentBits.GuildMembers // 服务器成员访问权限 ] }); // 替换为你自己在Discord开发者平台获取的Bot令牌 const BOT_TOKEN = "你的Bot令牌";
- 调整事件监听名称:discord.js v14已废弃旧的
message事件,需将你代码里的client.on("message", (msg) => {修改为client.on("messageCreate", (msg) => {,否则无法正常监听到消息 - 在你现有全部代码的最末尾,添加Bot登录代码:
client.login(BOT_TOKEN);
- 额外适配注意项:
- 前往Discord开发者平台的Bot设置页,打开Message Content Intent开关,否则Bot无法读取消息内容,所有消息触发命令都会失效
- 将
!clearRatelimits命令逻辑中的your id替换为你自己的Discord用户ID,否则你无法调用该清空限速的命令 - 若使用discord.js v13及更早版本,初始化和事件写法略有差异,可自行对应调整
完整修复后参考代码
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers ] }); const BOT_TOKEN = "你的Bot令牌"; let ratelimits = []; client.on("messageCreate", (msg) => { // APPLYING RATELIMITS const appliedRatelimit = ratelimits.find( (value) => value.user === msg.author.id && value.channel === msg.channel.id ); if (appliedRatelimit) { // Can they post the message? const canPostMessage = msg.createdAt.getTime() - appliedRatelimit.ratelimit >= appliedRatelimit.lastMessage; // They can if (canPostMessage) return (ratelimits[ ratelimits.indexOf(appliedRatelimit) ].lastMessage = msg.createdAt.getTime()); // They can't msg.delete({ reason: "Enforcing ratelimit." }); } // SET RATELIMIT if (msg.content === "!ratelimit") { // Checking it's you if (msg.author.id !== "705923685877415979") return msg.reply("ok."); // You can change these values in function of the received message const targetedUserId = "529395455109627925"; const targetedChannelId = msg.channel.id; const msRateLimit = 25000; // 25 seconds // Delete existant ratelimit if any for this user on this channel ratelimits = ratelimits.filter( (value) => !( value.user === targetedUserId && value.channel === targetedChannelId ) ); // Add ratelimit ratelimits.push({ user: targetedUserId, channel: targetedChannelId, ratelimit: msRateLimit, lastMessage: 0, }); } // CLEAR RATELIMITS if (msg.content === "!clearRatelimits") { // Checking it's you if (msg.author.id !== "替换为你自己的用户ID") return msg.reply("You can't do that."); // Clearing all ratelimits ratelimits = []; } }); client.login(BOT_TOKEN);
内容的提问来源于stack exchange,提问作者Fluxility
相关产品推荐
相关产品推荐

