discord tools | discord handy tools | | Search

The postMessageImageAttachment function is an asynchronous function that posts a message with an image attachment to a Discord channel, using a POST request to the Discord API with a multipart/form-data payload. The function takes four parameters: prompt, buff, channelId, and content, and returns a promise that resolves when the request is complete.

Run example

npm run import -- "create discord message with attachments"

create discord message with attachments

const { safeurl } = importer.import("domain cache tools")
const mime = require('mime-types');
const {requestAuthQ} = importer.import("discord request")


async function postMessageImageAttachment(prompt, buff, channelId, content = 'image/png') {
  return await requestAuthQ({
    headers: {
      'Content-Type': 'multipart/form-data; boundary=boundary123'
    },
    method: 'POST',
    url: `channels/${channelId}/messages`,
    body: `--boundary123
Content-Disposition: form-data; name="payload_json"
Content-Type: application/json

${JSON.stringify({
  content: 'Your ' + (content.includes('image') ? 'image' : content) + ' delivered: *' + prompt + '*',
  attachments: [{
    "id": 0,
    "description": prompt,
    "filename": safeurl(prompt) + '.' + mime.extension(content)
  }],
})}
--boundary123
Content-Disposition: form-data; name="files[0]"; filename="${safeurl(prompt)}.${mime.extension(content)}"
Content-Transfer-Encoding: base64
Content-Type: ${content}

${buff.toString('base64')}
--boundary123--`
  })
}


module.exports = {
  postMessageImageAttachment
}

What the code could have been:

const { safeurl } = require('./domainCacheTools');
const mime = require('mime-types');
const { requestAuthQ } = require('./discordRequest');

/**
 * Posts a message with an image attachment to a Discord channel.
 * 
 * @param {string} prompt - The prompt for the image.
 * @param {Buffer} buff - The image buffer.
 * @param {string} channelId - The ID of the channel to post to.
 * @param {string} [content='image/png'] - The content type of the image.
 * @returns {Promise} The response from the Discord API.
 */
async function postMessageImageAttachment(prompt, buff, channelId, content = 'image/png') {
  // Construct the payload as a JSON string
  const payloadJson = JSON.stringify({
    content: `Your ${content.includes('image')? 'image' : content} delivered: *${prompt}*`,
    attachments: [{
      id: 0,
      description: prompt,
      filename: `${safeurl(prompt)}.${mime.extension(content)}`,
    }],
  });

  // Construct the multipart/form-data body
  const boundary = 'boundary123';
  const body = [
    `--${boundary}`,
    `Content-Disposition: form-data; name="payload_json"`,
    `Content-Type: application/json`,
    '',
    payloadJson,
    `--${boundary}`,
    `Content-Disposition: form-data; name="files[0]"; filename="${safeurl(prompt)}.${mime.extension(content)}"`,
    'Content-Transfer-Encoding: base64',
    `Content-Type: ${content}`,
    '',
    buff.toString('base64'),
    `--${boundary}--`,
  ].join('\n');

  // Make the request
  return await requestAuthQ({
    headers: {
      'Content-Type': `multipart/form-data; boundary=${boundary}`,
    },
    method: 'POST',
    url: `channels/${channelId}/messages`,
    body,
  });
}

module.exports = {
  postMessageImageAttachment,
};

Code Breakdown

Importing Dependencies

const { safeurl } = importer.import('domain cache tools')
const mime = require('mime-types');
const {requestAuthQ} = importer.import('discord request')
  • The code imports dependencies:
    • safeurl from the domain cache tools module.
    • mime from the mime-types package.
    • requestAuthQ from the discord request module.

postMessageImageAttachment Function

async function postMessageImageAttachment(prompt, buff, channelId, content = 'image/png') {
    //...
}
  • The postMessageImageAttachment function is an asynchronous function that takes four parameters:
    • prompt: The prompt for the message.
    • buff: A buffer representing the image attachment.
    • channelId: The ID of the Discord channel to post the message.
    • content: The MIME type of the attachment (defaults to 'image/png').

Function Implementation

return await requestAuthQ({
    //...
})
  • The function uses requestAuthQ to make a POST request to the Discord API to post a message with an image attachment.

Request Body

body: `--boundary123
Content-Disposition: form-data; name="payload_json"
Content-Type: application/json

${JSON.stringify({
    //...
})}
--boundary123
Content-Disposition: form-data; name="files[0]"; filename="${safeurl(prompt)}.${mime.extension(content)}"
Content-Transfer-Encoding: base64
Content-Type: ${content}

${buff.toString('base64')}
--boundary123--`
  • The request body is a multipart/form-data payload with two parts:
    • The first part is a JSON payload with the message content and attachment details.
    • The second part is the image attachment itself, encoded as a base64 string.

Exporting the Function

module.exports = {
    postMessageImageAttachment
}
  • The postMessageImageAttachment function is exported as a module, making it available for use in other parts of the application.