問題描述
第二次在 StackOverflow 上發帖,如有錯誤,我深表歉意.請多多包涵.
與標題相同;您如何閱讀不和諧附件的內容,比如 .txt
文件并打印內容?
我嘗試使用 fs
但不幸失敗了,我也搜索了文檔但也失敗了.
想法?
您不能為此使用 fs
模塊,因為它只處理本地文件.當您將文件上傳到 Discord 服務器時,它會被上傳到 CDN,您所能做的就是從
Second time posting on StackOverflow so I apologize for any mistakes. Please bear with me.
Same with the title; How do you read contents of a discord attachment let's say a .txt
file and print the contents?
I have tried with fs
but unfortunately failed and I have also searched the documentation but failed also.
Ideas?
You can't use the fs
module for this as it only deals with local files. When you upload a file to the Discord server, it gets uploaded to a CDN and all you can do is grab the URL of this file from the MessageAttachment
using the url
property.
If you need to get a file from the web, you can fetch it from a URL using the built-in https
module, or you can install one from npm, like the one I used below, node-fetch
.
To install
node-fetch
, runnpm i node-fetch
in your root folder.
Check out the working code below, it works fine with text files:
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);
}
});
這篇關于讀取文件附件(例如;.txt 文件)- Discord.JS的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!