diff --git a/go b/go new file mode 160000 index 0000000..89a7f4a --- /dev/null +++ b/go @@ -0,0 +1 @@ +Subproject commit 89a7f4ab1188f6e787207d63a2d4f00013a704ab diff --git a/public/script.ts b/public/script.ts index 5687cdd..ad9c88a 100644 --- a/public/script.ts +++ b/public/script.ts @@ -57,6 +57,13 @@ class QuixoticApp { this.tg.ready(); this.tg.expand(); this.tg.MainButton.hide(); + + // Debug Telegram user info + console.log('🔧 Telegram WebApp initialized'); + console.log('👤 User ID:', this.tg.initDataUnsafe?.user?.id); + console.log('📋 Full initData:', this.tg.initDataUnsafe); + } else { + console.log('❌ Telegram WebApp not available'); } this.searchInput = document.getElementById('searchInput') as HTMLInputElement; @@ -248,40 +255,59 @@ class QuixoticApp { console.log('🔧 About to send to Telegram, tg available:', !!this.tg); if (this.tg) { - // Send to Telegram chat + // Try WebApp method first (might not work) const payload = { action: 'send_audio', audioUrl: data.audioUrl, title: title }; - console.log('📤 Sending data to Telegram via sendData:', payload); + console.log('📤 Attempting WebApp sendData first:', payload); try { this.tg.sendData(JSON.stringify(payload)); - console.log('✅ Data sent via Telegram.sendData'); + console.log('✅ WebApp sendData called'); this.showMessage('✓ MP3 готов! Отправляем в чат...', 'success'); - - // Fallback: also try to send via HTTP request to our server - setTimeout(async () => { - try { - console.log('🔄 Sending fallback notification to server...'); - await fetch('/api/telegram-notify', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - userId: this.tg?.initDataUnsafe?.user?.id, - audioUrl: data.audioUrl, - title: title - }) - }); - } catch (fallbackError) { - console.log('Fallback notification failed (not critical):', fallbackError); - } - }, 2000); // Wait 2 seconds before fallback - } catch (sendError) { - console.error('❌ Failed to send via Telegram.sendData:', sendError); - this.showMessage('❌ Ошибка отправки в Telegram', 'error'); + console.error('❌ WebApp sendData failed:', sendError); + } + + // Always use direct API as primary method now + const userId = this.tg?.initDataUnsafe?.user?.id; + console.log('👤 Current user ID for sending:', userId); + + if (!userId) { + console.error('❌ No user ID available from Telegram WebApp'); + this.showMessage('❌ Ошибка: не удается определить пользователя', 'error'); + return; + } + + try { + console.log('🔄 Sending via direct API...'); + const requestData = { + userId: userId, + audioUrl: data.audioUrl, + title: title + }; + console.log('📦 Request data:', requestData); + + const directResponse = await fetch('/api/telegram-send', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(requestData) + }); + + if (directResponse.ok) { + const result = await directResponse.json(); + console.log('✅ Direct API success:', result); + this.showMessage('✅ MP3 отправлен в чат!', 'success'); + } else { + const error = await directResponse.json(); + console.error('❌ Direct API failed:', error); + this.showMessage('❌ Ошибка отправки в Telegram', 'error'); + } + } catch (directError) { + console.error('❌ Direct API request failed:', directError); + this.showMessage('❌ Ошибка соединения с ботом', 'error'); } } else { // For testing in browser - download file diff --git a/src/server.ts b/src/server.ts index ddf9a41..f6cf177 100644 --- a/src/server.ts +++ b/src/server.ts @@ -189,40 +189,36 @@ app.post('/api/convert', async (req: Request, res: Response) => { } }); -// Fallback API for Telegram notifications when WebApp data doesn't work -app.post('/api/telegram-notify', async (req: Request, res: Response) => { +// Direct Telegram API for sending audio when WebApp fails +app.post('/api/telegram-send', async (req: Request, res: Response) => { try { const { userId, audioUrl, title }: { userId?: string; audioUrl?: string; title?: string } = req.body; - console.log('📡 Fallback Telegram notification received:', { userId, audioUrl, title }); + console.log('🔄 Direct Telegram send request:', { userId, audioUrl, title }); if (!userId || !audioUrl || !title) { return res.status(400).json({ error: 'Missing required fields' }); } - // Find bot instance and send the audio - // Note: We need to get the bot instance from somewhere - // For now, we'll store a reference to it - if ((global as any).quixoticBot) { - console.log('🤖 Using global bot instance for fallback notification'); - const bot = (global as any).quixoticBot; - - // Get user's chat ID from database - const user = await db.getUserByTelegramId(userId); - if (user) { - // We need to get chat ID - for now use user's telegram ID as chat ID - await bot.sendAudioFile(parseInt(userId), audioUrl, title); - console.log('✅ Fallback notification sent successfully'); - } else { - console.log('❌ User not found for fallback notification'); - } - } else { - console.log('❌ No bot instance available for fallback'); + // Get bot instance + const botInstance = (global as any).quixoticBot; + if (!botInstance) { + console.log('❌ No bot instance available'); + return res.status(500).json({ error: 'Bot not available' }); } - res.json({ success: true }); - } catch (error) { - console.error('Fallback notification error:', error); - res.status(500).json({ error: 'Fallback failed' }); + console.log('🤖 Using bot instance for direct send'); + + // Use userId as chatId for private chats (this is how Telegram works) + const chatId = parseInt(userId); + console.log(`📤 Sending audio to chat ${chatId}`); + + await botInstance.sendAudioFile(chatId, audioUrl, title); + console.log('✅ Audio sent successfully via direct API'); + + res.json({ success: true, message: 'Audio sent successfully' }); + } catch (error: any) { + console.error('❌ Direct send error:', error.message); + res.status(500).json({ error: error.message }); } });