Discord机器人调用message.edit报错:Edit is not a function
问题分析与修复方案
报错原因
你遇到的message.edit is not a function错误,核心原因是channel.send()方法返回的是Promise对象,而非你预期的Discord Message实例。你直接将Promise赋值给message变量,后续调用message.edit()时,Promise对象并没有这个方法,因此抛出错误。
修复步骤
要解决这个问题,必须等待channel.send()的Promise完成,获取到真正的Message实例后再进行后续编辑操作。以下是两种可行的修复方式:
方式一:使用async/await(推荐,代码更简洁)
确保外层函数为async函数,通过await等待Promise解析:
async function initBotMessage(channel) { let message; if (isTextChannel(channel) && !isStageChannel(channel)) { // 等待消息发送完成,拿到真正的Message对象 message = await channel.send({ embeds: [playerCountEmbedLoading()] }); } setInterval(async () => { // 额外判断message是否存在,避免未初始化时调用edit if (isTextChannel(channel) && !isStageChannel(channel) && message) { await message.edit({ embeds: [playerCountEmbed()] }); } }, 1000); // 根据需求设置合理的更新间隔,单位ms }
方式二:使用Promise的.then()方法
如果无法使用async/await(比如代码不在异步函数中),可以通过.then()处理Promise的回调:
let message; if (isTextChannel(channel) && !isStageChannel(channel)) { channel.send({ embeds: [playerCountEmbedLoading()] }) .then(sentMessage => { message = sentMessage; setInterval(() => { if (isTextChannel(channel) && !isStageChannel(channel) && message) { message.edit({ embeds: [playerCountEmbed()] }); } }, 1000); }) .catch(error => console.error('发送初始消息失败:', error)); }
额外注意事项
- 必须确保
message变量在调用edit()前已被正确赋值,因此在setInterval的判断逻辑中加入&& message,避免因消息发送失败导致的undefined调用错误。 - 注意Discord API的调用频率限制,不要设置过短的更新间隔,避免触发限流。
内容的提问来源于stack exchange,提问作者Chpsterz
相关产品推荐
相关产品推荐

