discord tools | | discord notebook connector | Search

The doDiscordPdf function is an asynchronous module that generates a temporary PDF, patches a Discord interaction's image attachment with the PDF, and updates the interaction with an error message if the PDF creation fails. It utilizes various external libraries and Node.js modules, including discord api, collect all bookmarks, browser crawler tools, and domain cache tools, to retrieve a cache, perform a browser request, and interact with the file system.

Run example

npm run import -- "discord pdf converter"

discord pdf converter

const os = require('os')
const fs = require('fs')
const {updateInteraction} = importer.import("discord api")
const {savePdf} = importer.import("collect all bookmarks")
const {patchInteractionImageAttachment} = importer.import("update discord interaction with attachments")
const {doBrowserRequest} = importer.import("browser crawler tools")
const {
  safeurl,
  existingCache,
  storeCache,
  readCache,
} = importer.import("domain cache tools")

const TEMP_DIR = os.tmpdir();
let counter = 0

async function doDiscordPdf(interaction) {
  // overwrite old pdfs, just for API, should transfer in memory directly, but oh well
  const cache = existingCache(interaction.data.options[0].value, false)
  const filename = path.join(TEMP_DIR, 'temporary_discord_pdf_' + (counter % 4) + '.pdf')
  if(fs.existsSync(filename))
    fs.unlinkSync(filename)
  counter++
  await doBrowserRequest(interaction.data.options[0].value, 
    readCache.bind(null, cache),
    storeCache.bind(null, cache),
    savePdf.bind(null, filename))
  if(fs.existsSync(filename)) {
    return await patchInteractionImageAttachment(interaction.data.options[0].value, fs.readFileSync(filename), interaction.token, 'application/pdf')
  } else {
    return await updateInteraction('Page saving failed: ' + interaction.data.options[0].value, interaction.id, interaction.token)
  }
}

module.exports = {
  doDiscordPdf
}

What the code could have been:

// Import required modules and tools
const os = require('os');
const fs = require('fs').promises; // Use promises for a more modern API
const { updateInteraction, patchInteractionImageAttachment } = require('discord-api');
const { savePdf } = require('collect-all-bookmarks');
const { doBrowserRequest } = require('browser-crawler-tools');
const { safeurl, existingCache, storeCache, readCache } = require('domain-cache-tools');
const path = require('path');

// Define constants
const TEMP_DIR = os.tmpdir();

// Initialize counter
let counter = 0;

/**
 * Creates a PDF from a given URL and sends it as an attachment to Discord.
 * 
 * @param {object} interaction - Discord interaction object.
 * @returns {Promise} Updated Discord interaction with the PDF attachment.
 */
async function doDiscordPdf(interaction) {
  try {
    // Get cache data
    const cache = existingCache(interaction.data.options[0].value, false);
    
    // Create temporary PDF file
    const filename = path.join(TEMP_DIR, `temporary_discord_pdf_${counter % 4}.pdf`);
    await fs.unlink(filename); // Remove existing file
    counter++;
    
    // Fetch PDF from URL
    await doBrowserRequest(interaction.data.options[0].value, readCache.bind(null, cache), storeCache.bind(null, cache), savePdf.bind(null, filename));
    
    // If PDF file exists, send it as an attachment
    if (await fs.access(filename)) {
      return await patchInteractionImageAttachment(interaction.data.options[0].value, await fs.readFile(filename), interaction.token, 'application/pdf');
    } else {
      // Return an error if PDF file doesn't exist
      return await updateInteraction(`Page saving failed: ${interaction.data.options[0].value}`, interaction.id, interaction.token);
    }
  } catch (error) {
    // Return an error if anything goes wrong
    return await updateInteraction(`Error creating PDF: ${error.message}`, interaction.id, interaction.token);
  }
}

module.exports = {
  doDiscordPdf,
};

Code Breakdown

Importing Modules

The code begins by importing various Node.js modules and functions from external libraries:

const os = require('os')
const fs = require('fs')
const {updateInteraction} = importer.import('discord api')
const {savePdf} = importer.import('collect all bookmarks')
const {patchInteractionImageAttachment} = importer.import('update discord interaction with attachments')
const {doBrowserRequest} = importer.import('browser crawler tools')
const {
  safeurl,
  existingCache,
  storeCache,
  readCache,
} = importer.import('domain cache tools')

Setting Environment Variables

The code sets the TEMP_DIR variable to the system's temporary directory using the os module:

const TEMP_DIR = os.tmpdir();

Initializing Counter Variable

A counter variable is initialized to keep track of the number of temporary PDFs created:

let counter = 0

Defining doDiscordPdf Function

The doDiscordPdf function is an asynchronous function that takes an interaction object as an argument:

async function doDiscordPdf(interaction) {
  //...
}

Function Implementation

The function does the following:

  1. Retrieves a cache from the existingCache function based on the interaction's value.
  2. Creates a temporary filename for the PDF.
  3. If the file already exists, deletes it.
  4. Increments the counter variable.
  5. Performs a browser request using the doBrowserRequest function, passing the interaction's value, a cache, and functions to store and read from the cache.
  6. If the PDF is created successfully, patches the interaction's image attachment with the PDF using the patchInteractionImageAttachment function.
  7. If the PDF creation fails, updates the interaction with an error message using the updateInteraction function.

Exporting doDiscordPdf Function

The doDiscordPdf function is exported as a module:

module.exports = {
  doDiscordPdf
}

Notes

  • The code assumes that the importer object is defined elsewhere and provides a way to import functions from external libraries.
  • The path module is used to join the TEMP_DIR with a temporary filename, but it is not imported in this code snippet.
  • The safeurl function is not used in this code snippet.
  • The code uses the fs module to interact with the file system and the os module to access the system's temporary directory.