TypeScript开发Discord Bot:延迟回复偶现生效致崩溃问题排查
问题原因与修复方案
核心问题:未等待延迟回复完成
interaction.deferReply()是异步操作,你的代码没有用await等待它执行完毕就继续后续逻辑,导致Discord还没创建延迟回复时,你就调用editReply,自然会触发“无法编辑未存在的回复”错误。
修复步骤
- 给
deferReply添加await
必须确保延迟回复创建完成后再执行后续操作,这是解决问题的关键。 - 添加错误处理
免费主机的API请求可能失败,加上try/catch捕获异常,避免机器人崩溃,同时给用户明确反馈。 - 完善边界情况处理
- 避免强制类型断言可能导致的错误
- 处理API返回无图片的情况
修改后的完整代码
export default (client: Client, commandsArray: Array<CommandInterface>) => { commandsArray.push({ name: "image", description: "Sends you a cute axolotl picture from Reddit.", executor: async (interaction: ChatInputCommandInteraction, client: Client) => { try { // 等待延迟回复创建完成 await interaction.deferReply(); // 安全获取频道,避免类型断言出错 if (!interaction.channel || !(interaction.channel instanceof TextChannel)) { return await interaction.editReply("无法获取有效频道,请在文本频道中使用此命令。"); } const channel = interaction.channel; let payload = "?minImages=1&flair=Just Showing Off 😍"; if (channel.nsfw) payload += "&nsfw=1"; const response = await Axios.get("https://axolotlapi.kirondevcoder.repl.co/reddit" + payload); const post = response.data.data[0]; // 检查是否有可用图片资源 const images: Array<ImageInterface> = post?.media?.filter((m: any) => m.kind === "image") || []; if (images.length === 0) { return await interaction.editReply("暂时没找到可爱的钝口螈图片,请稍后再试~"); } const image: string = images[Math.floor(Math.random() * images.length)].url; const embed = new EmbedBuilder() .setTitle(post.title) .setAuthor({ name: `u/${post.author}`, url: `https://reddit.com/u/${post.author}` }) .setURL(post.link) .setTimestamp(post.created_utc * 1000) .setImage(image); await interaction.editReply({ embeds: [embed] }); } catch (error) { console.error("命令执行出错:", error); // 根据延迟状态选择回复方式 if (interaction.deferred) { await interaction.editReply("获取图片失败,请稍后再试~"); } else { await interaction.reply("抱歉,命令执行出错了,请稍后再试~"); } } } }); }
额外说明
免费主机长期未使用会进入休眠状态,导致首次请求缓慢,延迟回复能避免Discord判定命令超时,而await deferReply是确保延迟回复生效的核心前提。
内容的提问来源于stack exchange,提问作者AceKiron
相关产品推荐
相关产品推荐

