Is it possible to add local files as attachments? #56
Unanswered
Sapphire-May
asked this question in
Q&A
Replies: 2 comments
-
If you're getting error like or you can also use with ES Module; I don't know how to do this, but i think you're on right path. |
Beta Was this translation helpful? Give feedback.
0 replies
-
I tried like this but... i can't sent with my token, i get // Node Modules
const fetch = require('node-fetch');
const fs = require('fs');
const FormData = require('form-data')
// Usage
const channelOrThreadId = '1234567890987654321'; // Replace with the ID of the channel you want to send the message to
const imageFilePath = './filename.png'; // Replace with the path to the file you want to send
const token = 'ENTER_YOUR_TOKEN_HERE' // Your Discord Token
// Function to send a message with a local file
async function sendMessageWithFile(channelOrThreadId, message, imageFilePath) {
const fileStream = fs.createReadStream(imageFilePath); // Create a stream to read the file
const formData = new FormData()
formData.append('payload_json', JSON.stringify({
content: message
})); // Add JSON data to send your message
formData.append('file', fileStream); // Add file to form data
const response = await fetch(`https://discord.com/api/v9/channels/${channelOrThreadId}/messages`, {
method: 'POST',
headers: {
Authorization: `Bot ${token}`,
...formData.getHeaders() // Add header information of form data
},
body: formData // Use form data as body
});
const data = await response.json();
return data;
}
// Sending
sendMessageWithFile(channelOrThreadId, 'Here is a local file:', imageFilePath)
.then(sentMessage => {
console.log('Message sent:', sentMessage);
})
.catch(error => {
console.error('Error sending message:', error);
}); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm using node.js. I've been trying this for hours and the files never show, even though urls do. I've tried a couple of different methods such as AttachmentBuilder, but this is the one I ended up on.
Beta Was this translation helpful? Give feedback.
All reactions