Features: - Multi-channel notifications (Email + Telegram) - User-configurable notification settings per channel - Telegram bot integration with rich messages, location pins, and inline buttons - QR code generation for easy bot access (@myidbot support) - Admin UI for notification settings management - Test functionality for Telegram connection - Comprehensive documentation Implementation: - lib/telegram-service.ts: Telegram API integration - lib/notification-settings-db.ts: Database layer for user notification preferences - lib/geofence-notifications.ts: Extended for parallel multi-channel delivery - API routes for settings management and testing - Admin UI with QR code display and step-by-step instructions - Database table: UserNotificationSettings Documentation: - docs/telegram.md: Technical implementation guide - docs/telegram-anleitung.md: User guide with @myidbot instructions - docs/telegram-setup.md: Admin setup guide - README.md: Updated NPM scripts section Docker: - Updated Dockerfile to copy public directory - Added TELEGRAM_BOT_TOKEN environment variable - Integrated notification settings initialization in db:init 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
7.2 KiB
7.2 KiB
🚀 Telegram Integration - Setup Guide
✅ Was wurde implementiert
Dateien erstellt:
-
Backend Services:
lib/telegram-service.ts- Telegram API Integrationlib/notification-settings-db.ts- Datenbank-Layer für Settingslib/geofence-notifications.ts- Erweitert für Multi-Channel (Email + Telegram)
-
Database:
scripts/init-notification-settings.js- DB Init Script- Tabelle:
UserNotificationSettingserstellt
-
API Endpoints:
GET/PATCH /api/users/[id]/notification-settings- Settings verwaltenPOST /api/users/[id]/notification-settings/test- Test-Nachricht
-
Admin UI:
app/admin/settings/notifications/page.tsx- Settings Page mit QR Code
-
Dokumentation:
docs/telegram-anleitung.md- User-Anleitungdocs/telegram-setup.md- Dieses Dokumentpublic/telegram-bot-qr.png- QR Code für Bot
🔧 Installation & Setup
1. Dependencies installiert
✅ npm install axios
✅ npm install qrcode
2. Datenbank initialisiert
✅ node scripts/init-notification-settings.js
Die Tabelle UserNotificationSettings wurde erstellt mit:
user_id(PK, FK → User.id)email_enabled(0/1)telegram_enabled(0/1)telegram_chat_id(TEXT)created_at,updated_at
📱 Bot Setup
Telegram Bot erstellen (für Admin):
- Öffne Telegram und suche: @BotFather
- Sende:
/newbot - Folge den Anweisungen:
- Bot Name:
MeinTracking Bot(oder anders) - Bot Username:
MeinTracking_bot(muss auf_botenden)
- Bot Name:
- BotFather gibt dir einen Token:
1234567890:ABCdefGHIjklMNOpqrsTUVwxyz - Wichtig: Token NIEMALS committen!
.env konfigurieren:
# .env oder .env.local
TELEGRAM_BOT_TOKEN=1234567890:ABCdefGHIjklMNOpqrsTUVwxyz
🎯 Für User: Bot aktivieren
Schritt-für-Schritt siehe: docs/telegram-anleitung.md
Kurzversion:
- Bot starten: https://t.me/MeinTracking_bot oder QR scannen
- Chat ID holen:
@myidbot→/getid(oder@userinfobot→/start) - Im Dashboard: Settings → Notifications → Chat ID eintragen
- Test Button drücken
🧪 Testing
1. QR Code generieren
npm run telegram:qr
Erstellt: public/telegram-bot-qr.png
2. Datenbank neu initialisieren
npm run db:init:notifications
Oder alles zusammen:
npm run db:init
3. Test-Nachricht senden
Option A: Über Admin UI
- Navigiere zu:
/admin/settings/notifications - Telegram aktivieren
- Chat ID eintragen
- Button "Telegram Test" klicken
Option B: Direkt via Script
Erstelle scripts/test-telegram.js:
const { telegramService } = require('../lib/telegram-service');
const CHAT_ID = '123456789'; // Deine Chat ID
async function test() {
await telegramService.testConnection(CHAT_ID);
}
test();
TELEGRAM_BOT_TOKEN=dein_token node scripts/test-telegram.js
🔐 Sicherheit & Privacy
Wie funktioniert die Privacy?
- 1 Bot für alle User (in
.env) - Jeder User hat eigene Chat ID (in DB)
- Bot sendet nur an spezifische Chat ID → Privater 1-zu-1 Chat
- User A sieht NIEMALS Nachrichten von User B
Telegram API Garantie:
telegram.sendMessage(chatId: "123456789", text: "...")
→ Geht NUR an Chat ID 123456789
→ Andere Chat IDs können dies NICHT sehen
Vergleich:
Wie Email: 1 SMTP-Server (Bot) sendet an verschiedene Adressen (Chat IDs)
📊 Wie es funktioniert
Notification Flow:
1. Device triggers Geofence
↓
2. geofence-engine.ts erkennt Event
↓
3. GeofenceEvent in DB erstellt
↓
4. geofence-notifications.ts aufgerufen
↓
5. getUserNotificationSettings(owner_id)
↓
6. Parallel execution:
├─→ Email (if enabled)
└─→ Telegram (if enabled)
↓
├─→ Text mit Emoji, Device, Geofence, Zeit
├─→ Inline Buttons (Karte, Dashboard)
└─→ Location Pin
Multi-Channel Strategy:
- Promise.allSettled() → Beide parallel
- Mind. 1 erfolgreich → Event als "sent" markiert
- Beide fehlgeschlagen → Event als "failed" markiert
- Robust: Email-Fehler betrifft nicht Telegram (und umgekehrt)
🎨 Admin UI Features
Page: /admin/settings/notifications
Komponenten:
- ☑️ Email Benachrichtigungen Toggle
- ☑️ Telegram Benachrichtigungen Toggle
- 📝 Telegram Chat ID Input
- 💾 Speichern Button
- 🧪 Telegram Test Button
- 📱 QR Code Display (400x400px)
- 📖 Schritt-für-Schritt Anleitung
🛠️ NPM Scripts
# Datenbank initialisieren
npm run db:init # Alles (inkl. Notifications)
npm run db:init:notifications # Nur Notifications Tabelle
# QR Code generieren
npm run telegram:qr # Erstellt public/telegram-bot-qr.png
# Testing
npm run test:geofence # Geofence Event simulieren
npm run test:geofence:email # Email Notification testen
📝 Telegram Message Format
Enter Event:
🟢 Geofence BETRETEN
📱 Device: Mein iPhone
📍 Geofence: Zuhause
🕐 Zeit: 04.12.25, 14:30
📊 Ereignis: Hat Zuhause betreten
+ Location Pin (Karte mit exakter Position)
+ Buttons:
- 🗺️ Auf Karte zeigen →
/map?lat=...&lon=... - 📊 Dashboard öffnen →
/admin/geofences/events
Exit Event:
🔴 Geofence VERLASSEN
📱 Device: Mein iPhone
📍 Geofence: Zuhause
🕐 Zeit: 04.12.25, 18:45
📊 Ereignis: Hat Zuhause verlassen
🚨 Troubleshooting
"Cannot find module telegram-service"
→ TypeScript nicht kompiliert. Lösung:
npm run build
Oder für Development:
npm run dev
"Telegram bot token not configured"
→ .env fehlt TELEGRAM_BOT_TOKEN
"Failed to send test message"
Mögliche Ursachen:
- Bot nicht gestartet (
/startan @MeinTracking_bot) - Chat ID falsch
- Bot blockiert
- Token falsch/abgelaufen
Debug:
# Check .env
cat .env | grep TELEGRAM
# Check DB
sqlite3 data/database.sqlite "SELECT * FROM UserNotificationSettings;"
# Test Telegram API direkt
curl https://api.telegram.org/bot<TOKEN>/getMe
QR Code wird nicht angezeigt
→ Prüfen ob Datei existiert:
ls -la public/telegram-bot-qr.png
Falls nicht:
npm run telegram:qr
📚 Environment Variables
# Required für Telegram
TELEGRAM_BOT_TOKEN=<dein_bot_token>
# Optional (für Map/Dashboard Links)
NEXTAUTH_URL=https://deine-domain.de
🎯 Nächste Schritte
Für Produktion:
- ✅
.env.productionmit echtem Bot-Token erstellen - ✅ Datenbank migrieren:
npm run db:init - ✅ QR Code generieren:
npm run telegram:qr - ✅ User-Anleitung teilen:
docs/telegram-anleitung.md - ✅ Test durchführen mit echtem Device
Optional:
- Push Notifications hinzufügen
- SMS Integration
- Webhook Support
- Notification History UI
- Per-Geofence Settings (nicht global)
📞 Support
Bot: @MeinTracking_bot
Dokumentation:
- User-Anleitung:
docs/telegram-anleitung.md - API Implementierung:
docs/telegram.md - Dieses Setup-Guide:
docs/telegram-setup.md
Letzte Aktualisierung: 04.12.2025