168 lines
6.7 KiB
TypeScript
168 lines
6.7 KiB
TypeScript
import TelegramBot, { CallbackQuery, InlineKeyboardMarkup } from 'node-telegram-bot-api';
|
||
import { ProfileService } from '../services/profileService';
|
||
import LocalizationService from '../services/localizationService';
|
||
|
||
export class LanguageHandlers {
|
||
private bot: TelegramBot;
|
||
private profileService: ProfileService;
|
||
private localizationService: LocalizationService;
|
||
|
||
constructor(bot: TelegramBot) {
|
||
this.bot = bot;
|
||
this.profileService = new ProfileService();
|
||
this.localizationService = LocalizationService.getInstance();
|
||
}
|
||
|
||
/**
|
||
* Показать меню выбора языка
|
||
*/
|
||
async showLanguageSelection(chatId: number, messageId?: number): Promise<void> {
|
||
const keyboard: InlineKeyboardMarkup = {
|
||
inline_keyboard: [
|
||
[
|
||
{ text: '🇷🇺 Русский', callback_data: 'set_lang_ru' },
|
||
{ text: '🇬🇧 English', callback_data: 'set_lang_en' }
|
||
],
|
||
[
|
||
{ text: '🇪🇸 Español', callback_data: 'set_lang_es' },
|
||
{ text: '🇫🇷 Français', callback_data: 'set_lang_fr' }
|
||
],
|
||
[
|
||
{ text: '🇩🇪 Deutsch', callback_data: 'set_lang_de' },
|
||
{ text: '🇮🇹 Italiano', callback_data: 'set_lang_it' }
|
||
],
|
||
[
|
||
{ text: '🇵🇹 Português', callback_data: 'set_lang_pt' },
|
||
{ text: '🇰🇷 한국어', callback_data: 'set_lang_ko' }
|
||
],
|
||
[
|
||
{ text: '🇨🇳 中文', callback_data: 'set_lang_zh' },
|
||
{ text: '🇯🇵 日本語', callback_data: 'set_lang_ja' }
|
||
]
|
||
]
|
||
};
|
||
|
||
const text =
|
||
'🌍 Choose your language / Выберите язык:\n\n' +
|
||
'🇷🇺 Русский\n' +
|
||
'🇬🇧 English\n' +
|
||
'🇪🇸 Español\n' +
|
||
'🇫🇷 Français\n' +
|
||
'🇩🇪 Deutsch\n' +
|
||
'🇮🇹 Italiano\n' +
|
||
'🇵🇹 Português\n' +
|
||
'🇰🇷 한국어\n' +
|
||
'🇨🇳 中文\n' +
|
||
'🇯🇵 日本語';
|
||
|
||
if (messageId) {
|
||
// Обновляем существующее сообщение
|
||
await this.bot.editMessageText(text, {
|
||
chat_id: chatId,
|
||
message_id: messageId,
|
||
reply_markup: keyboard
|
||
});
|
||
} else {
|
||
// Отправляем новое сообщение
|
||
await this.bot.sendMessage(chatId, text, { reply_markup: keyboard });
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Обработать установку языка
|
||
*/
|
||
async handleSetLanguage(query: CallbackQuery): Promise<void> {
|
||
const chatId = query.message?.chat.id;
|
||
const userId = query.from.id.toString();
|
||
const messageId = query.message?.message_id;
|
||
|
||
if (!chatId || !userId) return;
|
||
|
||
// Извлекаем код языка из callback_data (например, 'set_lang_ru' -> 'ru')
|
||
const langCode = query.data?.replace('set_lang_', '');
|
||
if (!langCode) return;
|
||
|
||
try {
|
||
// Проверяем, поддерживается ли язык
|
||
const supportedLanguages = this.localizationService.getSupportedLanguages();
|
||
if (!supportedLanguages.includes(langCode)) {
|
||
await this.bot.answerCallbackQuery(query.id, {
|
||
text: '❌ Unsupported language / Язык не поддерживается'
|
||
});
|
||
return;
|
||
}
|
||
|
||
// Обновляем язык пользователя в базе данных
|
||
await this.profileService.updateUserLanguage(userId, langCode);
|
||
|
||
// Устанавливаем язык в сервисе локализации
|
||
this.localizationService.setLanguage(langCode);
|
||
|
||
// Получаем переведенное сообщение об успехе
|
||
const successMessage = this.localizationService.t('language.changed');
|
||
|
||
// Показываем уведомление об успехе
|
||
await this.bot.answerCallbackQuery(query.id, {
|
||
text: successMessage,
|
||
show_alert: false
|
||
});
|
||
|
||
// Удаляем сообщение с выбором языка
|
||
if (messageId) {
|
||
await this.bot.deleteMessage(chatId, messageId);
|
||
}
|
||
|
||
// Показываем приветственное сообщение на выбранном языке
|
||
const keyboard: InlineKeyboardMarkup = {
|
||
inline_keyboard: [
|
||
[{ text: this.localizationService.t('start.createProfile'), callback_data: 'create_profile' }],
|
||
[{ text: this.localizationService.t('start.howItWorks'), callback_data: 'how_it_works' }]
|
||
]
|
||
};
|
||
|
||
await this.bot.sendMessage(
|
||
chatId,
|
||
this.localizationService.t('start.welcomeNew'),
|
||
{ reply_markup: keyboard }
|
||
);
|
||
|
||
} catch (error) {
|
||
console.error('Error setting language:', error);
|
||
await this.bot.answerCallbackQuery(query.id, {
|
||
text: '❌ Error / Ошибка'
|
||
});
|
||
}
|
||
}
|
||
|
||
/**
|
||
* Проверить, нужно ли показать выбор языка новому пользователю
|
||
*/
|
||
async checkAndShowLanguageSelection(userId: string, chatId: number): Promise<boolean> {
|
||
try {
|
||
// Получаем текущий язык пользователя
|
||
const currentLang = await this.profileService.getUserLanguage(userId);
|
||
|
||
// Если язык уже установлен, не показываем выбор
|
||
if (currentLang && currentLang !== 'ru') {
|
||
return false;
|
||
}
|
||
|
||
// Проверяем, есть ли у пользователя профиль
|
||
const profile = await this.profileService.getProfileByTelegramId(userId);
|
||
|
||
// Показываем выбор языка только новым пользователям без профиля
|
||
if (!profile) {
|
||
await this.showLanguageSelection(chatId);
|
||
return true;
|
||
}
|
||
|
||
return false;
|
||
} catch (error) {
|
||
console.error('Error checking language selection:', error);
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
|
||
export default LanguageHandlers;
|