使用discord.js与mineflayer开发机器人遇TypeError问题求助
问题
我用discord.js和mineflayer开发Discord机器人,一直碰到错误:TypeError: Cannot read properties of undefined (reading 'send')。查了好多帖子都没解决,怀疑是discordBot没登录,但不确定具体原因。
代码片段:
import mineflayer from "mineflayer"; import { Client, GatewayIntentBits, Partials, EmbedBuilder } from 'discord.js'; const discordBot = new Client({ intents: [ GatewayIntentBits.DirectMessages, GatewayIntentBits.Guilds, GatewayIntentBits.GuildBans, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ], 'partials': [Partials.Channel, Partials.Message, Partials.User, Partials.GuildMember, Partials.Reaction] }); const options = { host: server, username: ign, auth: 'microsoft' }; const bot = mineflayer.createBot(options); discordBot.login(process.env.token1) discordBot.on('ready', () => { console.log(`The Discord bot ${discordBot.user.username} is ready!`); discordBot.channels.cache.get('987349559724372059').send(`The Discord bot ${discordBot.user.username} is ready!`); }); bot.on('login', () => { console.log('Minecraft bot has logged in!'); }); bot.on('message', async (jsonMsg, position) => { if (jsonMsg != "") return; if (position === 'system') { await discordBot.channels.cache.get('987349559724372059').send(`${jsonMsg}`); } else if (position === 'game_info') { await discordBot.channels.cache.get('987349559724372059').send(`${jsonMsg}`); } });
运行脚本时报错:
Minecraft bot has logged in! file:///home/runner/InGameChat/index.js:138 await discordBot.channels.cache.get('987349559724372059').send(`${jsonMsg}`); ^ TypeError: Cannot read properties of undefined (reading 'send')
解决方案
核心原因:报错说明
discordBot.channels.cache.get('987349559724372059')返回了undefined,主要是两个可能:- Minecraft机器人先完成登录触发了
message事件,但Discord机器人还没完成登录、频道缓存也没加载好,此时找不到目标频道。 - 频道ID错误,或者机器人没有访问该频道的权限。
- Minecraft机器人先完成登录触发了
具体修复步骤:
等Discord机器人就绪后再处理Minecraft消息
加个状态变量标记Discord机器人是否就绪,未就绪时直接跳过消息处理:let discordReady = false; discordBot.on('ready', () => { console.log(`The Discord bot ${discordBot.user.username} is ready!`); discordReady = true; // 这里也加个错误判断,避免就绪时也出错 const channel = discordBot.channels.cache.get('987349559724372059'); if (channel) { channel.send(`The Discord bot ${discordBot.user.username} is ready!`); } else { console.error('找不到目标频道,请检查ID或机器人权限'); } }); bot.on('message', async (jsonMsg, position) => { if (!discordReady) return; if (jsonMsg === "") return; // 建议用严格相等=== const channel = discordBot.channels.cache.get('987349559724372059'); if (!channel) { console.error('无法获取目标频道'); return; } if (position === 'system' || position === 'game_info') { await channel.send(`${jsonMsg}`); } });验证频道ID和机器人权限
- 确认频道ID完全正确,别把服务器ID当成频道ID。
- 检查Discord机器人在目标服务器里是否有
发送消息的权限,同时确保启用了Guilds、GuildMessages这些必要的intents。
改用fetch获取频道(规避缓存问题)
如果缓存里加载不到频道,直接用fetch方法获取更可靠,还能捕获错误:// 在发送消息的地方替换成这段 try { const channel = await discordBot.channels.fetch('987349559724372059'); await channel.send(`${jsonMsg}`); } catch (err) { console.error('获取频道或发送消息失败:', err); }
内容的提问来源于stack exchange,提问作者user19530601
相关产品推荐
相关产品推荐

