#How to save images inside a local storage?
92 messages · Page 1 of 1 (latest)
thats not how i told you to fetch
nor is MessageAttachment v14
Sorry but it's very complicated for me without an example etc.
Do I need to read all of them?
That's sooo much
if you want it to work yes
put some effort in
It's like a different language to me
I don't understand the terms there
Could you at least tell me which block I should read?
okay thanks
I'll come back when I finish reading it
I swear by god that I understood nothing from it
I don't even know what you want me to use as an option
Looking at this example means.... nothing to me, I don't understand what I should do different in my codejs const myInit = { method: "GET", headers: myHeaders, mode: "cors", cache: "default", };
Please just tell me what i need to use there, this is waaaay too complex for a beginner
That thing had 20+ terms that I saw for the first time and didn't understand what they do
then maybe dont try something that complex if you cant understand it
downloading a file from a discord message is this complex?
for you apparently
i woudl recommend searching some guides on how to use node:fetch
😖
okay
- the package you're using has not listed "rar" as one of its formats
- it is a attachment, you can get a
.urlto fetch - it has changed to
AttachmentBuilder
Thank you very much ❤️
A question about the 2nd one
I watched some lessons after wolvinny's advise but still didn't understand what to use as option for fetch since I couldn't find any examples in discord.js
Do I need to use options?
options is for a customised request, discord CDN won't care much lol you can ignore it, like wolvinny said; its optional
Then why did I have to read that doc that made everything the more complicated for me 😖
Thanks a lot ❤️
I also looked at some docs about fs etc. and came up with two different ways
Could you please give me feedback and tell me what I'm doing wrong or could do better?
My Code + Error
Help from you is also very welcome 
I just want to get over with this thing 🙂
I got stuck with this for eternity it feels like
attachment.fetch()?
I don’t think that’s a function…?
const data = await fetch(someURL)
const buffer = await data.arrayBuffer()
Will work for an arrayBuffer(), fetch is native for node versions > v18 or something
Oh I’m stupid forget that I see the code at the bottom
Try using native fetch rather then node-fetch. Other then that sorry that I didn’t see the other code haha
use the second part, without wrapping it in another async function. writeFile is an asynchronous function
instead of
const files = attachments.map(...);
for (const file of files) {...}
you can also use
for (const [id, attachment] of attachments) {...}
if you'd like to
native fetch is still experimental ig
But won't that give error for arrayBuffer()?
I need to await that no?
Just use writeFileSync then
Ig you are not very familiar with promises

You can await them
They are already inside a async function
Type 'Promise<ArrayBuffer>' is missing the following properties from type 'DataView': buffer, byteLength, byteOffset, getFloat32, and 19 more.ts(2345)
const buffer: Promise<ArrayBuffer>```
I still get the same error for buffer
import fs from "fs";
import fetch from "node-fetch";
import path from "path";
import { Message } from "discord.js";
export default async function saveImages(message: Message<true>) {
// Primary --------------------------------------------------------------------------------------
const { channel, attachments, content } = message;
try {
if (channel.id !== "1148740978170146948") return;
if (!content.includes("!ns")) return;
if (message.attachments.size <= 0) return;
// Second
const imageURLs = attachments.map((image) => image.url);
const filePath = "./some_folder/images.zip";
async function downloadAttachmentTwo(imageURLs: string[], filePath: string) {
//
for (const imageURL of imageURLs) {
//
const response = await fetch(imageURL);
const buffer = await response.arrayBuffer();
const directoryPath = path.dirname(filePath);
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath, { recursive: true });
}
fs.writeFileSync(filePath, buffer, () => console.log("Attachment saved successfully!"));
//
}
}
return downloadAttachmentTwo(imageURLs, filePath);
//
} catch (error) {
console.log(error);
}
}
await the buffer too
You mean this? response.arrayBuffer();
Yes
because if yes it's still teh same
The type error?
import fs from "fs";
import fetch from "node-fetch";
import path from "path";
import { Message } from "discord.js";
export default async function saveImages(message: Message<true>) {
// Primary --------------------------------------------------------------------------------------
const { channel, attachments, content } = message;
try {
if (channel.id !== "1148740978170146948") return;
if (!content.includes("!ns")) return;
if (message.attachments.size <= 0) return;
// Second
const imageURLs = attachments.map((image) => image.url);
const filePath = "./some_folder/images.zip";
async function downloadAttachmentTwo(imageURLs: string[], filePath: string) {
//
for (const imageURL of imageURLs) {
//
const response = await fetch(imageURL);
const buffer = await response.arrayBuffer();
const directoryPath = path.dirname(filePath);
if (!fs.existsSync(directoryPath)) {
fs.mkdirSync(directoryPath, { recursive: true });
}
fs.writeFileSync(filePath, buffer, () => console.log("Attachment saved successfully!"));
//
}
}
return downloadAttachmentTwo(imageURLs, filePath);
//
} catch (error) {
console.log(error);
}
}
``````Argument of type 'ArrayBuffer' is not assignable to parameter of type 'string | ArrayBufferView'.
Type 'ArrayBuffer' is missing the following properties from type 'DataView': buffer, byteOffset, getFloat32, getFloat64, and 18 more.ts(2345)
const buffer: ArrayBuffer```
I didn't get any Type error since I'm not running this code yet
I get this underlining from TS though
is there an alternative buffer for this maybe?
Something else than .arrayBuffer()
I don't really know
Need to read
I can't believe it's this hard to save an image in local storage 😦
Is that all you’re trying to do?
Yes
When images get sent
I want my bot to store each image inside a zip folder (local)
But I couldn't find any examples of it
and without examples I jsut can't do anything
I can't learn without examples 😦
U wrote a function for that a while back
Let me see if I can find
I*
Me?

