turns-00044.parquet:67
80401aac5ed7faad9c9fe2ab
turn 8/9gpt-4o-2024-08-06EnglishIndonesia553 words
degenerate_repetitionAbsentFinal dense release
USER
Give me the full code :)
ASSISTANT
Certainly! Below is the complete code with the necessary modifications to address the deprecation warning by specifying the MIME type as `application/zip` when sending the backup file:
```javascript
const fs = require('fs');
const path = require('path');
const TelegramBot = require('node-telegram-bot-api');
const schedule = require('node-schedule');
const archiver = require('archiver');
// Replace with your own Telegram bot token
const token = 'YOUR_TELEGRAM_BOT_TOKEN';
const bot = new TelegramBot(token, { polling: true });
// Load or ask for backup directory
let backupDirectory;
const configPath = path.join(__dirname, 'config.json');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
backupDirectory = config.backupDirectory;
} else {
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
readline.question("Enter the desired backup directory: ", (dir) => {
backupDirectory = dir;
readline.question("Do you want to save this configuration? (yes/no): ", (answer) => {
if (answer.trim().toLowerCase() === 'yes') {
fs.writeFileSync(configPath, JSON.stringify({ backupDirectory }), 'utf8');
}
readline.close();
});
});
}
function createBackupZip() {
return new Promise((resolve, reject) => {
if (!fs.existsSync(backupDirectory)) {
return reject(new Error('Backup directory does not exist'));
}
const archiveName = `backup_${new Date().toISOString().replace(/[:.]/g, '-')}.zip`;
const outputFilePath = path.join(__dirname, archiveName);
const output = fs.createWriteStream(outputFilePath);
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', () => {
console.log(`Backup zip created: ${outputFilePath} (${archive.pointer()} total bytes)`);
resolve(outputFilePath);
});
archive.on('error', err => reject(err));
archive.pipe(output);
archive.directory(backupDirectory, false);
archive.finalize();
});
}
bot.onText(/\/start/, (msg) => {
bot.sendMessage(msg.chat.id, `Hi! Use /backup to create a backup.\nUse /schedule_backup [interval] [type] to enable auto backup.\nExample: /schedule_backup 1 hour`);
});
bot.onText(/\/backup/, async (msg) => {
try {
const backupZip = await createBackupZip();
bot.sendMessage(msg.chat.id, `Backup created.`);
// Send the backup file to the user with specified content type
bot.sendDocument(msg.chat.id, backupZip, {}, { contentType: 'application/zip' })
.then(() => console.log('Backup sent to user.'))
.catch(err => console.error('Error sending document:', err));
} catch (error) {
bot.sendMessage(msg.chat.id, `Error creating backup: ${error.message}`);
console.error('Error creating backup zip:', error);
}
});
bot.onText(/\/schedule_backup (\d+) (minute|hour|day|month)/, (msg, match) => {
const interval = parseInt(match[1]);
const intervalType = match[2];
let rule;
switch (intervalType) {
case 'minute':
rule = new schedule.RecurrenceRule();
rule.minute = new schedule.Range(0, 59, interval);
break;
case 'hour':
rule = new schedule.RecurrenceRule();
rule.hour = new schedule.Range(0, 23, interval);
rule.minute = 0;
break;
case 'day':
rule = new schedule.RecurrenceRule();
rule.dayOfWeek = new schedule.Range(0, 6, interval);
rule.hour = 0;
rule.minute = 0;
break;
case 'month':
// For simplicity, schedule every 30 days for 'month'
schedule.scheduleJob(Date.now() + interval * 30 * 24 * 60 * 60 * 1000, async () => {
try {
const backupZip = await createBackupZip();
await bot.sendDocument(msg.chat.id, backupZip, {}, { contentType: 'application/zip' });
console.log('Scheduled backup sent to user.');
} catch (error) {
console.error('Error during scheduled backup:', error);
}
});
return;
}
// For non-monthly backups, set up a repeating job
if (rule) {
schedule.scheduleJob(rule, async () => {
try {
const backupZip = await createBackupZip();
await bot.sendDocument(msg.chat.id, backupZip, {}, { contentType: 'application/zip' });
console.log('Scheduled backup sent to user.');
} catch (error) {
console.error('Error during scheduled backup:', error);
}
});
}
bot.sendMessage(msg.chat.id, `Auto backup scheduled every ${interval} ${intervalType}(s).`);
});
```
### Notes:
- **Token Replacement:** Remember to replace `'YOUR_TELEGRAM_BOT_TOKEN'` with your actual Telegram bot token.
- **Testing:** Test the bot thoroughly to ensure it handles different backup and directory scenarios gracefully.
- **Error Handling:** The script has improved handling for potential errors during zip creation and document sending.
- **Configuring MIME Type:** Specifying MIME type as `application/zip` addresses the deprecation warning.