update pdf

This commit is contained in:
Raven 2024-10-02 06:35:08 -04:00
parent 356d128fce
commit 81e55bd84b
2 changed files with 65 additions and 31 deletions

View File

@ -4,6 +4,20 @@ const he = require('he');
const fs = require('fs');
const PDFDocument = require('pdfkit'); // Import PDFKit
require('dotenv').config();
const markdownIt = require('markdown-it');
const puppeteer = require('puppeteer');
const highlight = require('highlight.js');
const md = new markdownIt({
highlight: function (str, lang) {
if (lang && highlight.getLanguage(lang)) {
try {
return highlight.highlight(str, { language: lang }).value;
} catch (__) {}
}
return ''; // use external default escaping
}
});
const client = new Client({
intents: [GatewayIntentBits.Guilds]
@ -69,7 +83,18 @@ client.on('interactionCreate', async interaction => {
} else if (commandName === 'privacy') {
await togglePrivacy(interaction);
} else if (commandName === 'pdf') {
await generatePDF(interaction);
try {
// Defer the reply to give time for PDF generation
await interaction.deferReply({ ephemeral: isEphemeral(interaction.user.id) });
// Generate the PDF
await generatePDF(interaction);
// After generating the PDF, you will handle the reply inside the generatePDF function
} catch (error) {
console.error('Failed to generate PDF:', error);
await interaction.editReply({ content: 'Failed to generate PDF.' });
}
}
});
@ -202,7 +227,6 @@ async function sendLongMessage(interaction, responseText) {
}
}
// Generate a PDF of the conversation history
async function generatePDF(interaction) {
try {
// Fetch the conversation history from the API
@ -217,45 +241,55 @@ async function generatePDF(interaction) {
// Filter out system messages
const filteredHistory = conversationHistory.filter(message => message.role !== 'system');
// Create a PDF document
const doc = new PDFDocument();
const pdfPath = `./conversation_${interaction.user.id}.pdf`;
const writeStream = fs.createWriteStream(pdfPath);
// Convert the conversation history to HTML with syntax highlighting
let htmlContent = `
<html>
<head>
<link id="highlightjs-style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.6.0/styles/atom-one-dark.min.css" rel="stylesheet">
<style>
body { font-family: Arial, sans-serif; }
pre { background-color: #f4f4f4; padding: 10px; border-radius: 4px; }
</style>
</head>
<body><h1>Conversation History</h1>`;
// Pipe the document to a file
doc.pipe(writeStream);
// Add conversation history to the PDF
doc.fontSize(14).text('Conversation History', { align: 'center' });
doc.moveDown();
filteredHistory.forEach((message, index) => {
filteredHistory.forEach(message => {
const role = message.role.charAt(0).toUpperCase() + message.role.slice(1);
const content = he.decode(message.content); // Decode any HTML entities
doc.fontSize(12).text(`${role}: ${content}`, { align: 'left' });
doc.moveDown();
const renderedMarkdown = md.render(content); // Convert Markdown to HTML with syntax highlighting
// Append the formatted HTML to the document
htmlContent += `<h3>${role}:</h3>`;
htmlContent += `<div>${renderedMarkdown}</div>`;
});
doc.end();
htmlContent += `</body></html>`;
// Wait for the PDF to finish writing
writeStream.on('finish', async () => {
const attachment = new AttachmentBuilder(pdfPath);
await interaction.reply({
content: 'Here is your conversation history in PDF format:',
files: [attachment],
ephemeral: isEphemeral(interaction.user.id)
});
// Clean up the PDF file after sending it
fs.unlinkSync(pdfPath);
// Use puppeteer to generate a PDF from the HTML content
const browser = await puppeteer.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox']
});
const page = await browser.newPage();
await page.setContent(htmlContent);
const pdfPath = `./conversation_${interaction.user.id}.pdf`;
await page.pdf({ path: pdfPath, format: 'A4' });
await browser.close();
// Send the PDF back to the user
const attachment = new AttachmentBuilder(pdfPath);
await interaction.editReply({
content: 'Here is your conversation history in PDF format:',
files: [attachment],
ephemeral: isEphemeral(interaction.user.id)
});
// Clean up the PDF file after sending it
fs.unlinkSync(pdfPath);
} catch (error) {
console.error('Failed to generate PDF:', error);
await interaction.reply({ content: 'Failed to generate PDF.', ephemeral: isEphemeral(interaction.user.id) });
}
}
// Log in the bot
client.login(process.env.THE_TOKEN_2);

View File

@ -1,3 +1,3 @@
{
"342128351638585344": true
"342128351638585344": false
}