Discord Bot开发:调用外部文件函数时message未定义的解决方法
解决Discord Bot中「ReferenceError: message is not defined」的问题
错误原因
你的testPing函数直接使用了message变量,但这个变量既未定义也未作为参数传入。更关键的是,Discord Bot发送消息必须依赖已连接的Discord客户端上下文(比如合法的通道对象),直接在index.js顶层调用testPing时,Bot还未完成登录,也没有任何消息/通道上下文,自然会报错。
修改方案
1. 重构testing.js,让函数接收通道对象
将函数改为接收通道对象作为参数,避免依赖未定义的message:
// commands/testing.js export default function testPing(channel, name) { // 返回发送消息的Promise,方便后续获取发送后的消息对象 return channel.send(`Sentence ${name}`); }
2. 修改index.js,确保在Bot上下文内调用函数
必须先完成Bot的初始化、登录,在有合法通道/消息上下文时调用testPing:
// index.js import { Client, GatewayIntentBits } from 'discord.js'; import testPing from './commands/testing.js'; // 初始化客户端,开启必要的意图权限 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent // 读取消息内容必须开启此意图 ] }); // Bot登录成功后触发 client.on('ready', () => { console.log(`已登录:${client.user.tag}`); // 示例1:主动发送消息到指定通道(替换为你的通道ID) const targetChannel = client.channels.cache.get('你的通道ID'); if (targetChannel) { testPing(targetChannel, 'ABC FGH'); } }); // 示例2:响应用户消息触发 client.on('messageCreate', async (message) => { // 忽略Bot自身的消息 if (message.author.bot) return; // 当用户发送!test指令时调用函数 if (message.content === '!test') { // 调用testPing并传入当前消息的通道 const sentMsg = await testPing(message.channel, 'ABC FGH'); // 可以获取发送后的消息变量进行后续处理 console.log('已发送消息内容:', sentMsg.content); } }); // 替换为你的Bot Token,启动Bot client.login('你的Bot令牌');
关键说明
- 发送消息必须依赖Discord客户端提供的通道对象(
channel),不能凭空使用未定义的message变量 - 所有涉及Discord API的操作都必须在Bot完成登录后执行(比如
ready事件、messageCreate事件内) - 如果需要返回变量,直接使用
channel.send()的返回值即可(它是一个Promise,解析后是发送的消息对象)
内容的提问来源于stack exchange,提问作者Lauren
相关产品推荐
相关产品推荐

