module.exports = {} const Discord = require('discord.js'); module.exports.definition = { name: 'export', description: 'Export glucose readings to a csv file', integration_types: [0, 1], contexts: [0, 1, 2], options: [ { name: 'start_date', description: 'Start date for the export in format mm/dd/yyyy', type: 3, // STRING required: false }, { name: 'end_date', description: 'End date for the export in format mm/dd/yyyy', type: 3, // STRING required: false } ], } module.exports.execute = async (interaction, client, db) => { const startDate = interaction.options.getString('start_date'); const endDate = interaction.options.getString('end_date'); if (!db) { return interaction.reply({ content: 'Database connection is not available.', ephemeral: true }); } try { let query = `SELECT * FROM glucose_log WHERE user_id = ?`; const params = [interaction.user.id]; if (startDate) { query += ` AND timestamp >= ?`; params.push(new Date(startDate).toISOString().slice(0, 19).replace('T', ' ')); } if (endDate) { query += ` AND timestamp <= ?`; params.push(new Date(endDate).toISOString().slice(0, 19).replace('T', ' ')); } db.all(query, params, (err, rows) => { if (err) { console.error('Database error:', err); return interaction.reply({ content: 'An error occurred while accessing the database.', ephemeral: true }); } if (rows.length === 0) { return interaction.reply({ content: 'No glucose readings found for the specified date range.', ephemeral: true }); } // Convert rows to CSV format const csvRows = rows.map(row => `${row.timestamp},${row.reading},${row.notes}`); const msg = rows.map(row => `**ID:** ${row.id}\n**Timestamp:** \n**Reading:** ${row.reading}\n**Notes:** ${row.notes || 'None'}`).join('\n'); const csvContent = `Timestamp,Reading,Notes\n${csvRows.join('\n')}`; const csvBuffer = Buffer.from(csvContent, 'utf8'); const attachment = new Discord.AttachmentBuilder(csvBuffer, { name: `glucose_readings.csv` }); return interaction.reply({ content: msg, files: [attachment] }); }); } catch (error) { console.error('Error exporting glucose readings:', error); return interaction.reply({ content: 'An error occurred while exporting your glucose readings.', ephemeral: true }); } }