Spaces:
No application file
No application file
uploadmain to chatbot telegram
Browse files- main.py +106 -0
- requirements.txt +0 -0
main.py
ADDED
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from telegram import Update
|
2 |
+
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
from fuzzywuzzy import fuzz
|
6 |
+
from fuzzywuzzy import process
|
7 |
+
|
8 |
+
# Configurar el logging para ver mensajes de depuración
|
9 |
+
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
+
|
12 |
+
ERROR_THRESHOLD = 30 # Umbral de error para la similitud (de 0 a 100)
|
13 |
+
|
14 |
+
# Cargar el archivo de intenciones
|
15 |
+
def load_intents():
|
16 |
+
try:
|
17 |
+
with open('intents.json', 'r', encoding='utf-8') as f:
|
18 |
+
return json.load(f)
|
19 |
+
except Exception as e:
|
20 |
+
logger.error(f"Error al cargar el archivo intents.json: {e}")
|
21 |
+
return None
|
22 |
+
|
23 |
+
# Función para calcular la similitud y manejar la respuesta
|
24 |
+
def handle_response(text: str) -> str:
|
25 |
+
intents = load_intents()
|
26 |
+
if not intents:
|
27 |
+
return "Lo siento, no puedo cargar mis respuestas en este momento."
|
28 |
+
|
29 |
+
best_match = None
|
30 |
+
best_score = 0
|
31 |
+
|
32 |
+
for intent in intents['intents']:
|
33 |
+
for pattern in intent['patterns']:
|
34 |
+
score = fuzz.ratio(pattern.lower(), text.lower())
|
35 |
+
if score > best_score:
|
36 |
+
best_score = score
|
37 |
+
best_match = intent
|
38 |
+
|
39 |
+
if best_score >= ERROR_THRESHOLD:
|
40 |
+
response = best_match['responses']
|
41 |
+
return response[0] # Selecciona la primera respuesta de la lista (puedes modificar esto para seleccionar aleatoriamente)
|
42 |
+
else:
|
43 |
+
return "No entiendo. ¿Puedes repetir?"
|
44 |
+
|
45 |
+
# Token y nombre de usuario del bot
|
46 |
+
token = "7366210086:AAFAUrIwBrKRfxy29-PjF9wSqcEEYrhg8M0"
|
47 |
+
|
48 |
+
# Comando /start
|
49 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
50 |
+
await update.message.reply_text("¡Bienvenido! ¿En qué puedo ayudarte hoy?")
|
51 |
+
|
52 |
+
# Comando /help
|
53 |
+
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
54 |
+
await update.message.reply_text("Puedes preguntarme cosas como: '¿Qué servicios ofrecen?' o '¿Cuál es su horario?'.")
|
55 |
+
|
56 |
+
# Comando /hacer_pedido
|
57 |
+
async def make_order(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
58 |
+
link = "https://example.com/make_order" # Reemplaza con el enlace que deseas
|
59 |
+
text = "¡Genial! ¿Qué deseas pedir? Haz clic en el siguiente enlace para realizar tu pedido: <a href='{}'>Realizar pedido</a>".format(link)
|
60 |
+
await update.message.reply_text(text, parse_mode='HTML')
|
61 |
+
|
62 |
+
# Comando /contactar
|
63 |
+
async def contact(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
64 |
+
await update.message.reply_text("¡Claro! Puedes contactarnos a través de [tu correo electrónico o número de teléfono]. Estamos aquí para ayudarte.")
|
65 |
+
|
66 |
+
# Comando /conocenos
|
67 |
+
async def about_us(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
68 |
+
await update.message.reply_text("¡Hola! Somos un equipo de desarrolladores apasionados de crear soluciones innovadoras. Nuestro objetivo es brindarte la mejor experiencia posible.")
|
69 |
+
|
70 |
+
# Manejar mensajes
|
71 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
72 |
+
text = update.message.text.strip().lower()
|
73 |
+
|
74 |
+
# Verificar si el mensaje comienza con "soy "
|
75 |
+
if text.startswith("soy "):
|
76 |
+
nombre = text[4:] # Obtener el nombre del mensaje (eliminar "soy ")
|
77 |
+
await update.message.reply_text(f"Encantado de conocerte, {nombre.capitalize()}!")
|
78 |
+
|
79 |
+
else:
|
80 |
+
response = handle_response(text)
|
81 |
+
await update.message.reply_text(response, parse_mode='HTML') # Añadir parse_mode='HTML' si es necesario
|
82 |
+
# Manejar errores
|
83 |
+
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
84 |
+
logger.error(f'Update "{update}" caused error "{context.error}"')
|
85 |
+
|
86 |
+
# Inicializar el bot
|
87 |
+
if __name__ == '__main__':
|
88 |
+
print('Iniciando bot...')
|
89 |
+
app = Application.builder().token(token).build()
|
90 |
+
|
91 |
+
# Añadir comandos
|
92 |
+
app.add_handler(CommandHandler('start', start))
|
93 |
+
app.add_handler(CommandHandler('help', help))
|
94 |
+
app.add_handler(CommandHandler('hacer_pedido', make_order))
|
95 |
+
app.add_handler(CommandHandler('contactar', contact))
|
96 |
+
app.add_handler(CommandHandler('conocenos', about_us))
|
97 |
+
|
98 |
+
# Manejar mensajes de texto
|
99 |
+
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
|
100 |
+
|
101 |
+
# Manejar errores
|
102 |
+
app.add_error_handler(error)
|
103 |
+
|
104 |
+
# Ejecutar el bot
|
105 |
+
logger.info('Bot iniciado')
|
106 |
+
app.run_polling(poll_interval=1, timeout=10)
|
requirements.txt
ADDED
File without changes
|