- Add 100 blog posts covering AI, development, and tech topics - Add .env.example for environment configuration - Add accessibility and lighthouse audit scripts - Remove obsolete SEO reports and temporary files - Remove dev-dist build artifacts and backup files - Remove unused portrait images (moved/consolidated elsewhere) - Update contact form and component improvements Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
250 lines
7.7 KiB
Markdown
250 lines
7.7 KiB
Markdown
# Telegram-Bots mit KI: Vom Proof-of-Concept zur Enterprise-Lösung
|
|
|
|
**Meta-Description:** Entwickeln Sie skalierbare AI-powered Telegram-Bots mit Node.js. Telegraf, GrammyJS, OpenAI-Integration und Production-Patterns für Enterprise.
|
|
|
|
**Keywords:** Telegram Bot, AI Bot, Telegraf, GrammyJS, Node.js Bot, ChatGPT Telegram, Enterprise Bot, Bot Development
|
|
|
|
---
|
|
|
|
## Einführung
|
|
|
|
Telegram-Bots mit KI-Integration revolutionieren Kundeninteraktion. Mit Webhooks für Echtzeit-Updates, natürlicher Sprachverarbeitung durch LLMs und einer API, die 400+ Millionen aktive User erreicht.
|
|
|
|
---
|
|
|
|
## Framework-Vergleich
|
|
|
|
| Framework | Stärke | TypeScript | Aktiv gepflegt |
|
|
|-----------|--------|------------|----------------|
|
|
| **Telegraf** | Middleware-System | Ja | Ja |
|
|
| **GrammyJS** | Leichtgewichtig | Ja | Ja |
|
|
| **node-telegram-bot-api** | Einfachheit | Types verfügbar | Ja |
|
|
|
|
---
|
|
|
|
## Projekt-Setup mit Telegraf
|
|
|
|
```typescript
|
|
// src/bot.ts
|
|
import { Telegraf, Context } from 'telegraf';
|
|
import { message } from 'telegraf/filters';
|
|
import OpenAI from 'openai';
|
|
|
|
const bot = new Telegraf(process.env.BOT_TOKEN!);
|
|
const openai = new OpenAI();
|
|
|
|
// Conversation History pro User
|
|
const conversations = new Map<number, Message[]>();
|
|
|
|
// AI-Response Middleware
|
|
bot.on(message('text'), async (ctx) => {
|
|
const userId = ctx.from.id;
|
|
const userMessage = ctx.message.text;
|
|
|
|
// History abrufen oder initialisieren
|
|
let history = conversations.get(userId) || [];
|
|
|
|
// User-Nachricht hinzufügen
|
|
history.push({ role: 'user', content: userMessage });
|
|
|
|
// AI-Antwort generieren
|
|
const response = await openai.chat.completions.create({
|
|
model: 'gpt-4o',
|
|
messages: [
|
|
{ role: 'system', content: 'Du bist ein hilfreicher Assistent.' },
|
|
...history
|
|
],
|
|
max_tokens: 500
|
|
});
|
|
|
|
const assistantMessage = response.choices[0].message.content!;
|
|
|
|
// History aktualisieren
|
|
history.push({ role: 'assistant', content: assistantMessage });
|
|
conversations.set(userId, history.slice(-20)); // Letzte 20 behalten
|
|
|
|
await ctx.reply(assistantMessage);
|
|
});
|
|
|
|
// Webhook für Production
|
|
if (process.env.NODE_ENV === 'production') {
|
|
bot.launch({
|
|
webhook: {
|
|
domain: process.env.WEBHOOK_DOMAIN!,
|
|
port: Number(process.env.PORT) || 3000
|
|
}
|
|
});
|
|
} else {
|
|
bot.launch(); // Polling für Development
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Skalierbare Architektur
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────────────────┐
|
|
│ PRODUCTION ARCHITECTURE │
|
|
├─────────────────────────────────────────────────────────────┤
|
|
│ │
|
|
│ Telegram API │
|
|
│ │ │
|
|
│ ▼ │
|
|
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
|
│ │ NGINX │────→│ Bot App │────→│ Redis │ │
|
|
│ │ (Webhook) │ │ (Node.js) │ │ (Queue) │ │
|
|
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
|
│ │ │ │
|
|
│ ▼ ▼ │
|
|
│ ┌─────────────┐ ┌─────────────┐ │
|
|
│ │ OpenAI │ │ BullMQ │ │
|
|
│ │ API │ │ (Workers) │ │
|
|
│ └─────────────┘ └─────────────┘ │
|
|
│ │
|
|
└─────────────────────────────────────────────────────────────┘
|
|
```
|
|
|
|
---
|
|
|
|
## Message Queue für Heavy Tasks
|
|
|
|
```typescript
|
|
// src/queue.ts
|
|
import { Queue, Worker } from 'bullmq';
|
|
import { Redis } from 'ioredis';
|
|
|
|
const redis = new Redis(process.env.REDIS_URL!);
|
|
|
|
// Queue für AI-Verarbeitung
|
|
const aiQueue = new Queue('ai-processing', { connection: redis });
|
|
|
|
// Worker für Verarbeitung
|
|
const worker = new Worker('ai-processing', async (job) => {
|
|
const { userId, message, chatId } = job.data;
|
|
|
|
// Lange AI-Operation
|
|
const response = await generateComplexResponse(message);
|
|
|
|
// Antwort senden
|
|
await bot.telegram.sendMessage(chatId, response);
|
|
}, { connection: redis });
|
|
|
|
// In Bot-Handler
|
|
bot.on(message('text'), async (ctx) => {
|
|
// Sofort bestätigen
|
|
await ctx.reply('Wird verarbeitet...');
|
|
|
|
// In Queue einreihen
|
|
await aiQueue.add('process', {
|
|
userId: ctx.from.id,
|
|
message: ctx.message.text,
|
|
chatId: ctx.chat.id
|
|
});
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
## Inline-Keyboards für Interaktivität
|
|
|
|
```typescript
|
|
bot.command('menu', async (ctx) => {
|
|
await ctx.reply('Wähle eine Option:', {
|
|
reply_markup: {
|
|
inline_keyboard: [
|
|
[
|
|
{ text: '🔍 Suchen', callback_data: 'search' },
|
|
{ text: '📊 Status', callback_data: 'status' }
|
|
],
|
|
[
|
|
{ text: '⚙️ Einstellungen', callback_data: 'settings' }
|
|
]
|
|
]
|
|
}
|
|
});
|
|
});
|
|
|
|
bot.action('search', async (ctx) => {
|
|
await ctx.answerCbQuery();
|
|
await ctx.reply('Was möchtest du suchen?');
|
|
// State setzen für nächste Nachricht
|
|
});
|
|
```
|
|
|
|
---
|
|
|
|
## Rate Limiting
|
|
|
|
```typescript
|
|
import rateLimit from 'telegraf-ratelimit';
|
|
|
|
const limitConfig = {
|
|
window: 3000, // 3 Sekunden
|
|
limit: 1, // 1 Nachricht
|
|
onLimitExceeded: (ctx) => ctx.reply('Bitte warte einen Moment...')
|
|
};
|
|
|
|
bot.use(rateLimit(limitConfig));
|
|
```
|
|
|
|
---
|
|
|
|
## Error Handling
|
|
|
|
```typescript
|
|
bot.catch((err, ctx) => {
|
|
console.error(`Error for ${ctx.updateType}`, err);
|
|
|
|
// User-freundliche Fehlermeldung
|
|
ctx.reply('Ein Fehler ist aufgetreten. Bitte versuche es erneut.')
|
|
.catch(() => {}); // Ignoriere wenn Reply auch fehlschlägt
|
|
});
|
|
|
|
// Graceful Shutdown
|
|
process.once('SIGINT', () => bot.stop('SIGINT'));
|
|
process.once('SIGTERM', () => bot.stop('SIGTERM'));
|
|
```
|
|
|
|
---
|
|
|
|
## Deployment Checklist
|
|
|
|
- [ ] Webhook statt Polling für Production
|
|
- [ ] Redis für Session-Management
|
|
- [ ] BullMQ für lange Tasks
|
|
- [ ] Rate Limiting implementiert
|
|
- [ ] Error Handling & Logging
|
|
- [ ] Health Check Endpoint
|
|
- [ ] Graceful Shutdown
|
|
- [ ] Environment Variables sicher
|
|
|
|
---
|
|
|
|
## Fazit
|
|
|
|
Telegram-Bots mit KI-Integration sind 2026 ein mächtiges Tool für:
|
|
- Customer Support Automatisierung
|
|
- Interne Team-Benachrichtigungen
|
|
- Deployment-Kontrolle
|
|
- Incident-Management
|
|
|
|
Mit Webhooks, Queues und proper Error Handling wird aus dem PoC eine Enterprise-Lösung.
|
|
|
|
---
|
|
|
|
## Bildprompts
|
|
|
|
1. "Telegram logo transforming into intelligent robot assistant, blue gradient background, modern app icon style"
|
|
2. "Chat interface with AI responses, smartphone floating in space, clean mockup style"
|
|
3. "Bot architecture diagram with Telegram, AI, and database layers, technical documentation style"
|
|
|
|
---
|
|
|
|
## Quellen
|
|
|
|
- [Telegraf GitHub](https://github.com/telegraf/telegraf)
|
|
- [GrammyJS](https://grammy.dev/)
|
|
- [EvaCodes: Create Telegram Bot 2026](https://evacodes.com/blog/create-telegram-bot)
|
|
- [Medium: Scalable Telegram Bot with BullMQ](https://medium.com/@pushpesh0/building-a-scalable-telegram-bot-with-node-js-bullmq-and-webhooks-6b0070fcbdfc)
|