求助:Discord机器人同服务器跨频道发消息遇fetch/cache未找到错误
Discord机器人跨频道发送消息的实现方案
问题背景
当Discord机器人返回结果(response)的条目数大于1时,需要向同一服务器的指定频道发送消息,但尝试跨频道发送时出现fetch not being found或cache not being found错误。当前代码仅能向命令发起频道发送消息,代码片段如下:
if(response.length > 1) { let returnMessage = 'Items found: " + response.length; for(let i = 0; i < response.length; i++) { let responseString = response[i].toString(); returnMessage += "\r\n" + responseString.substring(responseString.indexOf('/', 10)); } // send message to another channel here message.channel.send("test message"); // this sends the message to the current channel. }
解决步骤
1. 修复代码语法错误
原代码中returnMessage的字符串拼接存在引号不匹配问题,会直接导致语法报错,先修正:
// 用模板字符串更简洁直观 let returnMessage = `Items found: ${response.length}`; // 也可以用双引号拼接:let returnMessage = "Items found: " + response.length;
2. 正确获取目标频道
错误核心是获取目标频道的方式不正确,以下是两种可靠的实现方式(以Discord.js v14+为例):
方式一:通过fetch获取(不依赖缓存,推荐)
fetch是异步方法,需用await调用,确保代码在async函数内执行:
// 替换成你的目标频道ID const TARGET_CHANNEL_ID = '123456789012345678'; const targetChannel = await message.guild.channels.fetch(TARGET_CHANNEL_ID);
方式二:从缓存获取(需确保缓存启用)
如果机器人配置了频道缓存(未禁用GuildChannels缓存),可直接从缓存中获取:
const TARGET_CHANNEL_ID = '123456789012345678'; const targetChannel = message.guild.channels.cache.get(TARGET_CHANNEL_ID);
注意:若缓存未启用,此方法会返回
undefined,此时优先使用fetch方式。
3. 验证并发送消息
获取频道后,先验证频道是否存在且支持文本消息发送,再执行发送逻辑:
if (targetChannel && targetChannel.isTextBased()) { await targetChannel.send(returnMessage); } else { console.error('无法发送消息:目标频道不存在或不支持文本消息'); }
4. 确认机器人权限
机器人需要在目标频道拥有SendMessages权限,否则会发送失败。检查机器人的角色权限配置,确保权限正确。
修改后的完整代码
if(response.length > 1) { // 修复字符串拼接错误 let returnMessage = `Items found: ${response.length}`; for(let i = 0; i < response.length; i++) { let responseString = response[i].toString(); returnMessage += "\r\n" + responseString.substring(responseString.indexOf('/', 10)); } // 跨频道发送逻辑 const TARGET_CHANNEL_ID = '替换成你的目标频道ID'; try { const targetChannel = await message.guild.channels.fetch(TARGET_CHANNEL_ID); if (targetChannel && targetChannel.isTextBased()) { await targetChannel.send(returnMessage); } else { console.error('目标频道不可用'); } } catch (error) { console.error('获取目标频道失败:', error); } // 保留原有的当前频道发送逻辑(按需保留) message.channel.send("test message"); }
内容的提问来源于stack exchange,提问作者Russ
相关产品推荐
相关产品推荐

