codebybrody commited on
Commit
affb51f
·
verified ·
1 Parent(s): 2a4b2a2

Upload 70 files

Browse files
bot_telegram/.env ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ TELEGRAM_BOT_TOKEN=8675706224:AAHqF9lk88MFCn3kUx_4dU_FNU1e7bF5Dv8
2
+ TELEGRAM_API_ID=33226415
3
+ TELEGRAM_API_HASH=01999dae3e5348c7ab0dbcc6f7f4edc5
4
+ TELEGRAM_CHANNEL_ID=-1003976391937
5
+ PORT=8080
bot_telegram/README.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Telegram Bot (Python) para CodeByDante
2
+
3
+ Este bot usa **Pyrogram (MTProto)** para gestionar sesiones persistentes y permitir subidas de archivos desde tu página web.
4
+
5
+ ## Estructura
6
+ - `bot.py`: Código principal (Bot + API).
7
+ - `sessions/`: Aquí se guarda el archivo `.session` generado automáticamente.
8
+ - `.env`: Configuración de credenciales.
9
+
10
+ ## Instalación
11
+ Si no has instalado las dependencias:
12
+ ```bash
13
+ pip install pyrogram tgcrypto fastapi uvicorn python-dotenv
14
+ ```
15
+
16
+ ## Configuración
17
+ 1. Edita el archivo `.env`.
18
+ 2. Asegúrate de tener los valores correctos de `API_ID`, `API_HASH` y `BOT_TOKEN`.
19
+ 3. El `CHANNEL_ID` debe ser el ID del canal donde el bot es admin.
20
+
21
+ ## Ejecución
22
+ ```bash
23
+ python bot.py
24
+ ```
25
+
26
+ Al iniciar por primera vez, se creará el archivo `bot_session.session` dentro de la carpeta `sessions/`.
bot_telegram/bot.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from telethon import TelegramClient, events
4
+ from fastapi import FastAPI, UploadFile, File
5
+ from fastapi.middleware.cors import CORSMiddleware
6
+ import uvicorn
7
+ from dotenv import load_dotenv
8
+
9
+ # 1. Configuración
10
+ load_dotenv()
11
+
12
+ API_ID = int(os.getenv("TELEGRAM_API_ID", "0"))
13
+ API_HASH = os.getenv("TELEGRAM_API_HASH", "")
14
+ BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "")
15
+ CHANNEL_ID = int(os.getenv("TELEGRAM_CHANNEL_ID", "0"))
16
+
17
+ if not os.path.exists("sessions"):
18
+ os.makedirs("sessions")
19
+
20
+ # 2. Inicializar Cliente de Telethon
21
+ # Usamos 'sessions/bot_session' para guardar el archivo .session
22
+ client = TelegramClient('sessions/bot_session', API_ID, API_HASH)
23
+
24
+ # 3. Servidor API con FastAPI
25
+ app_api = FastAPI()
26
+
27
+ app_api.add_middleware(
28
+ CORSMiddleware,
29
+ allow_origins=["*"],
30
+ allow_methods=["*"],
31
+ allow_headers=["*"],
32
+ )
33
+
34
+ # --- COMANDOS DEL BOT (TELETHON) ---
35
+
36
+ @client.on(events.NewMessage(pattern='/start'))
37
+ async def start_handler(event):
38
+ # Revisar si el comando trae un ID (Deep Link)
39
+ # Ejemplo: /start 12345
40
+ parts = event.raw_text.split()
41
+ if len(parts) > 1:
42
+ file_id = parts[1]
43
+ try:
44
+ msg_id = int(file_id)
45
+ print(f"Buscando archivo con ID: {msg_id} para el usuario {event.sender_id}")
46
+
47
+ # Reenviar el archivo desde el canal al usuario
48
+ await client.forward_messages(event.chat_id, msg_id, CHANNEL_ID)
49
+ return # Terminamos aquí si se envió el archivo
50
+ except Exception as e:
51
+ print(f"Error al recuperar archivo: {e}")
52
+ await event.respond("Lo siento, no pude encontrar ese archivo o ha sido eliminado.")
53
+ return
54
+
55
+ print(f"Recibido /start normal de {event.sender_id}")
56
+ await event.respond('¡Hola! Soy el bot de CodeByDante. Usa los botones de la web para descargar tus archivos aquí.')
57
+
58
+ @client.on(events.NewMessage(pattern='/id'))
59
+ async def id_handler(event):
60
+ await event.respond(f'Tu ID es: `{event.sender_id}`\nID del Chat: `{event.chat_id}`')
61
+
62
+ # --- ENDPOINTS DE LA API ---
63
+
64
+ @app_api.post("/upload")
65
+ async def upload_file(file: UploadFile = File(...)):
66
+ try:
67
+ file_path = f"temp_{file.filename}"
68
+ with open(file_path, "wb") as buffer:
69
+ content = await file.read()
70
+ buffer.write(content)
71
+
72
+ print(f"Subiendo '{file.filename}' a Telegram vía Telethon...")
73
+ # Enviar al canal y capturar el mensaje enviado
74
+ sent_msg = await client.send_file(
75
+ CHANNEL_ID,
76
+ file_path,
77
+ caption=f"Archivo subido desde CodeByDante: {file.filename}"
78
+ )
79
+ print(f"¡Subida completada con éxito! ID: {sent_msg.id}")
80
+
81
+ os.remove(file_path)
82
+ return {
83
+ "status": "success",
84
+ "message_id": sent_msg.id,
85
+ "channel_id": CHANNEL_ID,
86
+ "filename": file.filename
87
+ }
88
+ except Exception as e:
89
+ print(f"Error en subida: {e}")
90
+ return {"status": "error", "message": str(e)}
91
+
92
+ # --- INICIO COMBINADO ---
93
+
94
+ async def main():
95
+ # Arrancar el bot de Telegram
96
+ print("Iniciando Bot de Telegram (Telethon)...")
97
+ await client.start(bot_token=BOT_TOKEN)
98
+ print("Bot en línea y escuchando mensajes.")
99
+
100
+ # Arrancar el servidor API
101
+ config = uvicorn.Config(app_api, host="0.0.0.0", port=8080, log_level="info")
102
+ server = uvicorn.Server(config)
103
+
104
+ # Ejecutar ambos sin bloquearse
105
+ await server.serve()
106
+
107
+ if __name__ == '__main__':
108
+ try:
109
+ asyncio.run(main())
110
+ except KeyboardInterrupt:
111
+ pass
bot_telegram/go.mod ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ module bot_telegram
2
+
3
+ go 1.26.1
4
+
5
+ require (
6
+ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 // indirect
7
+ github.com/joho/godotenv v1.5.1 // indirect
8
+ )
bot_telegram/go.sum ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc=
2
+ github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8=
3
+ github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
4
+ github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
bot_telegram/main.go ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package main
2
+
3
+ import (
4
+ "fmt"
5
+ "io"
6
+ "log"
7
+ "net/http"
8
+ "os"
9
+ "strconv"
10
+
11
+ tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
12
+ "github.com/joho/godotenv"
13
+ )
14
+
15
+ func main() {
16
+ // 1. Cargar variables de entorno
17
+ err := godotenv.Load()
18
+ if err != nil {
19
+ log.Println("Aviso: No se encontró archivo .env, usando variables de sistema")
20
+ }
21
+
22
+ token := os.Getenv("TELEGRAM_BOT_TOKEN")
23
+ channelIDStr := os.Getenv("TELEGRAM_CHANNEL_ID")
24
+ port := os.Getenv("PORT")
25
+ if port == "" {
26
+ port = "8080"
27
+ }
28
+
29
+ if token == "" || token == "tu_token_aqui" {
30
+ log.Fatal("ERROR: TELEGRAM_BOT_TOKEN no configurado en .env")
31
+ }
32
+
33
+ channelID, _ := strconv.ParseInt(channelIDStr, 10, 64)
34
+
35
+ // 2. Inicializar Bot de Telegram
36
+ bot, err := tgbotapi.NewBotAPI(token)
37
+ if err != nil {
38
+ log.Panic(err)
39
+ }
40
+
41
+ bot.Debug = true
42
+ log.Printf("Bot autorizado en la cuenta: %s", bot.Self.UserName)
43
+
44
+ // 3. Goroutine para manejar mensajes entrantes (Útil para obtener IDs de canales)
45
+ go func() {
46
+ u := tgbotapi.NewUpdate(0)
47
+ u.Timeout = 60
48
+ updates := bot.GetUpdatesChan(u)
49
+
50
+ for update := range updates {
51
+ if update.Message != nil {
52
+ log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
53
+
54
+ // Responder con el ID del chat si el usuario envía /id
55
+ if update.Message.Text == "/id" {
56
+ msg := tgbotapi.NewMessage(update.Message.Chat.ID, fmt.Sprintf("El ID de este chat es: %d", update.Message.Chat.ID))
57
+ bot.Send(msg)
58
+ }
59
+ }
60
+ }
61
+ }()
62
+
63
+ // 4. Servidor HTTP para recibir archivos de la Web
64
+ http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
65
+ // Habilitar CORS para que tu página web pueda conectar
66
+ w.Header().Set("Access-Control-Allow-Origin", "*")
67
+ w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
68
+ w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
69
+
70
+ if r.Method == "OPTIONS" {
71
+ return
72
+ }
73
+
74
+ if r.Method != "POST" {
75
+ http.Error(w, "Método no permitido", http.StatusMethodNotAllowed)
76
+ return
77
+ }
78
+
79
+ // Recibir el archivo del formulario
80
+ file, header, err := r.FormFile("file")
81
+ if err != nil {
82
+ http.Error(w, "Error al recibir archivo: "+err.Error(), http.StatusBadRequest)
83
+ return
84
+ }
85
+ defer file.Close()
86
+
87
+ log.Printf("Recibiendo archivo: %s (%d bytes)", header.Filename, header.Size)
88
+
89
+ // Preparar el envío a Telegram
90
+ fileBytes, err := io.ReadAll(file)
91
+ if err != nil {
92
+ http.Error(w, "Error al leer archivo", http.StatusInternalServerError)
93
+ return
94
+ }
95
+
96
+ // Crear el archivo para Telegram
97
+ // Puedes usar NewDocument (genérico) o NewVideo según el tipo
98
+ fileData := tgbotapi.FileBytes{
99
+ Name: header.Filename,
100
+ Bytes: fileBytes,
101
+ }
102
+
103
+ // Enviamos como documento por defecto para no perder calidad
104
+ docMsg := tgbotapi.NewDocument(channelID, fileData)
105
+ docMsg.Caption = "Archivo subido desde CodeByDante: " + header.Filename
106
+
107
+ sentMsg, err := bot.Send(docMsg)
108
+ if err != nil {
109
+ http.Error(w, "Error al enviar a Telegram: "+err.Error(), http.StatusInternalServerError)
110
+ return
111
+ }
112
+
113
+ // Responder con el ID del mensaje para guardarlo en Firebase
114
+ response := fmt.Sprintf("{\"status\": \"success\", \"message_id\": %d, \"channel_id\": %d}", sentMsg.MessageID, channelID)
115
+ w.Header().Set("Content-Type", "application/json")
116
+ w.Write([]byte(response))
117
+
118
+ log.Printf("Archivo enviado con éxito a Telegram. MessageID: %d", sentMsg.MessageID)
119
+ })
120
+
121
+ log.Printf("Servidor API escuchando en el puerto %s...", port)
122
+ log.Fatal(http.ListenAndServe(":"+port, nil))
123
+ }
bot_telegram/sessions/bot_session.session ADDED
Binary file (28.7 kB). View file
 
