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 fs = require('fs');
const PDFDocument = require('pdfkit'); // Import PDFKit const PDFDocument = require('pdfkit'); // Import PDFKit
require('dotenv').config(); 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({ const client = new Client({
intents: [GatewayIntentBits.Guilds] intents: [GatewayIntentBits.Guilds]
@ -69,7 +83,18 @@ client.on('interactionCreate', async interaction => {
} else if (commandName === 'privacy') { } else if (commandName === 'privacy') {
await togglePrivacy(interaction); await togglePrivacy(interaction);
} else if (commandName === 'pdf') { } else if (commandName === 'pdf') {
try {
// Defer the reply to give time for PDF generation
await interaction.deferReply({ ephemeral: isEphemeral(interaction.user.id) });
// Generate the PDF
await generatePDF(interaction); 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) { async function generatePDF(interaction) {
try { try {
// Fetch the conversation history from the API // Fetch the conversation history from the API
@ -217,32 +241,44 @@ async function generatePDF(interaction) {
// Filter out system messages // Filter out system messages
const filteredHistory = conversationHistory.filter(message => message.role !== 'system'); const filteredHistory = conversationHistory.filter(message => message.role !== 'system');
// Create a PDF document // Convert the conversation history to HTML with syntax highlighting
const doc = new PDFDocument(); let htmlContent = `
const pdfPath = `./conversation_${interaction.user.id}.pdf`; <html>
const writeStream = fs.createWriteStream(pdfPath); <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 filteredHistory.forEach(message => {
doc.pipe(writeStream);
// Add conversation history to the PDF
doc.fontSize(14).text('Conversation History', { align: 'center' });
doc.moveDown();
filteredHistory.forEach((message, index) => {
const role = message.role.charAt(0).toUpperCase() + message.role.slice(1); const role = message.role.charAt(0).toUpperCase() + message.role.slice(1);
const content = he.decode(message.content); // Decode any HTML entities const content = he.decode(message.content); // Decode any HTML entities
doc.fontSize(12).text(`${role}: ${content}`, { align: 'left' }); const renderedMarkdown = md.render(content); // Convert Markdown to HTML with syntax highlighting
doc.moveDown();
// 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 // Use puppeteer to generate a PDF from the HTML content
writeStream.on('finish', async () => { 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); const attachment = new AttachmentBuilder(pdfPath);
await interaction.editReply({
await interaction.reply({
content: 'Here is your conversation history in PDF format:', content: 'Here is your conversation history in PDF format:',
files: [attachment], files: [attachment],
ephemeral: isEphemeral(interaction.user.id) ephemeral: isEphemeral(interaction.user.id)
@ -250,12 +286,10 @@ async function generatePDF(interaction) {
// Clean up the PDF file after sending it // Clean up the PDF file after sending it
fs.unlinkSync(pdfPath); fs.unlinkSync(pdfPath);
});
} catch (error) { } catch (error) {
console.error('Failed to generate PDF:', error); console.error('Failed to generate PDF:', error);
await interaction.reply({ content: 'Failed to generate PDF.', ephemeral: isEphemeral(interaction.user.id) }); await interaction.reply({ content: 'Failed to generate PDF.', ephemeral: isEphemeral(interaction.user.id) });
} }
} }
// Log in the bot // Log in the bot
client.login(process.env.THE_TOKEN_2); client.login(process.env.THE_TOKEN_2);

View File

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