如何在discord.js v14中发送处理后的文本作为文件附件?
实现修改后文本以附件发送的方案
核心思路
先将处理后的文本写入临时文件,再通过对应消息客户端的附件接口发送该文件,发送完成后清理临时文件避免冗余。
具体代码实现
1. 引入必要模块
基于你已使用的request库,补充文件系统和路径处理模块,同时根据你所用的消息框架(如Discord.js、Telegram Bot API等)引入对应工具:
const fs = require('fs'); const path = require('path'); const request = require('request');
2. 处理文本并发送附件
在获取到原文件文本后,完成处理逻辑,生成临时文件并发送:
request(url, {json: false}, (err, res, body) => { if (err) {return msg.reply("There was an error getting the file")} // 替换为你的文本处理逻辑,比如内容替换、格式调整等 const processedText = body.replace(/placeholder/g, 'replaced-content'); // 生成唯一临时文件路径(可搭配uuid避免文件名冲突) const tempFilePath = path.join(__dirname, 'temp-processed.txt'); // 写入处理后的文本到临时文件 fs.writeFile(tempFilePath, processedText, (writeErr) => { if (writeErr) { return msg.reply("Failed to create processed file"); } // 以Discord.js为例发送附件 msg.reply({ content: "处理完成,这是修改后的文件:", files: [tempFilePath] }).then(() => { // 发送成功后删除临时文件 fs.unlink(tempFilePath, (unlinkErr) => { if (unlinkErr) console.error("Failed to delete temp file:", unlinkErr); }); }).catch(sendErr => { msg.reply("Failed to send processed file"); // 发送失败也要清理临时文件 fs.unlink(tempFilePath, (unlinkErr) => { if (unlinkErr) console.error("Failed to delete temp file:", unlinkErr); }); }); }); });
3. 适配不同消息框架的发送逻辑
- Telegram Bot API(node-telegram-bot-api):
bot.sendDocument(msg.chat.id, tempFilePath, { caption: "处理完成,这是修改后的文件:" }).then(() => fs.unlink(tempFilePath, err => err && console.error(err)));
- Slack Bot(@slack/web-api):
const { WebClient } = require('@slack/web-api'); const web = new WebClient(process.env.SLACK_TOKEN); web.files.upload({ channels: msg.channel, file: fs.createReadStream(tempFilePath), filename: 'processed-file.txt', initial_comment: "处理完成,这是修改后的文件:" }).then(() => fs.unlink(tempFilePath, err => err && console.error(err)));
关键注意事项
- 若存在并发请求,建议用
uuid生成唯一文件名,避免临时文件被覆盖:
const { v4: uuidv4 } = require('uuid'); const tempFilePath = path.join(__dirname, `${uuidv4()}-processed.txt`);
- 无论发送成功或失败,都要执行临时文件清理,防止服务器磁盘占用过高。
内容的提问来源于stack exchange,提问作者Haloxx
相关产品推荐
相关产品推荐

