create-bunspace 0.2.5 → 0.3.1

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.
Files changed (80) hide show
  1. package/dist/templates/monorepo/apps/example/package.json +1 -1
  2. package/dist/templates/monorepo/core/packages/utils/rolldown.config.ts +30 -0
  3. package/dist/templates/monorepo/tsconfig.json +3 -1
  4. package/dist/templates/telegram-bot/CLAUDE.deploy.md +2 -3
  5. package/dist/templates/telegram-bot/CLAUDE.dev.md +304 -5
  6. package/dist/templates/telegram-bot/CLAUDE.md +166 -89
  7. package/dist/templates/telegram-bot/README.md +252 -129
  8. package/dist/templates/telegram-bot/bun.lock +132 -3
  9. package/dist/templates/telegram-bot/core/.env.example +6 -0
  10. package/dist/templates/telegram-bot/core/package.json +11 -0
  11. package/dist/templates/telegram-bot/core/rolldown.config.ts +11 -0
  12. package/dist/templates/telegram-bot/core/src/config/env.ts +130 -1
  13. package/dist/templates/telegram-bot/core/src/config/logging.ts +4 -4
  14. package/dist/templates/telegram-bot/core/src/handlers/config-export.ts +123 -0
  15. package/dist/templates/telegram-bot/core/src/handlers/control.ts +46 -11
  16. package/dist/templates/telegram-bot/core/src/handlers/demo-full.ts +58 -0
  17. package/dist/templates/telegram-bot/core/src/handlers/demo-keyboard.ts +49 -0
  18. package/dist/templates/telegram-bot/core/src/handlers/demo-media.ts +163 -0
  19. package/dist/templates/telegram-bot/core/src/handlers/demo-text.ts +27 -0
  20. package/dist/templates/telegram-bot/core/src/handlers/health.ts +40 -37
  21. package/dist/templates/telegram-bot/core/src/handlers/info.ts +189 -0
  22. package/dist/templates/telegram-bot/core/src/handlers/listener.ts +168 -0
  23. package/dist/templates/telegram-bot/core/src/handlers/logs.ts +16 -7
  24. package/dist/templates/telegram-bot/core/src/index.ts +49 -1
  25. package/dist/templates/telegram-bot/core/src/utils/formatters.ts +14 -33
  26. package/dist/templates/telegram-bot/core/src/utils/instance-manager.ts +6 -2
  27. package/dist/templates/telegram-bot/core/src/utils/message-builder.ts +180 -0
  28. package/dist/templates/telegram-bot/core/tsconfig.json +2 -0
  29. package/dist/templates/telegram-bot/docs/automatizacion_integral_de_bots_de_telegram_con_type_script.md +326 -0
  30. package/dist/templates/telegram-bot/docs/cli-commands.md +514 -5
  31. package/dist/templates/telegram-bot/docs/environment.md +191 -3
  32. package/dist/templates/telegram-bot/docs/getting-started.md +202 -15
  33. package/dist/templates/telegram-bot/package.json +7 -3
  34. package/dist/templates/telegram-bot/packages/utils/package.json +12 -1
  35. package/dist/templates/telegram-bot/packages/utils/rolldown.config.ts +11 -0
  36. package/dist/templates/telegram-bot/packages/utils/src/logger.ts +1 -0
  37. package/dist/templates/telegram-bot/packages/utils/tsconfig.json +10 -0
  38. package/dist/templates/telegram-bot/tools/commands/doctor.ts +62 -0
  39. package/dist/templates/telegram-bot/tools/commands/setup.ts +984 -170
  40. package/dist/templates/telegram-bot/tsconfig.json +7 -2
  41. package/package.json +1 -1
  42. package/templates/monorepo/apps/example/package.json +1 -1
  43. package/templates/monorepo/core/packages/utils/rolldown.config.ts +30 -0
  44. package/templates/monorepo/tsconfig.json +3 -1
  45. package/templates/telegram-bot/CLAUDE.deploy.md +2 -3
  46. package/templates/telegram-bot/CLAUDE.dev.md +304 -5
  47. package/templates/telegram-bot/CLAUDE.md +166 -89
  48. package/templates/telegram-bot/README.md +252 -129
  49. package/templates/telegram-bot/bun.lock +132 -3
  50. package/templates/telegram-bot/core/.env.example +6 -0
  51. package/templates/telegram-bot/core/package.json +11 -0
  52. package/templates/telegram-bot/core/rolldown.config.ts +11 -0
  53. package/templates/telegram-bot/core/src/config/env.ts +130 -1
  54. package/templates/telegram-bot/core/src/config/logging.ts +4 -4
  55. package/templates/telegram-bot/core/src/handlers/config-export.ts +123 -0
  56. package/templates/telegram-bot/core/src/handlers/control.ts +46 -11
  57. package/templates/telegram-bot/core/src/handlers/demo-full.ts +58 -0
  58. package/templates/telegram-bot/core/src/handlers/demo-keyboard.ts +49 -0
  59. package/templates/telegram-bot/core/src/handlers/demo-media.ts +163 -0
  60. package/templates/telegram-bot/core/src/handlers/demo-text.ts +27 -0
  61. package/templates/telegram-bot/core/src/handlers/health.ts +40 -37
  62. package/templates/telegram-bot/core/src/handlers/info.ts +189 -0
  63. package/templates/telegram-bot/core/src/handlers/listener.ts +168 -0
  64. package/templates/telegram-bot/core/src/handlers/logs.ts +16 -7
  65. package/templates/telegram-bot/core/src/index.ts +49 -1
  66. package/templates/telegram-bot/core/src/utils/formatters.ts +14 -33
  67. package/templates/telegram-bot/core/src/utils/instance-manager.ts +6 -2
  68. package/templates/telegram-bot/core/tsconfig.json +2 -0
  69. package/templates/telegram-bot/docs/automatizacion_integral_de_bots_de_telegram_con_type_script.md +326 -0
  70. package/templates/telegram-bot/docs/cli-commands.md +514 -5
  71. package/templates/telegram-bot/docs/environment.md +191 -3
  72. package/templates/telegram-bot/docs/getting-started.md +202 -15
  73. package/templates/telegram-bot/package.json +7 -3
  74. package/templates/telegram-bot/packages/utils/package.json +12 -1
  75. package/templates/telegram-bot/packages/utils/rolldown.config.ts +11 -0
  76. package/templates/telegram-bot/packages/utils/src/logger.ts +1 -0
  77. package/templates/telegram-bot/packages/utils/tsconfig.json +10 -0
  78. package/templates/telegram-bot/tools/commands/doctor.ts +62 -0
  79. package/templates/telegram-bot/tools/commands/setup.ts +984 -170
  80. package/templates/telegram-bot/tsconfig.json +7 -2
