### Install discord-html-transcripts Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt Install the module using npm. ```bash npm install discord-html-transcripts ``` -------------------------------- ### Configure Image Compression in Transcripts Source: https://github.com/itzderock/discord-html-transcripts/blob/master/README.md Set up image compression for transcripts by installing the 'sharp' module and configuring the 'resolveImageSrc' callback. This example sets a maximum image size and applies 40% quality compression, converting images to WebP format. ```javascript callbacks: { resolveImageSrc: new TranscriptImageDownloader() .withMaxSize(5120) // 5MB in KB .withCompression(40, true) // 40% quality, convert to webp .build() } ``` -------------------------------- ### Install discord-html-transcripts with NPM Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/README.md Install the module using NPM. Ensure you are running discord.js version 14 or higher. ```shell npm install --save discord-html-transcripts ``` -------------------------------- ### createTranscript Options Example Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md This example shows common options for transcript generation, including return type, filename, image saving, footer text, and callback functions. Use these options to tailor the transcript output. ```javascript const attachment = await discordTranscripts.createTranscript(channel, { returnType: 'attachment', // Valid options: 'buffer' | 'string' | 'attachment' Default: 'attachment' OR use the enum ExportReturnType filename: 'transcript.html', // Only valid with returnType is 'attachment'. Name of attachment. saveImages: false, // Download all images and include the image data in the HTML (allows viewing the image even after it has been deleted) (! WILL INCREASE FILE SIZE !) footerText: "Exported {number} message{s}", // Change text at footer, don't forget to put {number} to show how much messages got exported, and {s} for plural callbacks: { // register custom callbacks for the following: resolveChannel: (channelId: string) => Awaitable, resolveUser: (userId: string) => Awaitable, resolveRole: (roleId: string) => Awaitable }, poweredBy: true // Whether to include the "Powered by discord-html-transcripts" footer }); ``` -------------------------------- ### Install discord-html-transcripts with Yarn Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/README.md Install the module using Yarn. Ensure you are running discord.js version 14 or higher. ```shell yarn add discord-html-transcripts ``` -------------------------------- ### Install discord-html-transcripts with PNPM Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/README.md Install the module using PNPM. Ensure you are running discord.js version 14 or higher. ```shell pnpm i -S discord-html-transcripts ``` -------------------------------- ### Generate Transcript from Provided Messages Source: https://github.com/itzderock/discord-html-transcripts/blob/master/README.md This example demonstrates how to generate an HTML transcript when you already have a collection of messages and a channel object. This is useful if you've fetched messages using a different method. ```javascript const discordTranscripts = require('discord-html-transcripts'); // or (if using typescript) import * as discordTranscripts from 'discord-html-transcripts'; const messages = someWayToGetMessages(); // Must be Collection or Message[] const channel = someWayToGetChannel(); // Used for ticket name, guild icon, and guild name // Must be awaited const attachment = await discordTranscripts.generateFromMessages(messages, channel); ``` -------------------------------- ### Create Transcript with Options (TypeScript) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/createtranscript.md This TypeScript example demonstrates how to create a transcript from a Discord channel, including options for image saving and footer text. The generated transcript is an AttachmentBuilder, ready to be sent via discord.js. ```typescript import * as discordTranscripts from "discord-html-transcripts"; [...] // Notice the async here ⤵️ client.on('messageCreate', async (message) => { if (message.content === "!transcript") { // Use the following to fetch the transcript. const transcript = await discordTranscripts.createTranscript( message.channel, { // options go here // for example saveImages: true, footerText: "Saved {number} message{s}" } ); // and by default, createTranscript will return an AttachmentBuilder // which you can directly send to discord.js message.reply({ content: "Here's your transcript!", files: [transcript] }); } }); ``` -------------------------------- ### Configure Transcript Export Return Type Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt Demonstrates how to specify the return type for transcript generation using the ExportReturnType enum. Use this to get the transcript as a Buffer, a string, or an AttachmentBuilder. ```typescript import * as discordTranscripts from 'discord-html-transcripts'; import { ExportReturnType } from 'discord-html-transcripts'; import { TextChannel, AttachmentBuilder } from 'discord.js'; // Return as Buffer const bufferTranscript = await discordTranscripts.createTranscript( channel as TextChannel, { returnType: ExportReturnType.Buffer } ); // bufferTranscript is typed as Buffer await fs.writeFile('transcript.html', bufferTranscript); ``` ```typescript // Return as string const stringTranscript = await discordTranscripts.createTranscript( channel as TextChannel, { returnType: ExportReturnType.String } ); // stringTranscript is typed as string console.log(`Generated ${stringTranscript.length} characters of HTML`); ``` ```typescript // Return as AttachmentBuilder (default) const attachmentTranscript = await discordTranscripts.createTranscript( channel as TextChannel, { returnType: ExportReturnType.Attachment, filename: 'logs.html' } ); // attachmentTranscript is typed as AttachmentBuilder await channel.send({ files: [attachmentTranscript] }); ``` -------------------------------- ### Ticket System Integration with Transcript Archival Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt An example of a complete ticket closing system. It generates a transcript, sends it to a log channel, and then deletes the ticket channel. Ensure the 'ticket-logs' channel exists and the bot has permissions. ```javascript const discordTranscripts = require('discord-html-transcripts'); const { EmbedBuilder, PermissionFlagsBits } = require('discord.js'); async function closeTicket(interaction, ticketChannel, logChannel) { // Defer the reply as transcript generation may take time await interaction.deferReply({ ephemeral: true }); try { // Generate the transcript with all messages and images saved const transcript = await discordTranscripts.createTranscript(ticketChannel, { limit: -1, filename: `ticket-${ticketChannel.name}-${Date.now()}.html`, saveImages: true, footerText: 'Ticket closed • {number} message{s} archived', poweredBy: true, filter: (message) => { // Include all messages except system join messages return message.type !== 7; // MessageType.UserJoin } }); // Create a log embed const logEmbed = new EmbedBuilder() .setTitle('Ticket Closed') .setColor(0xff6b6b) .addFields( { name: 'Ticket', value: ticketChannel.name, inline: true }, { name: 'Closed by', value: interaction.user.tag, inline: true }, { name: 'Closed at', value: ``, inline: false } ) .setTimestamp(); // Send transcript to log channel await logChannel.send({ embeds: [logEmbed], files: [transcript] }); // Notify user and delete ticket channel await interaction.editReply({ content: 'Ticket closed. Transcript has been saved.' }); // Wait briefly then delete the channel setTimeout(async () => { await ticketChannel.delete('Ticket closed by ' + interaction.user.tag); }, 3000); } catch (error) { console.error('Failed to generate transcript:', error); await interaction.editReply({ content: 'Failed to generate transcript. Please try again.' }); } } // Button interaction handler client.on('interactionCreate', async (interaction) => { if (!interaction.isButton()) return; if (interaction.customId !== 'close-ticket') return; const logChannel = interaction.guild.channels.cache.find( ch => ch.name === 'ticket-logs' ); if (!logChannel) { return interaction.reply({ content: 'Log channel not found!', ephemeral: true }); } await closeTicket(interaction, interaction.channel, logChannel); }); ``` -------------------------------- ### Generate Transcript from Custom Messages (TypeScript) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md This TypeScript example demonstrates generating an HTML transcript using a predefined set of messages. It requires discord.js and discord-html-transcripts. Provide a Collection of Message objects and a channel object to the function. ```typescript import * as discordTranscripts from "discord-html-transcripts"; import { Collection, Message } from "discord.js"; [...] const messages = new Collection(); const channel = /* somehow get this */; // somehow fill the messages collection const transcript = await discordTransTranscripts.generateFromMessages( messages, // the content in the transcript channel, // used for transcript title, etc { /* options */ } ); // By default returns an AttachmentBuilder that can be sent in a channel. channel.send({ files: [attachment] }); ``` -------------------------------- ### Generate Transcript with discord.js Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt Use the `createTranscript` function to generate an HTML transcript from a Discord channel. This example demonstrates fetching all messages, customizing the output format, and sending it as an attachment. Ensure your bot has the necessary intents (Guilds, GuildMessages, MessageContent) and is logged in with a valid token. ```javascript const discordTranscripts = require('discord-html-transcripts'); const { Client, GatewayIntentBits } = require('discord.js'); const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); client.on('messageCreate', async (message) => { if (message.content === '!transcript') { // Generate transcript from all messages in the channel const transcript = await discordTranscripts.createTranscript(message.channel, { limit: -1, // -1 fetches all messages recursively returnType: 'attachment', // 'buffer' | 'string' | 'attachment' filename: 'channel-transcript.html', // Output filename saveImages: true, // Download and embed images as base64 footerText: 'Exported {number} message{s}', // Custom footer text poweredBy: true, // Include "Powered by" footer hydrate: true, // Server-side hydration filter: (msg) => !msg.author.bot // Filter out bot messages }); // Send the transcript as an attachment await message.channel.send({ content: 'Here is the channel transcript!', files: [transcript] }); } }); client.login('YOUR_BOT_TOKEN'); ``` -------------------------------- ### Generate Transcript from Custom Messages (JavaScript) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md Use this JavaScript snippet to generate an HTML transcript from a custom collection of messages. Ensure you have the discord.js library and discord-html-transcripts installed. The function requires a message collection and a channel object. ```javascript const discordTranscripts = require("discord-html-transcripts"); const { Collection } = require("discord.js"); [...] const messages = new Collection(); const channel = /* somehow get this */; // somehow fill the messages collection const transcript = await discordTranscripts.generateFromMessages( messages, // the content in the transcript channel, // used for transcript title, etc { /* options */ } ); // By default returns an AttachmentBuilder that can be sent in a channel. channel.send({ files: [attachment] }); ``` -------------------------------- ### Configure Transcript Generation (Built-in Fetcher) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/README.md Customize the transcript generation process using an options object with `createTranscript`. Options include message limit, return type, filename, image saving, footer text, callbacks, and more. ```javascript const attachment = await discordTranscripts.createTranscript(channel, { limit: -1, // Max amount of messages to fetch. `-1` recursively fetches. returnType: 'attachment', // Valid options: 'buffer' | 'string' | 'attachment' Default: 'attachment' OR use the enum ExportReturnType filename: 'transcript.html', // Only valid with returnType is 'attachment'. Name of attachment. saveImages: false, // Download all images and include the image data in the HTML (allows viewing the image even after it has been deleted) (! WILL INCREASE FILE SIZE !) footerText: "Exported {number} message{s}", // Change text at footer, don't forget to put {number} to show how much messages got exported, and {s} for plural callbacks: { // register custom callbacks for the following: resolveChannel: (channelId: string) => Awaitable, resolveUser: (userId: string) => Awaitable, resolveRole: (roleId: string) => Awaitable, resolveImageSrc: ( attachment: APIAttachment, message: APIMessage ) => Awaitable }, poweredBy: true, // Whether to include the "Powered by discord-html-transcripts" footer hydrate: true, // Whether to hydrate the html server-side filter: (message) => true // Filter messages, e.g. (message) => !message.author.bot }); ``` -------------------------------- ### Configure Transcript Image Downloader with Compression Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt Use TranscriptImageDownloader to configure image downloading behavior with optional compression. Useful when you need to preserve images but want to control file sizes through quality settings and format conversion. Ensure Discord.js is initialized. ```javascript const discordTranscripts = require('discord-html-transcripts'); const { TranscriptImageDownloader } = discordTranscripts; client.on('messageCreate', async (message) => { if (message.content === '!archive') { // Create a custom image downloader with compression const imageDownloader = new TranscriptImageDownloader() .withMaxSize(5120) // Skip images larger than 5MB (5120 KB) .withCompression(40, true); // 40% quality, convert to WebP const transcript = await discordTranscripts.createTranscript(message.channel, { limit: 500, filename: 'archive.html', callbacks: { resolveImageSrc: imageDownloader.build() // Use custom downloader } }); await message.reply({ files: [transcript] }); } }); // Advanced: Custom image resolution callback const customImageCallback = async (attachment, apiMessage) => { // Return undefined to use original URL if (!attachment.width || !attachment.height) return undefined; // Return null to exclude the attachment entirely if (attachment.size > 10 * 1024 * 1024) return null; // Skip files > 10MB // Return a custom URL or base64 data URL const response = await fetch(attachment.url); const buffer = Buffer.from(await response.arrayBuffer()); const mimeType = response.headers.get('content-type'); return `data:${mimeType};base64,${buffer.toString('base64')}`; }; // Use with createTranscript const transcript = await discordTranscripts.createTranscript(channel, { callbacks: { resolveImageSrc: customImageCallback } }); ``` -------------------------------- ### Configure Transcript Generation (Provided Messages) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/README.md Configure transcript generation when providing your own messages using `generateFromMessages`. The available options are the same as `createTranscript`, excluding `limit` and `filter`. ```javascript const attachment = await discordTranscripts.generateFromMessages(messages, channel, { // Same as createTranscript, except no limit or filter }); ``` -------------------------------- ### Create Transcript with Options (JavaScript) Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/createtranscript.md Use this snippet to create a transcript from a Discord channel with custom options like saving images and adding a footer. The function returns an AttachmentBuilder by default, suitable for direct use with discord.js. ```javascript const discordTranscripts = require("discord-html-transcripts"); [...] // Notice the async here ⤵️ client.on('messageCreate', async (message) => { if (message.content === "!transcript") { // Use the following to fetch the transcript. const transcript = await discordTranscripts.createTranscript( message.channel, { // options go here // for example saveImages: true, footerText: "Saved {number} message{s}" } ); // and by default, createTranscript will return an AttachmentBuilder // which you can directly send to discord.js message.reply({ content: "Here's your transcript!", files: [transcript] }); } }); ``` -------------------------------- ### Generate Transcript with Built-in Fetcher Source: https://github.com/itzderock/discord-html-transcripts/blob/master/README.md Use this snippet to generate an HTML transcript directly from a Discord channel using the module's built-in message fetching capabilities. The generated attachment can then be sent to a channel. ```javascript const discordTranscripts = require('discord-html-transcripts'); // or (if using typescript) import * as discordTranscripts from 'discord-html-transcripts'; const channel = message.channel; // or however you get your TextChannel // Must be awaited const attachment = await discordTranscripts.createTranscript(channel); channel.send({ files: [attachment], }); ``` -------------------------------- ### createTranscript API Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/createtranscript.md The createTranscript function fetches messages from a specified Discord channel and can return the transcript as a Buffer, string, or AttachmentBuilder. It accepts a channel object and an optional options object for customization. ```APIDOC ## POST /api/transcripts/create ### Description Fetches messages from a provided channel and generates an HTML transcript. The transcript can be returned as a Buffer, string, or AttachmentBuilder. ### Method POST ### Endpoint /api/transcripts/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **channel** (TextBasedChannel) - Required - The channel from which to fetch messages. This can be a TextChannel, NewsChannel, ThreadChannel, or VoiceChannel. - **options** (CreateTranscriptOptions) - Optional - An object containing options for transcript generation. This includes: - **limit** (number) - Optional - The maximum number of messages to fetch. - **saveImages** (boolean) - Optional - Whether to save images found in messages. - **footerText** (string) - Optional - Text to display in the footer of the transcript, can include placeholders like {number} and {s}. - **filter** (function) - Optional - A function to filter messages before inclusion in the transcript. If it returns false, the message is excluded. ### Request Example ```json { "channel": "CHANNEL_ID", "options": { "limit": 100, "saveImages": true, "footerText": "Transcript generated on {date}" } } ``` ### Response #### Success Response (200) - **transcript** (Buffer | string | AttachmentBuilder) - The generated transcript in the specified format. #### Response Example (AttachmentBuilder example) ```json { "content": "Here's your transcript!", "files": [transcript] } ``` ``` -------------------------------- ### Custom Channel Resolution Callback Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md Allows you to provide a custom function to resolve channel IDs to channel objects. This is useful for scenarios where the default fetch method is not sufficient. ```APIDOC ## Custom Channel Resolution Callback ### Description A custom function that will be used by the module whenever it needs to resolve a channel (for example, if someone mentions a channel). The default option uses `channel.client.channels.fetch(...)` function. ### Method Signature `options.callbacks.resolveChannel: (channelId: string) => Awaitable` ### Parameters #### Path Parameters - **channelId** (string) - Required - The ID of the channel to resolve. ``` -------------------------------- ### createTranscript Function Signature Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/createtranscript.md The basic signature for the createTranscript function, showing the required channel parameter and the optional options object. ```javascript createTranscript(channel, (options = {})); ``` -------------------------------- ### Custom User Resolution Callback Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md Provides a custom function to resolve user IDs to user objects. This is beneficial for custom user fetching logic. ```APIDOC ## Custom User Resolution Callback ### Description A custom function that will be used by the module whenever it needs to resolve a user (for example, if a user is mentioned). The default option uses `channel.client.users.fetch(...)`. ### Method Signature `options.callbacks.resolveUser: (userId: string) => Awaitable` ### Parameters #### Path Parameters - **userId** (string) - Required - The ID of the user to resolve. ``` -------------------------------- ### Generate Transcript from Specific Messages Source: https://context7.com/itzderock/discord-html-transcripts/llms.txt Use generateFromMessages when you have pre-fetched messages or need fine-grained control over which messages appear in the transcript. Accepts either a Message array or a Collection, useful for combining messages from multiple sources or applying custom ordering. Ensure all necessary Discord.js dependencies are available. ```javascript const discordTranscripts = require('discord-html-transcripts'); const { Collection } = require('discord.js'); // Example: Generate transcript from specific messages async function createCustomTranscript(channel, messageIds) { // Fetch specific messages const messages = []; for (const id of messageIds) { const msg = await channel.messages.fetch(id).catch(() => null); if (msg) messages.push(msg); } // Generate transcript from the fetched messages const transcript = await discordTranscripts.generateFromMessages( messages, // Message[] or Collection channel, // Used for channel name, guild info, icon { returnType: 'string', // Return raw HTML string saveImages: false, // Don't embed images footerText: 'Selected {number} message{s}', poweredBy: true, callbacks: { // Custom resolution callbacks resolveChannel: async (channelId) => { return channel.client.channels.fetch(channelId).catch(() => null); }, resolveUser: async (userId) => { return channel.client.users.fetch(userId).catch(() => null); }, resolveRole: async (roleId) => { return channel.guild?.roles.fetch(roleId).catch(() => null); } } } ); return transcript; // Returns HTML string } // Usage in a command handler client.on('interactionCreate', async (interaction) => { if (!interaction.isCommand() || interaction.commandName !== 'export') return; const messageLinks = interaction.options.getString('messages'); const ids = messageLinks.split(',').map(link => link.trim().split('/').pop()); const html = await createCustomTranscript(interaction.channel, ids); // Save to file or process further const buffer = Buffer.from(html); await interaction.reply({ files: [{ attachment: buffer, name: 'selected-messages.html' }] }); }); ``` -------------------------------- ### Custom Role Resolution Callback Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md Enables the use of a custom function to resolve role IDs to role objects, offering flexibility in role management. ```APIDOC ## Custom Role Resolution Callback ### Description A custom function that will be used by the module whenever it needs to resolve a role (for example, if a role is mentioned). The default option uses `channel.guild?.roles.fetch(...)`. ### Method Signature `options.callbacks.resolveRole: (roleId: string) => Awaitable` ### Parameters #### Path Parameters - **roleId** (string) - Required - The ID of the role to resolve. ``` -------------------------------- ### generateFromMessages Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md Generates an HTML transcript from a provided collection or array of messages. ```APIDOC ## POST /generateFromMessages ### Description Generates an HTML transcript from a provided collection or array of messages. This function allows for finer control over the transcript content by letting you supply the messages. ### Method POST ### Endpoint /generateFromMessages ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **messages** (Message[] | Collection) - Required - An array or collection of discord.js Message objects to include in the transcript. - **channel** (TextBasedChannel) - Required - The channel object, used for obtaining transcript metadata like guild name, icon, and channel name. - **options** (GenerateFromMessagesOptions) - Optional - An object containing configuration options for the transcript generation. ##### options.returnType ('buffer' | 'string' | 'attachment') Determines the return type of the function. Defaults to 'attachment'. - 'buffer': Returns the HTML data as a buffer. - 'string': Returns the HTML data as a string. - 'attachment': Returns the HTML data as an AttachmentBuilder. ##### options.filename (string) The name of the output file when `returnType` is 'attachment'. Defaults to 'transcript-{channel id}.html'. ##### options.saveImages (boolean) If true, downloads all image attachments and embeds their data into the HTML. This preserves images even if they are deleted from Discord. Defaults to `false`. Warning: Enabling this can significantly increase file size and may cause issues with Discord's upload limits. ##### options.footerText (string) Custom text for the transcript's footer. Placeholders `{number}` and `{s}` can be used for message count and pluralization. Defaults to 'Exported {number} message{s}'. ##### options.poweredBy (boolean) If true, includes a 'Powered by discord-html-transcripts' footer. Defaults to `true`. ### Request Example ```json { "messages": [ { "id": "123456789012345678", "content": "Hello, world!", "author": { "id": "987654321098765432", "username": "TestUser", "avatar": "testavatar" }, "createdTimestamp": 1678886400000 } ], "channel": { "id": "112233445566778899", "name": "general", "guild": { "id": "111122223333444455", "name": "Test Server", "iconURL": "testicon.png" } }, "options": { "returnType": "attachment", "filename": "my-custom-transcript.html", "saveImages": false, "footerText": "Transcript generated on {date}", "poweredBy": true } } ``` ### Response #### Success Response (200) Returns an `AttachmentBuilder` object by default, which can be sent directly to a Discord channel. Other return types are possible based on the `options.returnType` parameter. #### Response Example (AttachmentBuilder object - content not directly representable in JSON) ``` -------------------------------- ### generateFromMessages Function Signature Source: https://github.com/itzderock/discord-html-transcripts/blob/master/docs/api-reference/generatefrommessages.md The generateFromMessages function accepts messages, a channel, and an optional options object for customization. ```javascript generateFromMessages(messages, channel, (options = {})); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.