create-bunspace 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/templates/fumadocs/content-template/docs/index.mdx +2 -0
- package/dist/templates/fumadocs/content-template/en/docs/index.mdx +2 -0
- package/dist/templates/telegram-bot/CLAUDE.deploy.md +2 -3
- package/dist/templates/telegram-bot/CLAUDE.dev.md +304 -5
- package/dist/templates/telegram-bot/CLAUDE.md +166 -89
- package/dist/templates/telegram-bot/README.md +252 -129
- package/dist/templates/telegram-bot/bun.lock +146 -3
- package/dist/templates/telegram-bot/core/.env.example +6 -0
- package/dist/templates/telegram-bot/core/src/config/env.ts +130 -1
- package/dist/templates/telegram-bot/core/src/config/logging.ts +3 -1
- package/dist/templates/telegram-bot/core/src/handlers/config-export.ts +122 -0
- package/dist/templates/telegram-bot/core/src/handlers/control.ts +37 -11
- package/dist/templates/telegram-bot/core/src/handlers/health.ts +21 -26
- package/dist/templates/telegram-bot/core/src/handlers/info.ts +191 -0
- package/dist/templates/telegram-bot/core/src/handlers/listener.ts +168 -0
- package/dist/templates/telegram-bot/core/src/handlers/logs.ts +14 -7
- package/dist/templates/telegram-bot/core/src/index.ts +29 -0
- package/dist/templates/telegram-bot/core/src/utils/formatters.ts +55 -19
- package/dist/templates/telegram-bot/core/src/utils/instance-manager.ts +6 -2
- package/dist/templates/telegram-bot/core/src/utils/message-builder.ts +180 -0
- package/dist/templates/telegram-bot/docs/automatizacion_integral_de_bots_de_telegram_con_type_script.md +326 -0
- package/dist/templates/telegram-bot/docs/cli-commands.md +514 -5
- package/dist/templates/telegram-bot/docs/environment.md +191 -3
- package/dist/templates/telegram-bot/docs/getting-started.md +202 -15
- package/dist/templates/telegram-bot/package.json +5 -2
- package/dist/templates/telegram-bot/packages/utils/src/logger.ts +1 -0
- package/dist/templates/telegram-bot/tools/commands/doctor.ts +62 -0
- package/dist/templates/telegram-bot/tools/commands/setup.ts +984 -170
- package/package.json +1 -1
- package/templates/fumadocs/content-template/docs/index.mdx +2 -0
- package/templates/fumadocs/content-template/en/docs/index.mdx +2 -0
- package/templates/telegram-bot/CLAUDE.deploy.md +2 -3
- package/templates/telegram-bot/CLAUDE.dev.md +304 -5
- package/templates/telegram-bot/CLAUDE.md +166 -89
- package/templates/telegram-bot/README.md +252 -129
- package/templates/telegram-bot/bun.lock +146 -3
- package/templates/telegram-bot/core/.env.example +6 -0
- package/templates/telegram-bot/core/src/config/env.ts +130 -1
- package/templates/telegram-bot/core/src/config/logging.ts +3 -1
- package/templates/telegram-bot/core/src/handlers/config-export.ts +122 -0
- package/templates/telegram-bot/core/src/handlers/control.ts +37 -11
- package/templates/telegram-bot/core/src/handlers/health.ts +21 -26
- package/templates/telegram-bot/core/src/handlers/info.ts +191 -0
- package/templates/telegram-bot/core/src/handlers/listener.ts +168 -0
- package/templates/telegram-bot/core/src/handlers/logs.ts +14 -7
- package/templates/telegram-bot/core/src/index.ts +29 -0
- package/templates/telegram-bot/core/src/utils/formatters.ts +55 -19
- package/templates/telegram-bot/core/src/utils/instance-manager.ts +6 -2
- package/templates/telegram-bot/core/src/utils/message-builder.ts +180 -0
- package/templates/telegram-bot/docs/automatizacion_integral_de_bots_de_telegram_con_type_script.md +326 -0
- package/templates/telegram-bot/docs/cli-commands.md +514 -5
- package/templates/telegram-bot/docs/environment.md +191 -3
- package/templates/telegram-bot/docs/getting-started.md +202 -15
- package/templates/telegram-bot/package.json +5 -2
- package/templates/telegram-bot/packages/utils/src/logger.ts +1 -0
- package/templates/telegram-bot/tools/commands/doctor.ts +62 -0
- package/templates/telegram-bot/tools/commands/setup.ts +984 -170
|
@@ -5,9 +5,8 @@
|
|
|
5
5
|
Guía de deployment para multi-entorno y multi-instancia.
|
|
6
6
|
|
|
7
7
|
**Documentación relacionada**:
|
|
8
|
-
- [docs/
|
|
9
|
-
- [docs/
|
|
10
|
-
- [docs/deployment/environments.mdx](./docs/deployment/environments.mdx)
|
|
8
|
+
- [docs/environment.md](./docs/environment.md)
|
|
9
|
+
- [docs/troubleshooting.md](./docs/troubleshooting.md)
|
|
11
10
|
|
|
12
11
|
---
|
|
13
12
|
|
|
@@ -5,8 +5,8 @@
|
|
|
5
5
|
Guía de desarrollo para extender y modificar el bot template.
|
|
6
6
|
|
|
7
7
|
**Documentación relacionada**:
|
|
8
|
-
- [docs/development
|
|
9
|
-
- [docs/
|
|
8
|
+
- [docs/development.md](./docs/development.md)
|
|
9
|
+
- [docs/getting-started.md](./docs/getting-started.md)
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
@@ -38,13 +38,34 @@ Guía de desarrollo para extender y modificar el bot template.
|
|
|
38
38
|
|
|
39
39
|
```typescript
|
|
40
40
|
import type { Context } from 'telegraf'
|
|
41
|
+
import { myCommandLogger, badge, kv, colors, colorText } from '../middleware/logging.js'
|
|
41
42
|
|
|
42
43
|
export async function handleMyCommand(ctx: Context): Promise<void> {
|
|
43
|
-
|
|
44
|
+
const userId = ctx.from?.id ?? 'unknown'
|
|
45
|
+
|
|
46
|
+
myCommandLogger.debug(
|
|
47
|
+
`${badge('MYCMD', 'rounded')} ${kv({
|
|
48
|
+
cmd: '/mycommand',
|
|
49
|
+
user: colorText(String(userId), colors.user),
|
|
50
|
+
})}`
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
// Lógica del comando...
|
|
54
|
+
|
|
55
|
+
await ctx.reply('Respuesta del comando', { parse_mode: 'Markdown' })
|
|
44
56
|
}
|
|
45
57
|
```
|
|
46
58
|
|
|
47
|
-
### 2.
|
|
59
|
+
### 2. Agregar Logger Especializado (si no existe)
|
|
60
|
+
|
|
61
|
+
**Archivo**: `core/src/middleware/logging.ts`
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
import { component } from '@mks2508/better-logger'
|
|
65
|
+
export const myCommandLogger = component('MyCommand')
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 3. Registrar en Bot
|
|
48
69
|
|
|
49
70
|
**Archivo**: `core/src/index.ts`
|
|
50
71
|
|
|
@@ -255,7 +276,285 @@ bun test # Run tests
|
|
|
255
276
|
- `core/src/handlers/` - Command handlers
|
|
256
277
|
- `core/src/middleware/` - Telegraf middleware
|
|
257
278
|
- `core/src/config/` - Configuration and env validation
|
|
258
|
-
- `
|
|
279
|
+
- `core/src/utils/` - Utilities (formatters, instance-manager, etc.)
|
|
280
|
+
|
|
281
|
+
---
|
|
282
|
+
|
|
283
|
+
## ⚠️ Mejores Prácticas - CRÍTICO
|
|
284
|
+
|
|
285
|
+
### 🔴 Errores Comunes a EVITAR
|
|
286
|
+
|
|
287
|
+
#### 1. NO poner código de comandos en `index.ts`
|
|
288
|
+
|
|
289
|
+
❌ **INCORRECTO**:
|
|
290
|
+
```typescript
|
|
291
|
+
// core/src/index.ts
|
|
292
|
+
bot.command('mycommand', async (ctx) => {
|
|
293
|
+
// ... 50 líneas de código ...
|
|
294
|
+
ctx.reply('...')
|
|
295
|
+
})
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
✅ **CORRECTO**:
|
|
299
|
+
```typescript
|
|
300
|
+
// core/src/handlers/mycommand.ts
|
|
301
|
+
export async function handleMyCommand(ctx: Context): Promise<void> {
|
|
302
|
+
// ...
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// core/src/index.ts
|
|
306
|
+
import { handleMyCommand } from './handlers/mycommand.js'
|
|
307
|
+
bot.command('mycommand', handleMyCommand)
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
#### 2. NO usar `console.*` - SIEMPRE usar Better Logger
|
|
311
|
+
|
|
312
|
+
❌ **INCORRECTO**:
|
|
313
|
+
```typescript
|
|
314
|
+
console.log('Bot iniciado')
|
|
315
|
+
console.error('Error:', error)
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
✅ **CORRECTO**:
|
|
319
|
+
```typescript
|
|
320
|
+
import { botLogger } from './middleware/logging.js'
|
|
321
|
+
botLogger.info('Bot iniciado')
|
|
322
|
+
botLogger.error('Error:', error)
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
#### 3. NO repetir lógica de formateo - USAR helpers existentes
|
|
326
|
+
|
|
327
|
+
❌ **INCORRECTO**:
|
|
328
|
+
```typescript
|
|
329
|
+
const uptime = Math.floor(ms / 1000) + 's'
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
✅ **CORRECTO**:
|
|
333
|
+
```typescript
|
|
334
|
+
import { formatDuration } from './middleware/logging.js'
|
|
335
|
+
const uptime = formatDuration(ms)
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
#### 4. NO usar backticks en template strings de Markdown
|
|
339
|
+
|
|
340
|
+
❌ **INCORRECTO** (causa error de sintaxis):
|
|
341
|
+
```typescript
|
|
342
|
+
info += `User ID: \`${userId}\`\n` // ❌ Backtick dentro de template string
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
✅ **CORRECTO**:
|
|
346
|
+
```typescript
|
|
347
|
+
const backtick = '`'
|
|
348
|
+
info += `User ID: ${backtick}${userId}${backtick}\n`
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
#### 5. NO olvidar type guards para propiedades opcionales de Telegraf
|
|
352
|
+
|
|
353
|
+
❌ **INCORRECTO**:
|
|
354
|
+
```typescript
|
|
355
|
+
if (chat.title) info += chat.title // Error si chat es PrivateChat
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
✅ **CORRECTO**:
|
|
359
|
+
```typescript
|
|
360
|
+
if ('title' in chat && chat.title) info += chat.title
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
---
|
|
364
|
+
|
|
365
|
+
### ✅ Checklist ANTES de implementar funcionalidad
|
|
366
|
+
|
|
367
|
+
Antes de agregar comandos o funcionalidades:
|
|
368
|
+
|
|
369
|
+
- [ ] **Revisar handlers existentes** - `core/src/handlers/health.ts`, `control.ts`, `logs.ts`
|
|
370
|
+
- [ ] **Revisar utils existentes** - `core/src/utils/formatters.ts`, `telegram.ts`
|
|
371
|
+
- [ ] **Revisar loggers disponibles** - `packages/utils/src/logger.ts`
|
|
372
|
+
- [ ] **Seguir el patrón de logging**: `badge()` + `kv()` + `colorText()`
|
|
373
|
+
- [ ] **Usar formatters existentes**: `formatUptime()`, `formatHealthMessage()`, etc.
|
|
374
|
+
- [ ] **Crear handler separado** - NUNCA en `index.ts`
|
|
375
|
+
- [ ] **Agregar logger especializado** si es un comando nuevo
|
|
376
|
+
- [ ] **Type guards para propiedades opcionales** de objetos de Telegraf
|
|
377
|
+
|
|
378
|
+
---
|
|
379
|
+
|
|
380
|
+
### 📁 Estructura de Archivos
|
|
381
|
+
|
|
382
|
+
```
|
|
383
|
+
core/src/
|
|
384
|
+
├── handlers/ # ← TODOS los comandos van aquí
|
|
385
|
+
│ ├── health.ts # /health, /uptime, /stats
|
|
386
|
+
│ ├── control.ts # /stop, /restart, /mode
|
|
387
|
+
│ ├── logs.ts # /logs
|
|
388
|
+
│ └── info.ts # /getinfo
|
|
389
|
+
├── middleware/ # Telegraf middleware
|
|
390
|
+
│ ├── auth.ts
|
|
391
|
+
│ ├── error-handler.ts
|
|
392
|
+
│ ├── topics.ts
|
|
393
|
+
│ └── logging.ts # Reexporta desde utils
|
|
394
|
+
├── utils/ # Helpers y formatters
|
|
395
|
+
│ ├── formatters.ts # formatUptime, formatHealth, etc.
|
|
396
|
+
│ ├── telegram.ts # formatBytes, formatMemory, etc.
|
|
397
|
+
│ ├── bot-manager.ts
|
|
398
|
+
│ └── instance-manager.ts
|
|
399
|
+
└── index.ts # SOLO registro de comandos
|
|
400
|
+
# NO lógica de comandos aquí
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
---
|
|
404
|
+
|
|
405
|
+
### 🎯 Patrones de Código a SEGUIR
|
|
406
|
+
|
|
407
|
+
#### Patrón de Handler
|
|
408
|
+
|
|
409
|
+
```typescript
|
|
410
|
+
import type { Context } from 'telegraf'
|
|
411
|
+
import { xxxLogger, badge, kv, colors, colorText } from '../middleware/logging.js'
|
|
412
|
+
import { formatXxx } from '../utils/formatters.js'
|
|
413
|
+
|
|
414
|
+
export async function handleXxx(ctx: Context): Promise<void> {
|
|
415
|
+
// 1. Logging con badge + kv + colorText
|
|
416
|
+
xxxLogger.debug(
|
|
417
|
+
`${badge('XXX', 'rounded')} ${kv({
|
|
418
|
+
cmd: '/xxx',
|
|
419
|
+
user: colorText(String(ctx.from?.id), colors.user),
|
|
420
|
+
})}`
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
// 2. Lógica del comando
|
|
424
|
+
// ...
|
|
425
|
+
|
|
426
|
+
// 3. Formatear respuesta usando helpers
|
|
427
|
+
const message = formatXxx(data)
|
|
428
|
+
|
|
429
|
+
// 4. Responder
|
|
430
|
+
await ctx.reply(message, { parse_mode: 'Markdown' })
|
|
431
|
+
}
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
#### Patrón de Logging
|
|
435
|
+
|
|
436
|
+
```typescript
|
|
437
|
+
// Debug info para tracking
|
|
438
|
+
xxxLogger.debug(`${badge('CMD', 'rounded')} ${kv({ cmd: '/xxx', user: id })}`)
|
|
439
|
+
|
|
440
|
+
// Info para eventos importantes
|
|
441
|
+
xxxLogger.info('Operación completada')
|
|
442
|
+
|
|
443
|
+
// Success para confirmaciones
|
|
444
|
+
xxxLogger.success('Configuración actualizada')
|
|
445
|
+
|
|
446
|
+
// Warning para situaciones anormales no-críticas
|
|
447
|
+
xxxLogger.warn('Valor inválido, usando default')
|
|
448
|
+
|
|
449
|
+
// Error para fallos
|
|
450
|
+
xxxLogger.error('Fallo al procesar:', error)
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
---
|
|
454
|
+
|
|
455
|
+
## 🧵 Topics y Organización de Grupos
|
|
456
|
+
|
|
457
|
+
El bot soporta **Forum Topics** de Telegram para mantener el chat organizado.
|
|
458
|
+
|
|
459
|
+
### Detectar Thread ID
|
|
460
|
+
|
|
461
|
+
Para obtener el Thread ID de un topic:
|
|
462
|
+
|
|
463
|
+
```typescript
|
|
464
|
+
import { getThreadId } from './handlers/info.js'
|
|
465
|
+
|
|
466
|
+
// En cualquier handler
|
|
467
|
+
const threadId = getThreadId(ctx.message)
|
|
468
|
+
if (threadId) {
|
|
469
|
+
logger.info(`Message sent in thread ${threadId}`)
|
|
470
|
+
}
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
### Configuración por Topic
|
|
474
|
+
|
|
475
|
+
```typescript
|
|
476
|
+
// middleware/topics.ts - Ya implementado en el template
|
|
477
|
+
export function topicValidation() {
|
|
478
|
+
return async (ctx, next) => {
|
|
479
|
+
const config = getConfig()
|
|
480
|
+
|
|
481
|
+
// Si hay un topic de control configurado, validar
|
|
482
|
+
if (config.controlTopicId) {
|
|
483
|
+
const threadId = getThreadId(ctx.message)
|
|
484
|
+
|
|
485
|
+
// Comandos de control solo en el topic específico
|
|
486
|
+
if (ctx.message?.text?.startsWith('/')) {
|
|
487
|
+
const isControlCommand = CONTROL_COMMANDS.some(cmd =>
|
|
488
|
+
ctx.message?.text?.startsWith(cmd)
|
|
489
|
+
)
|
|
490
|
+
|
|
491
|
+
if (isControlCommand && threadId !== config.controlTopicId) {
|
|
492
|
+
return // Ignorar comando fuera del topic
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
return next()
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
```
|
|
501
|
+
|
|
502
|
+
### Helper Function
|
|
503
|
+
|
|
504
|
+
Usa la función `getThreadId()` para detectar topics:
|
|
505
|
+
|
|
506
|
+
```typescript
|
|
507
|
+
/**
|
|
508
|
+
* Get thread ID from a message
|
|
509
|
+
* Checks multiple possible locations where thread_id can be stored
|
|
510
|
+
*/
|
|
511
|
+
function getThreadId(msg: any): number | undefined {
|
|
512
|
+
if (!msg) return undefined
|
|
513
|
+
|
|
514
|
+
// Direct thread_id property (forum topics)
|
|
515
|
+
if ('thread_id' in msg && typeof msg.thread_id === 'number') {
|
|
516
|
+
return msg.thread_id
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
// message_thread_id (alternative property)
|
|
520
|
+
if ('message_thread_id' in msg && typeof msg.message_thread_id === 'number') {
|
|
521
|
+
return msg.message_thread_id
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// Check in reply_to_message
|
|
525
|
+
if ('reply_to_message' in msg && msg.reply_to_message) {
|
|
526
|
+
const replyTo = msg.reply_to_message
|
|
527
|
+
|
|
528
|
+
if ('thread_id' in replyTo && typeof replyTo.thread_id === 'number') {
|
|
529
|
+
return replyTo.thread_id
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if ('message_thread_id' in replyTo && typeof replyTo.message_thread_id === 'number') {
|
|
533
|
+
return replyTo.message_thread_id
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
return undefined
|
|
538
|
+
}
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
### Mejores Prácticas para Topics
|
|
542
|
+
|
|
543
|
+
1. **Separa preocupaciones:**
|
|
544
|
+
- Topic "General" - Chat casual
|
|
545
|
+
- Topic "Control" - Solo comandos de control
|
|
546
|
+
- Topic "Logs" - Streaming de logs
|
|
547
|
+
- Topic "Config" - Discusiones de configuración
|
|
548
|
+
|
|
549
|
+
2. **Usa `/getinfo` en cada topic:**
|
|
550
|
+
- Envia `/getinfo` dentro del topic
|
|
551
|
+
- Copia el Thread ID mostrado
|
|
552
|
+
- Configúralo en `.env`
|
|
553
|
+
|
|
554
|
+
3. **Valida location de comandos:**
|
|
555
|
+
- Comandos de control → Solo en topic "Control"
|
|
556
|
+
- Logs → Solo en topic "Logs"
|
|
557
|
+
- Públicos → Cualquier topic
|
|
259
558
|
|
|
260
559
|
---
|
|
261
560
|
|