alpha-test

This commit is contained in:
2025-09-18 13:46:35 +09:00
parent 85027a7747
commit 5ea3e8c1f3
27 changed files with 5887 additions and 174 deletions

View File

@@ -0,0 +1,142 @@
// Скрипт для восстановления оригинальной функциональности callbackHandlers.ts
const fs = require('fs');
const path = require('path');
// Находим самую последнюю версию файла callbackHandlers.ts в репозитории
const { execSync } = require('child_process');
try {
console.log('Поиск оригинальной версии CallbackHandlers.ts с полной функциональностью...');
// Находим коммиты, содержащие значительные изменения в файле (более 1000 символов)
const commits = execSync('git log --format="%H" -- src/handlers/callbackHandlers.ts')
.toString()
.trim()
.split('\n');
console.log(`Найдено ${commits.length} коммитов с изменениями файла`);
// Пробуем разные коммиты, начиная с последнего, чтобы найти полную реализацию
let foundFullImplementation = false;
let fullImplementationContent = '';
for (const commit of commits) {
console.log(`Проверяем коммит ${commit.substring(0, 8)}...`);
try {
const fileContent = execSync(`git show ${commit}:src/handlers/callbackHandlers.ts`).toString();
// Проверяем, содержит ли файл полные реализации методов
const hasFullImplementations = !fileContent.includes('// Заглушка метода') &&
fileContent.includes('await this.bot.sendMessage');
if (hasFullImplementations) {
console.log(`✅ Найдена полная реализация в коммите ${commit.substring(0, 8)}`);
fullImplementationContent = fileContent;
foundFullImplementation = true;
break;
} else {
console.log(`❌ Коммит ${commit.substring(0, 8)} не содержит полной реализации`);
}
} catch (error) {
console.error(`Ошибка при проверке коммита ${commit}:`, error.message);
}
}
if (!foundFullImplementation) {
console.error('❌ Не удалось найти полную реализацию в истории коммитов');
process.exit(1);
}
// Теперь получаем текущую версию файла с поддержкой уведомлений
console.log('Получаем текущую версию с поддержкой уведомлений...');
const currentFilePath = path.join(__dirname, '..', 'src', 'handlers', 'callbackHandlers.ts');
const currentContent = fs.readFileSync(currentFilePath, 'utf-8');
// Сначала создаем бэкап текущего файла
const backupPath = currentFilePath + '.backup-' + Date.now();
fs.writeFileSync(backupPath, currentContent);
console.log(`✅ Создан бэкап текущей версии: ${path.basename(backupPath)}`);
// Извлекаем код для поддержки уведомлений из текущей версии
console.log('Извлекаем код для поддержки уведомлений...');
// Находим импорт NotificationHandlers
const notificationImportRegex = /import\s+{\s*NotificationHandlers\s*}\s*from\s*['"]\.\/notificationHandlers['"]\s*;/;
const notificationImport = currentContent.match(notificationImportRegex)?.[0] || '';
// Находим объявление поля notificationHandlers
const notificationFieldRegex = /private\s+notificationHandlers\?\s*:\s*NotificationHandlers\s*;/;
const notificationField = currentContent.match(notificationFieldRegex)?.[0] || '';
// Находим инициализацию notificationHandlers в конструкторе
const notificationInitRegex = /\/\/\s*Создаем экземпляр NotificationHandlers[\s\S]*?try\s*{[\s\S]*?this\.notificationHandlers\s*=\s*new\s*NotificationHandlers[\s\S]*?}\s*catch[\s\S]*?}/;
const notificationInit = currentContent.match(notificationInitRegex)?.[0] || '';
// Находим метод handleNotificationSettings
const notificationSettingsMethodRegex = /async\s+handleNotificationSettings[\s\S]*?}\s*}/;
const notificationSettingsMethod = currentContent.match(notificationSettingsMethodRegex)?.[0] || '';
// Находим обработку callback для notifications в handleCallback
const notificationCallbackRegex = /\/\/\s*Настройки уведомлений[\s\S]*?else\s+if\s*\(data\s*===\s*['"]notifications['"][\s\S]*?}\s*}/;
const notificationCallback = currentContent.match(notificationCallbackRegex)?.[0] || '';
// Получаем часть обработки коллбэков для уведомлений
const notificationToggleRegex = /\/\/\s*Обработка переключения настроек уведомлений[\s\S]*?else\s+if[\s\S]*?notif_[\s\S]*?}\s*}/;
const notificationToggle = currentContent.match(notificationToggleRegex)?.[0] || '';
console.log(`✅ Извлечены блоки кода для уведомлений`);
// Интегрируем код уведомлений в оригинальную версию
console.log('Интегрируем код уведомлений в оригинальную версию...');
// 1. Добавляем импорт
let newContent = fullImplementationContent;
if (notificationImport) {
newContent = newContent.replace(/import\s*{[^}]*}\s*from\s*['"]\.\/messageHandlers['"]\s*;/,
match => match + '\n' + notificationImport);
}
// 2. Добавляем объявление поля
if (notificationField) {
newContent = newContent.replace(/private\s+translationController\s*:\s*TranslationController\s*;/,
match => match + '\n ' + notificationField);
}
// 3. Добавляем инициализацию в конструкторе
if (notificationInit) {
newContent = newContent.replace(/this\.translationController\s*=\s*new\s*TranslationController\(\);/,
match => match + '\n ' + notificationInit);
}
// 4. Добавляем обработку коллбэков для уведомлений
if (notificationCallback) {
newContent = newContent.replace(/else\s+{\s*await\s+this\.bot\.answerCallbackQuery\(query\.id[\s\S]*?return;/,
match => notificationCallback + '\n ' + match);
}
// 5. Добавляем обработку переключения настроек уведомлений
if (notificationToggle) {
newContent = newContent.replace(/else\s+{\s*await\s+this\.bot\.answerCallbackQuery\(query\.id[\s\S]*?return;/,
match => notificationToggle + '\n ' + match);
}
// 6. Добавляем метод handleNotificationSettings в конец класса
if (notificationSettingsMethod) {
newContent = newContent.replace(/}(\s*)$/, notificationSettingsMethod + '\n}$1');
}
// Сохраняем обновленный файл
const outputPath = currentFilePath + '.fixed';
fs.writeFileSync(outputPath, newContent);
console.log(`✅ Создана исправленная версия файла: ${path.basename(outputPath)}`);
console.log('\nИнструкция по восстановлению:');
console.log(`1. Проверьте файл ${path.basename(outputPath)}`);
console.log('2. Если все выглядит правильно, выполните команду:');
console.log(` Move-Item -Force "${path.basename(outputPath)}" "${path.basename(currentFilePath)}"`);
console.log('3. Перезапустите бота');
} catch (error) {
console.error('Произошла ошибка:', error);
}