第二次在 StackOverflow 上发帖,对于任何错误我深表歉意。
请多多包涵。
与标题相同;您如何阅读不和谐附件的内容比方说.txt
文件并打印内容?
我尝试过fs
但不幸的是失败了,我也搜索了文档但也失败了。
Ideas?
你不能使用fs
模块,因为它只处理本地文件。当您将文件上传到 Discord 服务器时,它会被上传到 CDN,您所能做的就是从MessageAttachment https://discord.js.org/#/docs/main/stable/class/MessageAttachment使用url
财产。
如果您需要从网络获取文件,您可以使用内置的 URL 从 URL 获取它https
模块,或者你可以从 npm 安装一个,就像我下面使用的那样,node-fetch https://www.npmjs.com/package/node-fetch.
安装node-fetch
, run npm i node-fetch
在你的根文件夹中。
查看下面的工作代码,它可以很好地处理文本文件:
const { Client } = require('discord.js');
const fetch = require('node-fetch');
const client = new Client();
client.on('message', async (message) => {
if (message.author.bot) return;
// get the file's URL
const file = message.attachments.first()?.url;
if (!file) return console.log('No attached file found');
try {
message.channel.send('Reading the file! Fetching data...');
// fetch the file from the external URL
const response = await fetch(file);
// if there was an error send a message with the status
if (!response.ok)
return message.channel.send(
'There was an error with fetching the file:',
response.statusText,
);
// take the response stream and read it to completion
const text = await response.text();
if (text) {
message.channel.send(`\`\`\`${text}\`\`\``);
}
} catch (error) {
console.log(error);
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)