I really don't remember
I* typo
Oh you okay
That would be very very nice
I'm stuck at this since a couple days 🙂
it's not, im just too new for this lol but somewhere its possible
❤️ Ty for the help though
a zip? won't you have to append all images for every new image you would fetch?
You don’t need to use a zip file lol
Yeah it actually doesn't have to be a zip
I just want to store the images inside a local storage
that's all
But @lofty socket
I'm hosting my but most of the time on a server
Will that local storage work even then?

ty
I'll try it
the guy has used a separate lib for determining the extension which a discord attachment already has, so you must skip that part
I can’t seem to find it, but I know I used native fetch and then just .arrayBuffer() it
Thanks, I'm trying it rn
It works... finally 🙂
Here is the code of someone else needs it in the future:
import fs from "fs";
import fetch from "node-fetch";
import { Message } from "discord.js";
export default async function saveImages(message: Message<true>) {
// Primary --------------------------------------------------------------------------------------
const { channel, attachments, content } = message;
function hasAttachment() {
console.log("Checking attachment...");
if (message.attachments.size > 0) {
console.log("Attachment detected.");
return true;
} else {
console.log("Unable to detect any attachments.");
return false;
}
}
try {
if (channel.id !== "1148740978170146948") return;
if (!content.includes("!ns")) return;
if (!hasAttachment()) return;
async function savePhotoFromAPI() {
//
const urls = attachments.map((attachment) => attachment.url);
for (const url of urls) {
//
const response = await fetch(url);
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
if (url.includes(".png") || url.includes(".jpg")) {
//
const ext = url.includes(".png") ? ".png" : ".jpg";
let i = 1;
let outputFileName = `testSaveImages${ext}`;
while (fs.existsSync(outputFileName)) {
outputFileName = `testSaveImages_${i}${ext}`;
i++;
}
fs.createWriteStream(outputFileName).write(buffer);
//
return Promise.resolve("Attachement has been saved?");
} else {
return Promise.reject(
"File type could not be reliably determined! The binary data may be malformed! No file saved!"
);
}
}
}
await savePhotoFromAPI()
.then((msg) => console.log(msg))
.catch((msg) => console.log(msg));
//
} catch (error) {
console.log(error);
}
}
How to save images inside a local storage?
I found what I done before,
async function savefile(url) {
await fetch(url).then(async (res) => {
const d = await res.arrayBuffer();
const buffer = Buffer.from(d);
const type = res.headers.get('Content-Type')?.split('/')?.[1]
const { writeFile } = require('node:fs');
writeFile('filename' + type, buffer, { encoding: 'base64' }, function (err) {
if(err) throw err;
console.log('done')
})
})
}
the type was from the headers but idk how you get the name but that's down to your discretion with how you wanna handle that tbf
Oh
Thanks for the example