Discord.js报错TypeError:无法读取undefined的'messages'属性求助
Discord机器人读取频道消息报错解决
我开发Discord机器人时,写了个从频道获取消息的函数,但机器人无法读取消息,报以下错误:
错误栈
An error occurred while trying to fetch the channels: TypeError: Cannot read properties of undefined (reading 'messages') at file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/utils.js:7:88 at Array.map (<anonymous>) at Object.allMessagesFromChannelList (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/utils.js:7:53) at Object.updateServerInfo (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/scheduler.js:6:34) at Timeout._onTimeout (file:///C:/Users/Administrator/Desktop/gb-ac-bot/src/index.js:53:21) at listOnTimeout (node:internal/timers:559:17) at processTimers (node:internal/timers:502:7)
我的utils.js代码
const allMessagesFromChannelList = async (client) => { const channels = global.channels.map(id => client.channels.cache.get(id)) try { const messages = await Promise.all(channels.map(async channel => await channel.messages.fetch({ limit: 50 }))) return messages.map(collection => collection.map(value => value)) .flat() .filter(msg => msg.author.id === global.botId) } catch (error) { console.error('An error occurred while trying to fetch the channels: ', error) return [] } }
报错行(第7行):
const messages = await Promise.all(channels.map(async channel => await channel.messages.fetch({ limit: 50 })))
问题分析
这个错误的核心是channel变量为undefined,也就是client.channels.cache.get(id)没有找到对应的频道。可能的原因有:
global.channels里的频道ID写错了,或者对应的频道已被删除、机器人无权限访问- 机器人权限不足,没有
查看频道或读取消息历史的权限 - 频道不在机器人本地缓存中,
cache.get()无法获取数据
解决步骤
1. 先过滤无效频道,避免报错
先把channels数组里的undefined过滤掉,防止后续调用channel.messages时出错:
const channels = global.channels.map(id => client.channels.cache.get(id)).filter(channel => channel);
2. 检查频道ID和机器人权限
- 核对
global.channels里的每个ID,确保这些频道确实存在,且机器人已加入对应服务器 - 前往Discord开发者门户,确认机器人开启了
Read Message History和View Channels权限,邀请机器人到服务器时要勾选这些权限
3. 改用API拉取频道(不依赖缓存)
如果频道不在缓存里,cache.get()会返回undefined,可以改用client.channels.fetch()直接从Discord API拉取频道:
const allMessagesFromChannelList = async (client) => { let channels; try { // 逐个拉取频道,过滤掉无法获取的 channels = await Promise.all(global.channels.map(async id => { try { return await client.channels.fetch(id); } catch (err) { console.warn(`频道 ${id} 无法获取:`, err); return null; } })); channels = channels.filter(channel => channel); } catch (err) { console.error('获取频道列表失败:', err); return []; } try { const messages = await Promise.all(channels.map(async channel => { // 额外判断:确保是文本频道,避免语音/论坛等不支持消息的频道 if (channel.type !== 0) { // Discord.js v14及以上用ChannelType.GuildText console.warn(`频道 ${channel.id} 不是文本频道,跳过`); return []; } return await channel.messages.fetch({ limit: 50 }); })); return messages.map(collection => collection.map(value => value)) .flat() .filter(msg => msg.author.id === global.botId); } catch (error) { console.error('获取消息时出错:', error); return []; } }
注:Discord.js v14及以上版本,频道类型判断要用
ChannelType.GuildText,需先导入{ ChannelType } from 'discord.js'
4. 确认机器人的intents设置
如果是Discord.js v13+,需要在客户端初始化时启用必要的intents,比如Guilds、GuildMessages、MessageContent:
const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] });
内容的提问来源于stack exchange,提问作者Klein
相关产品推荐
相关产品推荐

