Reading file attachments (Ex; .txt file) - Discord.JS(读取文件附件(例如;.txt 文件)- Discord.JS)
问题描述
第二次在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:读取文件附件(例如;.txt 文件)- Discord.JS


基础教程推荐
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01