From f6cce5394acc70425198d67b13aedcea1400927b Mon Sep 17 00:00:00 2001 From: Ruslan Date: Wed, 9 Sep 2026 10:59:09 +0000 Subject: [PATCH] v3: hybrid teacher - works on pages and with AI --- script.js | 149 +++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 132 insertions(+), 17 deletions(-) diff --git a/script.js b/script.js index 784d2fe..c66b628 100644 --- a/script.js +++ b/script.js @@ -494,14 +494,128 @@ function hideTypingIndicator() { if (typing) typing.remove(); } -async function askTeacher(message) { - // Получаем контекст уровня - const levelContext = currentLevel ? `Current student level: ${currentLevel}. ` : ''; +// Готовые ответы для статической версии (без сервера) +const teacherResponses = { + greetings: { + keywords: ['hello', 'hi', 'привет', 'здравствуй', 'good morning', 'good afternoon'], + answers: [ + 'Hello! Great to see you! How can I help you with English today?', + 'Hi there! Ready to practice English? What would you like to work on?', + 'Hello! I\'m your English teacher. Ask me anything about grammar, vocabulary, or let\'s just chat!' + ] + }, + thanks: { + keywords: ['thank', 'спасибо', 'thanks'], + answers: [ + 'You\'re welcome! Keep up the good work! 👍', + 'Anytime! That\'s what I\'m here for! 😊', + 'No problem! Feel free to ask more questions!' + ] + }, + help: { + keywords: ['help', 'помощь', 'помоги', 'explain', 'объясни'], + answers: [ + 'I can help you with: grammar rules, vocabulary, pronunciation tips, or just conversation practice. What do you need?', + 'Sure! I can explain grammar, check your sentences, or suggest words. What topic interests you?' + ] + }, + grammar: { + keywords: ['grammar', 'грамматик', 'rule', 'правило', 'tense', 'время'], + answers: [ + 'Grammar is important! The key is practice. Start with Present Simple - it\'s the most common tense. Example: "I work every day." Want me to explain more?', + 'English grammar has 12 tenses, but you only need 5-6 for daily conversation. Which tense would you like to learn?' + ] + }, + vocabulary: { + keywords: ['word', 'слово', 'vocabulary', 'translate', 'перевод', 'meaning'], + answers: [ + 'Great question! Building vocabulary takes time. Try learning 5-10 new words daily and use them in sentences. What word interests you?', + 'I can help with translations! Just tell me the word you want to know.' + ] + }, + practice: { + keywords: ['practice', 'практик', 'speak', 'говорить', 'chat', 'болтать'], + answers: [ + 'Let\'s practice! Tell me about your day in English. Don\'t worry about mistakes - I\'ll help you correct them!', + 'Great! Let\'s have a conversation. What topics interest you? Hobbies, work, travel, movies?' + ] + }, + mistake: { + keywords: ['mistake', 'ошибка', 'wrong', 'correct', 'правильно'], + answers: [ + 'Mistakes are how we learn! Don\'t be afraid to make them. Even native speakers make mistakes!', + 'Good catch! Let me explain the rule so you remember it better.' + ] + }, + goodbye: { + keywords: ['bye', 'goodbye', 'пока', 'до свидания', 'see you'], + answers: [ + 'Goodbye! Keep practicing and you\'ll improve fast! See you next time! 👋', + 'Bye! Great job today! Come back when you want to practice more!' + ] + }, + encouragement: { + keywords: ['hard', 'трудно', 'difficult', 'can\'t', 'не могу', 'impossible'], + answers: [ + 'Learning English takes time, but you\'re doing great! Every day you\'re getting better. Keep going! 💪', + 'I understand it can be challenging. Break it into small steps. What specifically is difficult? I\'ll help!' + ] + }, + level: { + keywords: ['level', 'уровень', 'beginner', 'intermediate', 'advanced'], + answers: [ + 'Choose your level from the cards above! Each level has theory, vocabulary, and exercises. Start where you feel comfortable.', + 'Don\'t worry too much about levels. Just start practicing and you\'ll naturally progress!' + ] + } +}; + +const fallbackAnswers = [ + 'Interesting! Tell me more about it in English. Practice makes perfect! 😊', + 'I see! Can you give me an example sentence? I\'ll help you check it.', + 'That\'s a great topic! What specific aspect would you like to discuss?', + 'Good question! Let me think... Actually, the best way to learn is through practice. Try making a sentence with this!', + 'Hmm, I\'m not sure I understand completely. Can you rephrase that? Or ask me something more specific about English.' +]; + +function getStaticResponse(message) { + const lower = message.toLowerCase(); - const messages = [ - { - role: 'system', - content: `You are a friendly and supportive English teacher. Your tasks: + // Ищем совпадения по ключевым словам + for (const [category, data] of Object.entries(teacherResponses)) { + if (data.keywords.some(kw => lower.includes(kw))) { + const answers = data.answers; + return answers[Math.floor(Math.random() * answers.length)]; + } + } + + // Определяем язык + const isRussian = /[а-яА-ЯёЁ]/.test(message); + + if (isRussian) { + const ruResponses = [ + 'Отличный вопрос! Попробуй задать его на английском - я помогу с переводом и грамматикой.', + 'Интересно! Расскажи подробнее. Не бойся делать ошибки - я помогу их исправить.', + 'Хорошо! Давай обсудим это. Какой аспект тебя интересует?', + 'Вопрос понятен! Лучший способ выучить - практиковаться. Попробуй составить предложение на эту тему!', + 'Я тут, чтобы помочь! Спроси что-то конкретное о грамматике, словах или давай поболтаем на английском.' + ]; + return ruResponses[Math.floor(Math.random() * ruResponses.length)]; + } + + // English fallback + return fallbackAnswers[Math.floor(Math.random() * fallbackAnswers.length)]; +} + +async function askTeacher(message) { + // Пробуем серверный ИИ (если есть) + try { + const levelContext = currentLevel ? `Current student level: ${currentLevel}. ` : ''; + + const messages = [ + { + role: 'system', + content: `You are a friendly and supportive English teacher. Your tasks: 1. Communicate at the student's level 2. Correct mistakes gently and explain grammar rules 3. Help with vocabulary and constructions @@ -509,20 +623,20 @@ async function askTeacher(message) { 5. Answer grammar questions ${levelContext}Respond briefly (2-4 sentences), in a friendly manner. If the student writes in Russian, respond in Russian with English examples. If in English, respond in English but you can add translations of difficult words.` - }, - { - role: 'user', - content: message - } - ]; + }, + { + role: 'user', + content: message + } + ]; - try { const response = await fetch('/api/ai', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ messages }) + body: JSON.stringify({ messages }), + timeout: 5000 }); if (!response.ok) { @@ -538,8 +652,9 @@ ${levelContext}Respond briefly (2-4 sentences), in a friendly manner. If the stu return answer.replace(/\n/g, '
'); } catch (error) { - console.error('AI request failed:', error); - return 'Sorry, I can\'t respond right now. But I\'m here to help you with English!'; + // Фолбэк на статические ответы + console.log('Using static responses:', error.message); + return getStaticResponse(message); } }