@@ -0,0 +1,180 @@
1
+ import telegramFormat from '@flla/telegram-format'
2
+ import type { Formatter } from '@flla/telegram-format'
3
+
4
+ // Get the formatters from the main module
5
+ const { html } = telegramFormat
6
+
7
+ /**
8
+ * MessageBuilder - Fluent API for building formatted Telegram messages
9
+ *
10
+ * Provides a consistent way to build messages without worrying about:
11
+ * - Proper escaping of special characters
12
+ * - Format consistency (Markdown vs HTML)
13
+ * - Parse errors from malformed entities
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const message = MessageBuilder.markdown()
18
+ * .title('User Information')
19
+ * .newline()
20
+ * .line('User ID', '123456', { code: true })
21
+ * .line('Username', '@john_doe')
22
+ * .build()
23
+ * ```
24
+ */
25
+ export class MessageBuilder {
26
+ private parts: string[] = []
27
+ private listDepth = 0
28
+
29
+ private constructor(
30
+ private formatter: Formatter,
31
+ private parseModeValue: 'Markdown' | 'HTML' | 'MarkdownV2'
32
+ ) {}
33
+
34
+ /**
35
+ * Create an HTML message builder (default)
36
+ * HTML is simpler and more reliable than MarkdownV2
37
+ */
38
+ static markdown(): MessageBuilder {
39
+ return new MessageBuilder(html as unknown as Formatter, 'HTML')
40
+ }
41
+
42
+ /**
43
+ * Create an HTML message builder
44
+ */
45
+ static html(): MessageBuilder {
46
+ return new MessageBuilder(html as unknown as Formatter, 'HTML')
47
+ }
48
+
49
+ /**
50
+ * Add a title/heading (bold)
51
+ */
52
+ title(text: string): this {
53
+ this.parts.push(this.formatter.bold(text))
54
+ return this
55
+ }
56
+
57
+ /**
58
+ * Add a section heading (underline/italic)
59
+ */
60
+ section(text: string): this {
61
+ this.parts.push(this.formatter.underline(text))
62
+ return this
63
+ }
64
+
65
+ /**
66
+ * Add a key-value line
67
+ * @param key - The label/key
68
+ * @param value - The value
69
+ * @param opts - Options for formatting the value
70
+ */
71
+ line(key: string, value: string, opts?: { code?: boolean; bold?: boolean }): this {
72
+ let formattedValue = value
73
+ if (opts?.code) {
74
+ formattedValue = this.formatter.monospace(value)
75
+ } else if (opts?.bold) {
76
+ formattedValue = this.formatter.bold(value)
77
+ }
78
+ this.parts.push(`${key}: ${formattedValue}`)
79
+ return this
80
+ }
81
+
82
+ /**
83
+ * Add a code block
84
+ */
85
+ codeBlock(text: string, language?: string): this {
86
+ this.parts.push(this.formatter.monospaceBlock(text, language))
87
+ return this
88
+ }
89
+
90
+ /**
91
+ * Add a list item
92
+ */
93
+ listItem(text: string, depth: number = 0): this {
94
+ const indent = ' '.repeat(depth)
95
+ const bullet = this.listDepth > 0 ? '•' : `${this.listDepth + 1}.`
96
+ this.parts.push(`${indent}${bullet} ${text}`)
97
+ return this
98
+ }
99
+
100
+ /**
101
+ * Add a sublist (increase indentation)
102
+ */
103
+ startSublist(): this {
104
+ this.listDepth++
105
+ return this
106
+ }
107
+
108
+ /**
109
+ * End sublist (decrease indentation)
110
+ */
111
+ endSublist(): this {
112
+ if (this.listDepth > 0) this.listDepth--
113
+ return this
114
+ }
115
+
116
+ /**
117
+ * Add a newline
118
+ */
119
+ newline(): this {
120
+ this.parts.push('\n')
121
+ return this
122
+ }
123
+
124
+ /**
125
+ * Add raw text (escaped, no formatting)
126
+ */
127
+ text(text: string): this {
128
+ this.parts.push(this.formatter.escape(text))
129
+ return this
130
+ }
131
+
132
+ /**
133
+ * Add a horizontal rule (separator)
134
+ */
135
+ separator(): this {
136
+ this.parts.push(this.parseModeValue === 'HTML' ? '<hr>' : '---')
137
+ return this
138
+ }
139
+
140
+ /**
141
+ * Build the final message string
142
+ * @returns The formatted message ready to send
143
+ */
144
+ build(): string {
145
+ return this.parts.join('\n').trim()
146
+ }
147
+
148
+ /**
149
+ * Get the parse_mode for Telegraf
150
+ * Note: Telegraf accepts 'Markdown' for both Markdown and MarkdownV2
151
+ */
152
+ getParseMode(): 'Markdown' | 'HTML' {
153
+ return this.parseModeValue === 'MarkdownV2' ? 'Markdown' : this.parseModeValue
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Quick escape helper for raw text
159
+ */
160
+ export function escapeText(text: string): string {
161
+ const formatter = html as unknown as Formatter
162
+ return formatter.escape(text)
163
+ }
164
+
165
+ /**
166
+ * Format mode type
167
+ */
168
+ export type FormatType = 'html'
169
+
170
+ /**
171
+ * Quick format helpers
172
+ */
173
+ export const fmt = {
174
+ bold: (text: string) => (html as unknown as Formatter).bold(text),
175
+ italic: (text: string) => (html as unknown as Formatter).italic(text),
176
+ underline: (text: string) => (html as unknown as Formatter).underline(text),
177
+ code: (text: string) => (html as unknown as Formatter).monospace(text),
178
+ link: (text: string, url: string) => (html as unknown as Formatter).url(text, url),
179
+ escape: (text: string) => (html as unknown as Formatter).escape(text),
180
+ }
@@ -2,6 +2,8 @@
2
2
  "extends": "../tsconfig.json",
3
3
  "compilerOptions": {
4
4
  "rootDir": ".",
5
+ "outDir": "./dist",
6
+ "declarationDir": "./dist",
5
7
  "types": ["bun-types", "node"]
6
8
  },
7
9
  "include": ["src/**/*.ts"],
@@ -0,0 +1,326 @@
1
+ # Automatización integral de bots de Telegram con TypeScript
2
+
3
+ ## 1. Objetivo
4
+
5
+ Construir un **"BotFather personal"** totalmente automatizado que permita, desde **TypeScript**, realizar:
6
+
7
+ - Creación de bots de Telegram sin intervención manual.
8
+ - Creación de grupos y supergrupos (foros) y gestión de topics.
9
+ - Obtención automática de *bot tokens*, *chat IDs*, *topic IDs* y demás valores críticos.
10
+ - Creación de un repositorio GitHub desde un template.
11
+ - Despliegue automático del bot en **Coolify**, incluyendo variables de entorno y auto‑deploy.
12
+
13
+ El objetivo final es eliminar el *setup manual* y dejar un pipeline reproducible y escalable.
14
+
15
+ ---
16
+
17
+ ## 2. Qué se puede y NO se puede hacer según la API de Telegram
18
+
19
+ ### 2.1 Bot API (HTTP – bots)
20
+
21
+ **Disponible:**
22
+
23
+ - Enviar/recibir mensajes.
24
+ - Gestionar grupos *si el bot ya está añadido*.
25
+ - Crear y gestionar **forum topics** (`createForumTopic`).
26
+ - Obtener información de chats (`getChat`, `getChatMember`).
27
+ - Moderación (ban, pin, permisos, etc.).
28
+
29
+ **NO disponible (limitaciones duras):**
30
+
31
+ - ❌ Crear bots.
32
+ - ❌ Crear grupos o supergrupos.
33
+ - ❌ Iniciar conversaciones con usuarios.
34
+ - ❌ Obtener listado de topics existentes.
35
+
36
+ 👉 La Bot API **NO sirve** para el bootstrap inicial.
37
+
38
+ ---
39
+
40
+ ### 2.2 Telegram API (MTProto – cuenta de usuario)
41
+
42
+ **Disponible:**
43
+
44
+ - Enviar mensajes como un usuario (incluido a @BotFather).
45
+ - Crear bots interactuando con @BotFather.
46
+ - Crear grupos y supergrupos.
47
+ - Convertir grupos en supergrupos (megagroups).
48
+ - Añadir bots como administradores.
49
+ - Obtener IDs reales de chats.
50
+
51
+ **Consideraciones:**
52
+
53
+ - Requiere `api_id` y `api_hash`.
54
+ - Necesita login por código SMS.
55
+ - Es la **única vía** para automatizar la creación completa.
56
+
57
+ ---
58
+
59
+ ## 3. Arquitectura recomendada (TypeScript)
60
+
61
+ ```
62
+ Bootstrap Service (MTProto)
63
+ ├─ Crear bot vía BotFather
64
+ ├─ Crear supergrupo
65
+ ├─ Añadir bot como admin
66
+ ├─ Extraer IDs y tokens
67
+ └─ Provisionar infra (GitHub + Coolify)
68
+
69
+ Bot Runtime (Bot API)
70
+ └─ Telegraf / grammY
71
+ ```
72
+
73
+ Separar **bootstrap** y **runtime** es clave.
74
+
75
+ ---
76
+
77
+ ## 4. Librerías disponibles en TypeScript
78
+
79
+ ### 4.1 Telegram API (MTProto)
80
+
81
+ **GramJS (recomendada)**
82
+
83
+ - Cliente MTProto completo para Node.js.
84
+ - Permite login como usuario.
85
+ - Permite hablar con @BotFather.
86
+ - Permite crear chats y canales.
87
+
88
+ ```ts
89
+ import { TelegramClient } from "telegram";
90
+ import { StringSession } from "telegram/sessions";
91
+ ```
92
+
93
+ Alternativas:
94
+
95
+ - TDLib (más compleja, overkill).
96
+ - Telethon (Python, no TS).
97
+
98
+ ---
99
+
100
+ ### 4.2 Bot API
101
+
102
+ **Telegraf**
103
+
104
+ - Muy madura.
105
+ - Ideal para bots productivos.
106
+
107
+ **grammY**
108
+
109
+ - Más moderna.
110
+ - Mejor tipado TS.
111
+ - Más flexible para middlewares.
112
+
113
+ ---
114
+
115
+ ## 5. Flujo técnico detallado (Telegram)
116
+
117
+ ### 5.1 Crear bot automáticamente
118
+
119
+ Usando **Telegram API** (usuario):
120
+
121
+ 1. Login con `api_id + api_hash`.
122
+ 2. Abrir chat con `@BotFather`.
123
+ 3. Enviar `/newbot`.
124
+ 4. Responder nombre y username.
125
+ 5. Parsear el mensaje que contiene el **BOT TOKEN**.
126
+
127
+ > El token se guarda como variable de entorno.
128
+
129
+ ---
130
+
131
+ ### 5.2 Crear supergrupo (forum)
132
+
133
+ Usando Telegram API:
134
+
135
+ - Crear un **megagroup**.
136
+ - Activar modo foro.
137
+ - Obtener `chat_id` (ej: `-100xxxxxxxxxx`).
138
+
139
+ ---
140
+
141
+ ### 5.3 Añadir bot como administrador
142
+
143
+ - Invitar el bot por username.
144
+ - Asignar permisos:
145
+ - `can_manage_topics`
146
+ - `can_delete_messages`
147
+
148
+ ---
149
+
150
+ ### 5.4 Crear topics
151
+
152
+ Usando **Bot API**:
153
+
154
+ ```http
155
+ POST https://api.telegram.org/bot<TOKEN>/createForumTopic
156
+ ```
157
+
158
+ Payload:
159
+
160
+ ```json
161
+ {
162
+ "chat_id": -1001234567890,
163
+ "name": "logs"
164
+ }
165
+ ```
166
+
167
+ Respuesta contiene:
168
+
169
+ - `message_thread_id` → ID del topic.
170
+
171
+ ---
172
+
173
+ ## 6. Integración con GitHub (TypeScript)
174
+
175
+ ### 6.1 Crear repositorio desde template
176
+
177
+ HTTP REST:
178
+
179
+ ```http
180
+ POST /repos/{template_owner}/{template_repo}/generate
181
+ ```
182
+
183
+ Payload:
184
+
185
+ ```json
186
+ {
187
+ "owner": "mi-user",
188
+ "name": "telegram-bot-prod",
189
+ "private": true
190
+ }
191
+ ```
192
+
193
+ Resultado:
194
+
195
+ - Repo creado.
196
+ - Listo para deploy.
197
+
198
+ ---
199
+
200
+ ## 7. Coolify (sección extensa)
201
+
202
+ ### 7.1 Qué aporta Coolify
203
+
204
+ - Docker builder.
205
+ - Git‑based deploy.
206
+ - Variables de entorno.
207
+ - Auto‑deploy.
208
+ - Logs centralizados.
209
+
210
+ Perfecto para bots.
211
+
212
+ ---
213
+
214
+ ### 7.2 Autenticación
215
+
216
+ - Crear **API Token** desde el panel.
217
+ - Todas las llamadas usan:
218
+
219
+ ```
220
+ Authorization: Bearer <COOLIFY_TOKEN>
221
+ ```
222
+
223
+ ---
224
+
225
+ ### 7.3 Crear aplicación automáticamente
226
+
227
+ Endpoint típico:
228
+
229
+ ```http
230
+ POST /applications/private-deploy-key
231
+ ```
232
+
233
+ Payload:
234
+
235
+ ```json
236
+ {
237
+ "project_uuid": "...",
238
+ "server_uuid": "...",
239
+ "environment_uuid": "...",
240
+ "git_repository": "https://github.com/user/bot",
241
+ "git_branch": "main",
242
+ "name": "telegram-bot"
243
+ }
244
+ ```
245
+
246
+ Esto:
247
+
248
+ - Clona repo.
249
+ - Ejecuta Dockerfile.
250
+ - Despliega.
251
+
252
+ ---
253
+
254
+ ### 7.4 Variables de entorno (CRÍTICO)
255
+
256
+ Variables típicas:
257
+
258
+ - `BOT_TOKEN`
259
+ - `CHAT_ID`
260
+ - `LOG_TOPIC_ID`
261
+ - `NODE_ENV=production`
262
+
263
+ Se pueden crear vía API:
264
+
265
+ ```http
266
+ POST /applications/{uuid}/envs
267
+ ```
268
+
269
+ Esto permite **inyección completa automática**.
270
+
271
+ ---
272
+
273
+ ### 7.5 Auto‑deploy
274
+
275
+ Opciones:
276
+
277
+ - GitHub App (recomendado).
278
+ - Webhook manual.
279
+
280
+ Resultado:
281
+
282
+ - Push a `main` → deploy automático.
283
+
284
+ ---
285
+
286
+ ### 7.6 Arquitectura final
287
+
288
+ ```
289
+ User Script (TS)
290
+ ├─ Telegram API
291
+ ├─ GitHub API
292
+ └─ Coolify API
293
+
294
+ Bot Runtime
295
+ └─ Telegraf / grammY
296
+ ```
297
+
298
+ ---
299
+
300
+ ## 8. Conclusión
301
+
302
+ - **No es posible** hacerlo solo con Bot API.
303
+ - **Sí es posible** usando Telegram API + Bot API.
304
+ - TypeScript tiene tooling suficiente.
305
+ - Coolify es perfectamente automatizable.
306
+
307
+ Este enfoque permite crear bots, infra y despliegues en **un solo comando**.
308
+
309
+ ---
310
+
311
+ ## 9. Referencias
312
+
313
+ - Telegram Bot API [https://core.telegram.org/bots/api](https://core.telegram.org/bots/api)
314
+
315
+ - Telegram API (MTProto) [https://core.telegram.org/api](https://core.telegram.org/api)
316
+
317
+ - GramJS [https://gram.js.org/](https://gram.js.org/)
318
+
319
+ - Telegraf [https://telegraf.js.org/](https://telegraf.js.org/)
320
+
321
+ - grammY [https://grammy.dev/](https://grammy.dev/)
322
+
323
+ - GitHub REST API – Templates [https://docs.github.com/en/rest/repos/repos#create-a-repository-using-a-template](https://docs.github.com/en/rest/repos/repos#create-a-repository-using-a-template)
324
+
325
+ - Coolify API [https://coolify.io/docs/api-reference](https://coolify.io/docs/api-reference)
326
+