components/EditorToolbar.tsx CHANGED
@@ -38,7 +38,8 @@ import {
38
  Globe,
39
  Mail,
40
  FileText,
41
- Minus
 
42
  } from 'lucide-react';
43
  import { TiktokIcon } from './TiktokIcon';
44
 
@@ -70,7 +71,9 @@ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
70
  const [showLinkInput, setShowLinkInput] = useState(false);
71
  const [linkUrl, setLinkUrl] = useState('');
72
  const fileInputRef = React.useRef<HTMLInputElement>(null);
73
- const [isUploading, setIsUploading] = useState(false);
 
 
74
  const [showVideoInput, setShowVideoInput] = useState(false);
75
  const [videoUrl, setVideoUrl] = useState('');
76
  const [showButtonInput, setShowButtonInput] = useState(false);
@@ -251,7 +254,7 @@ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
251
  const file = e.target.files?.[0];
252
  if (!file) return;
253
 
254
- setIsUploading(true);
255
  try {
256
  const url = await uploadImageToImgBB(file);
257
  if (editor) {
@@ -261,7 +264,7 @@ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
261
  console.error('Failed to upload image:', error);
262
  alert('Error al subir la imagen. Por favor intenta de nuevo.');
263
  } finally {
264
- setIsUploading(false);
265
  if (fileInputRef.current) {
266
  fileInputRef.current.value = '';
267
  }
@@ -447,9 +450,89 @@ export const EditorToolbar: React.FC<EditorToolbarProps> = ({
447
  <ToolbarButton
448
  onMouseDown={(e) => { e.preventDefault(); handleImageUploadClick(); }}
449
  isActive={false}
450
- icon={isUploading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <ImageIcon size={18} />}
451
  title="Subir Imagen"
452
  />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
453
  <input
454
  type="file"
455
  ref={fileInputRef}
 
38
  Globe,
39
  Mail,
40
  FileText,
41
+ Minus,
42
+ Paperclip
43
  } from 'lucide-react';
44
  import { TiktokIcon } from './TiktokIcon';
45
 
 
71
  const [showLinkInput, setShowLinkInput] = useState(false);
72
  const [linkUrl, setLinkUrl] = useState('');
73
  const fileInputRef = React.useRef<HTMLInputElement>(null);
74
+ const [isImageUploading, setIsImageUploading] = useState(false);
75
+ const [isFileUploading, setIsFileUploading] = useState(false);
76
+ const [uploadProgress, setUploadProgress] = useState(0);
77
  const [showVideoInput, setShowVideoInput] = useState(false);
78
  const [videoUrl, setVideoUrl] = useState('');
79
  const [showButtonInput, setShowButtonInput] = useState(false);
 
254
  const file = e.target.files?.[0];
255
  if (!file) return;
256
 
257
+ setIsImageUploading(true);
258
  try {
259
  const url = await uploadImageToImgBB(file);
260
  if (editor) {
 
264
  console.error('Failed to upload image:', error);
265
  alert('Error al subir la imagen. Por favor intenta de nuevo.');
266
  } finally {
267
+ setIsImageUploading(false);
268
  if (fileInputRef.current) {
269
  fileInputRef.current.value = '';
270
  }
 
450
  <ToolbarButton
451
  onMouseDown={(e) => { e.preventDefault(); handleImageUploadClick(); }}
452
  isActive={false}
453
+ icon={isImageUploading ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : <ImageIcon size={18} />}
454
  title="Subir Imagen"
455
  />
456
+
457
+ <ToolbarButton
458
+ onMouseDown={async (e) => {
459
+ e.preventDefault();
460
+ const input = document.createElement('input');
461
+ input.type = 'file';
462
+ input.multiple = true; // Habilitamos selección múltiple
463
+
464
+ input.onchange = async (event: any) => {
465
+ const files = Array.from(event.target.files || []);
466
+ if (files.length === 0) return;
467
+
468
+ setIsFileUploading(true);
469
+
470
+ // Procesamos los archivos uno por uno para no saturar el bot
471
+ for (const file of files as File[]) {
472
+ setUploadProgress(0);
473
+
474
+ await new Promise((resolve, reject) => {
475
+ const formData = new FormData();
476
+ formData.append('file', file);
477
+
478
+ const xhr = new XMLHttpRequest();
479
+ xhr.upload.addEventListener('progress', (e) => {
480
+ if (e.lengthComputable) {
481
+ const percent = Math.round((e.loaded / e.total) * 100);
482
+ setUploadProgress(percent);
483
+ }
484
+ });
485
+
486
+ xhr.onreadystatechange = () => {
487
+ if (xhr.readyState === 4) {
488
+ if (xhr.status === 200) {
489
+ const data = JSON.parse(xhr.responseText);
490
+ if (data.status === 'success') {
491
+ editor?.chain()
492
+ .focus()
493
+ .insertContent([
494
+ {
495
+ type: 'customFile',
496
+ attrs: {
497
+ name: file.name,
498
+ messageId: data.message_id || 'Subido',
499
+ channelId: data.channel_id
500
+ }
501
+ },
502
+ { type: 'paragraph' }
503
+ ])
504
+ .run();
505
+ resolve(true);
506
+ } else {
507
+ alert('Error en ' + file.name + ': ' + data.message);
508
+ resolve(false);
509
+ }
510
+ } else {
511
+ alert('Error de conexión al subir ' + file.name);
512
+ resolve(false);
513
+ }
514
+ }
515
+ };
516
+
517
+ xhr.open('POST', 'http://localhost:8080/upload', true);
518
+ xhr.send(formData);
519
+ });
520
+ }
521
+
522
+ setIsFileUploading(false);
523
+ };
524
+ input.click();
525
+ }}
526
+ isActive={false}
527
+ icon={isFileUploading ? (
528
+ <div className="relative flex items-center justify-center">
529
+ <div className="w-8 h-8 border-2 border-primary/20 border-t-primary rounded-full animate-spin" />
530
+ <span className="absolute text-[10px] font-bold text-primary">{uploadProgress}%</span>
531
+ </div>
532
+ ) : <Paperclip size={18} />}
533
+ title="Subir Archivo a Telegram"
534
+ />
535
+
536
  <input
537
  type="file"
538
  ref={fileInputRef}
components/TipTapEditor.tsx CHANGED
@@ -11,6 +11,7 @@ import { CustomImageExtension } from './extensions/CustomImageExtension';
11
  import { UniversalVideoExtension } from './extensions/UniversalVideoExtension';
12
  import { CustomCodeBlock } from './extensions/CustomCodeBlock';
13
  import { CustomButton } from './extensions/CustomButton';
 
14
  import { WordBehaviorExtension } from './extensions/WordBehaviorExtension';
15
  import { EditorToolbar } from './EditorToolbar';
16
  import { StyleSettingsPanel } from './StyleSettingsPanel';
@@ -178,6 +179,7 @@ export const TipTapEditor: React.FC<TipTapEditorProps> = ({
178
  CustomImageExtension,
179
  UniversalVideoExtension,
180
  CustomButton,
 
181
  HorizontalRule.configure({
182
  HTMLAttributes: {
183
  class: 'border-t border-white/10 my-8', // Reduced opacity
@@ -214,7 +216,7 @@ export const TipTapEditor: React.FC<TipTapEditorProps> = ({
214
  // Context menu handler removed
215
  },
216
  attributes: {
217
- class: `prose prose-invert max-w-none focus:outline-none whitespace-pre-wrap prose-p:whitespace-pre-wrap ${dense ? 'min-h-[40px]' : 'min-h-[50px]'} !h-auto prose-headings:font-bold prose-h1:text-3xl prose-h2:text-2xl prose-p:text-gray-300 prose-p:leading-relaxed prose-p:my-1 prose-blockquote:not-italic prose-pre:bg-[#000000] prose-pre:text-gray-300 prose-code:text-primary prose-code:rounded prose-code:px-1 prose-code:py-1 prose-code:leading-relaxed prose-code:decoration-clone prose-code:before:content-none prose-code:after:content-none prose-hr:border-white/10 ${className}`,
218
  style: `
219
  --code-font-family: ${styleConfig.code.fontFamily};
220
  `
 
11
  import { UniversalVideoExtension } from './extensions/UniversalVideoExtension';
12
  import { CustomCodeBlock } from './extensions/CustomCodeBlock';
13
  import { CustomButton } from './extensions/CustomButton';
14
+ import { CustomFileExtension } from './extensions/CustomFileExtension';
15
  import { WordBehaviorExtension } from './extensions/WordBehaviorExtension';
16
  import { EditorToolbar } from './EditorToolbar';
17
  import { StyleSettingsPanel } from './StyleSettingsPanel';
 
179
  CustomImageExtension,
180
  UniversalVideoExtension,
181
  CustomButton,
182
+ CustomFileExtension,
183
  HorizontalRule.configure({
184
  HTMLAttributes: {
185
  class: 'border-t border-white/10 my-8', // Reduced opacity
 
216
  // Context menu handler removed
217
  },
218
  attributes: {
219
+ class: `prose prose-invert max-w-none focus:outline-none ${dense ? 'min-h-[40px]' : 'min-h-[50px]'} !h-auto prose-headings:font-bold prose-h1:text-3xl prose-h2:text-2xl prose-p:text-gray-300 prose-p:leading-relaxed prose-p:my-1 prose-blockquote:not-italic prose-pre:bg-[#000000] prose-pre:text-gray-300 prose-code:text-primary prose-code:rounded prose-code:px-1 prose-code:py-1 prose-code:leading-relaxed prose-code:decoration-clone prose-code:before:content-none prose-code:after:content-none prose-hr:border-white/10 ${className}`,
220
  style: `
221
  --code-font-family: ${styleConfig.code.fontFamily};
222
  `
components/extensions/CustomFileExtension.tsx ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Node, mergeAttributes } from '@tiptap/core';
2
+ import { ReactNodeViewRenderer, NodeViewWrapper } from '@tiptap/react';
3
+ import React from 'react';
4
+ import { FileText, Send } from 'lucide-react';
5
+
6
+ // Extensión para renderizar archivos subidos de forma elegante
7
+ export const CustomFileExtension = Node.create({
8
+ name: 'customFile',
9
+ group: 'block',
10
+ atom: true,
11
+
12
+ addAttributes() {
13
+ return {
14
+ name: { default: 'Archivo' },
15
+ messageId: { default: null },
16
+ channelId: { default: null },
17
+ size: { default: null },
18
+ };
19
+ },
20
+
21
+ parseHTML() {
22
+ return [{ tag: 'div[data-type="custom-file"]' }];
23
+ },
24
+
25
+ renderHTML({ HTMLAttributes }) {
26
+ return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'custom-file' })];
27
+ },
28
+
29
+ addNodeView() {
30
+ return ReactNodeViewRenderer(FileComponent);
31
+ },
32
+ });
33
+
34
+ const FileComponent = ({ node }: any) => {
35
+ const { name = "Archivo sin nombre", messageId = "0" } = node.attrs || {};
36
+
37
+ const botUsername = "CodeByDantePrimebot";
38
+ const telegramUrl = `https://t.me/${botUsername}?start=${messageId}`;
39
+
40
+ return (
41
+ <NodeViewWrapper className="custom-file-node">
42
+ <div
43
+ contentEditable={false}
44
+ className="my-3 p-3 bg-zinc-900/90 border border-white/10 rounded-xl flex items-center justify-between gap-4 group hover:border-primary/50 transition-all shadow-lg select-none"
45
+ >
46
+ <div className="flex items-center gap-3 flex-1 min-w-0">
47
+ <div className="w-10 h-10 bg-primary/10 rounded-lg flex items-center justify-center text-primary shrink-0">
48
+ <FileText size={20} />
49
+ </div>
50
+ <div className="flex-1 min-w-0">
51
+ <div className="text-sm font-bold text-white truncate">
52
+ {name}
53
+ </div>
54
+ <div className="text-[10px] text-zinc-500 flex items-center gap-2">
55
+ <span>ID: {messageId}</span>
56
+ </div>
57
+ </div>
58
+ </div>
59
+
60
+ <a
61
+ href={telegramUrl}
62
+ target="_blank"
63
+ rel="noopener noreferrer"
64
+ className="px-4 py-2 bg-primary hover:bg-primary-hover text-white rounded-lg flex items-center gap-2 text-xs font-bold transition-all shrink-0 no-underline whitespace-nowrap"
65
+ >
66
+ <Send size={14} />
67
+ <span>Telegram</span>
68
+ </a>
69
+ </div>
70
+ </NodeViewWrapper>
71
+ );
72
+ };
components/extensions/WordBehaviorExtension.ts CHANGED
@@ -48,6 +48,26 @@ export const WordBehaviorExtension = Extension.create({
48
  return this.editor.commands.liftListItem('listItem');
49
  }
50
  return false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  }
52
  };
53
  }
 
48
  return this.editor.commands.liftListItem('listItem');
49
  }
50
  return false;
51
+ },
52
+
53
+ 'Control-Space': () => {
54
+ const { state } = this.editor;
55
+ const { selection } = state;
56
+ const { $from, empty } = selection;
57
+
58
+ // Si estamos al inicio de un punto de lista
59
+ if (empty && this.editor.isActive('listItem') && $from.parentOffset === 0) {
60
+ // Calculamos la posición exacta antes del listItem
61
+ const pos = $from.before($from.depth - 1);
62
+
63
+ // Insertamos un párrafo vacío y nos aseguramos de que no se convierta en lista
64
+ this.editor.chain()
65
+ .focus()
66
+ .insertContentAt(pos, { type: 'paragraph' })
67
+ .run();
68
+ return true;
69
+ }
70
+ return false;
71
  }
72
  };
73
  }
run.bat CHANGED
@@ -1,13 +1,23 @@
1
  @echo off
2
- echo [*] Iniciando el servidor de desarrollo...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  echo.
4
- echo ========================================================
5
- echo --- ENLACES DE ACCESO ---
6
- echo.
7
- echo Acceso Normal: http://localhost:3000/
8
- echo Acceso Administrador: http://localhost:3000/?admin=true
9
- echo.
10
- echo ========================================================
11
- echo.
12
- npm run dev
13
  pause
 
1
  @echo off
2
+ title CodeByDante - Sistema Completo
3
+
4
+ echo ==========================================
5
+ echo INICIANDO SISTEMA CODEBYDANTE
6
+ echo ==========================================
7
+
8
+ :: 1. Iniciar la página web (React/Vite)
9
+ echo [1/2] Iniciando Web App...
10
+ start cmd /k "npm run dev"
11
+
12
+ :: 2. Iniciar el Bot de Telegram (Python)
13
+ echo [2/2] Iniciando Bot de Telegram...
14
+ cd bot_telegram
15
+ start cmd /k "python bot.py"
16
+
17
  echo.
18
+ echo ==========================================
19
+ echo ¡SISTEMA EN LINEA!
20
+ echo Web en: http://localhost:5173 (o similar)
21
+ echo Bot API en: http://localhost:8080
22
+ echo ==========================================
 
 
 
 
23
  pause