Merge pull request #7 from marcogll/feat/initial-project-structure-5769203822268670178

Feat/initial project structure 5769203822268670178
This commit is contained in:
Marco Gallegos
2025-12-15 14:42:16 -06:00
committed by GitHub
4 changed files with 148 additions and 41 deletions

View File

@@ -1,15 +1,31 @@
# app/main.py # app/main.py
import logging import logging
from telegram import Update from telegram import Update
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes from telegram.ext import (
Application,
CommandHandler,
CallbackQueryHandler,
ConversationHandler,
MessageHandler,
ContextTypes,
filters,
)
from config import TELEGRAM_BOT_TOKEN from config import TELEGRAM_BOT_TOKEN
from permissions import get_user_role from permissions import get_user_role
from modules.onboarding import handle_start as onboarding_handle_start from modules.onboarding import handle_start as onboarding_handle_start
from modules.agenda import get_agenda from modules.agenda import get_agenda
from modules.citas import request_appointment from modules.citas import request_appointment
from modules.equipo import propose_activity, view_requests_status from modules.equipo import (
from modules.aprobaciones import approve_request, view_pending propose_activity_start,
get_description,
get_duration,
cancel_proposal,
view_requests_status,
DESCRIPTION,
DURATION,
)
from modules.aprobaciones import view_pending, handle_approval_action
from modules.servicios import get_service_info from modules.servicios import get_service_info
# Enable logging # Enable logging
@@ -25,36 +41,35 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
logger.info(f"User {chat_id} started conversation with role: {user_role}") logger.info(f"User {chat_id} started conversation with role: {user_role}")
# Delegate to the onboarding module
response_text, reply_markup = onboarding_handle_start(user_role) response_text, reply_markup = onboarding_handle_start(user_role)
await update.message.reply_text(response_text, reply_markup=reply_markup) await update.message.reply_text(response_text, reply_markup=reply_markup)
async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Parses the CallbackQuery and calls the appropriate module.""" """Parses the CallbackQuery and calls the appropriate module for simple actions."""
query = update.callback_query query = update.callback_query
await query.answer() await query.answer()
logger.info(f"Button handler received callback query: {query.data}")
logger.info(f"Received callback query: {query.data}")
response_text = "Acción no reconocida." response_text = "Acción no reconocida."
reply_markup = None
if query.data == 'view_agenda': if query.data.startswith(('approve:', 'reject:')):
response_text = get_agenda() response_text = handle_approval_action(query.data)
elif query.data == 'view_pending': elif query.data == 'view_pending':
response_text = view_pending() response_text, reply_markup = view_pending()
elif query.data == 'approve_request': else:
response_text = approve_request() simple_callbacks = {
elif query.data == 'propose_activity': 'view_agenda': get_agenda,
response_text = propose_activity() 'view_requests_status': view_requests_status,
elif query.data == 'view_requests_status': 'schedule_appointment': request_appointment,
response_text = view_requests_status() 'get_service_info': get_service_info,
elif query.data == 'schedule_appointment': }
response_text = request_appointment() handler_func = simple_callbacks.get(query.data)
elif query.data == 'get_service_info': if handler_func:
response_text = get_service_info() response_text = handler_func()
await query.edit_message_text(text=response_text, parse_mode='Markdown') await query.edit_message_text(text=response_text, reply_markup=reply_markup, parse_mode='Markdown')
def main() -> None: def main() -> None:
"""Start the bot.""" """Start the bot."""
@@ -62,14 +77,23 @@ def main() -> None:
logger.error("TELEGRAM_BOT_TOKEN is not set in the environment variables.") logger.error("TELEGRAM_BOT_TOKEN is not set in the environment variables.")
return return
# Create the Application and pass it your bot's token.
application = Application.builder().token(TELEGRAM_BOT_TOKEN).build() application = Application.builder().token(TELEGRAM_BOT_TOKEN).build()
# Add command handlers # Conversation handler for proposing activities
conv_handler = ConversationHandler(
entry_points=[CallbackQueryHandler(propose_activity_start, pattern='^propose_activity$')],
states={
DESCRIPTION: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_description)],
DURATION: [MessageHandler(filters.TEXT & ~filters.COMMAND, get_duration)],
},
fallbacks=[CommandHandler('cancel', cancel_proposal)],
per_message=False
)
application.add_handler(conv_handler)
application.add_handler(CommandHandler("start", start)) application.add_handler(CommandHandler("start", start))
application.add_handler(CallbackQueryHandler(button)) application.add_handler(CallbackQueryHandler(button))
# Run the bot until the user presses Ctrl-C
logger.info("Starting Talía Bot...") logger.info("Starting Talía Bot...")
application.run_polling() application.run_polling()

View File

@@ -1,15 +1,55 @@
# app/modules/aprobaciones.py # app/modules/aprobaciones.py
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
def approve_request(): def get_approval_menu(request_id):
""" """Returns an inline keyboard for approving or rejecting a request."""
Handles the owner's action to approve a request. keyboard = [
""" [
# TODO: Implement the full approval workflow InlineKeyboardButton("✅ Aprobar", callback_data=f'approve:{request_id}'),
return "Has seleccionado aprobar una solicitud. Aquí tienes las solicitudes pendientes:\n\n[Lista de solicitudes...]" InlineKeyboardButton("❌ Rechazar", callback_data=f'reject:{request_id}'),
]
]
return InlineKeyboardMarkup(keyboard)
def view_pending(): def view_pending():
""" """
Shows the owner a list of pending requests. Shows the owner a list of pending requests with approval buttons.
For now, it returns a hardcoded list of proposals.
""" """
# TODO: Fetch pending requests # TODO: Fetch pending requests from a database or webhook events
return "⏳ *Solicitudes Pendientes*\n\n- *Grabación de proyecto (4h)* - Solicitado por: Miembro del equipo A\n- *Taller de guion (2h)* - Solicitado por: Miembro del equipo B" proposals = [
{"id": "prop_001", "desc": "Grabación de proyecto", "duration": 4, "user": "Equipo A"},
{"id": "prop_002", "desc": "Taller de guion", "duration": 2, "user": "Equipo B"},
]
if not proposals:
return "No hay solicitudes pendientes.", None
# For simplicity, we'll just show the first pending proposal
proposal = proposals[0]
text = (
f"⏳ *Nueva Solicitud Pendiente*\n\n"
f"🙋‍♂️ *Solicitante:* {proposal['user']}\n"
f"📝 *Actividad:* {proposal['desc']}\n"
f"⏳ *Duración:* {proposal['duration']} horas"
)
reply_markup = get_approval_menu(proposal['id'])
return text, reply_markup
def handle_approval_action(callback_data):
"""
Handles the owner's approval or rejection of a request.
"""
action, request_id = callback_data.split(':')
if action == 'approve':
# TODO: Update the status of the request to 'approved'
return f"✅ La solicitud *{request_id}* ha sido aprobada."
elif action == 'reject':
# TODO: Update the status of the request to 'rejected'
return f"❌ La solicitud *{request_id}* ha sido rechazada."
return "Acción desconocida.", None

View File

@@ -1,11 +1,53 @@
# app/modules/equipo.py # app/modules/equipo.py
from telegram import Update
from telegram.ext import ContextTypes, ConversationHandler
def propose_activity(): # Conversation states
""" DESCRIPTION, DURATION = range(2)
Handles a team member's request to propose an activity.
""" async def propose_activity_start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
# TODO: Implement the full workflow for proposing an activity """Starts the conversation to propose an activity after a button press."""
return "Estás a punto de proponer una actividad. Por favor, describe la actividad, su duración y el objetivo." await update.callback_query.answer()
await update.callback_query.edit_message_text(
"Por favor, describe la actividad que quieres proponer."
)
return DESCRIPTION
async def get_description(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Stores the description and asks for the duration."""
context.user_data['activity_description'] = update.message.text
await update.message.reply_text(
"Entendido. Ahora, por favor, indica la duración estimada en horas (ej. 2, 4.5)."
)
return DURATION
async def get_duration(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Stores the duration, confirms the proposal, and ends the conversation."""
try:
duration = float(update.message.text)
context.user_data['activity_duration'] = duration
description = context.user_data.get('activity_description', 'N/A')
confirmation_text = (
f"Gracias. Se ha enviado la siguiente propuesta para aprobación:\n\n"
f"📝 *Actividad:* {description}\n"
f"⏳ *Duración:* {duration} horas\n\n"
"Recibirás una notificación cuando sea revisada."
)
# TODO: Send this proposal to the owner via webhook/db
await update.message.reply_text(confirmation_text, parse_mode='Markdown')
context.user_data.clear()
return ConversationHandler.END
except ValueError:
await update.message.reply_text("Por favor, introduce un número válido para la duración en horas.")
return DURATION
async def cancel_proposal(update: Update, context: ContextTypes.DEFAULT_TYPE) -> int:
"""Cancels and ends the conversation."""
await update.message.reply_text("La propuesta de actividad ha sido cancelada.")
context.user_data.clear()
return ConversationHandler.END
def view_requests_status(): def view_requests_status():
""" """

View File

@@ -22,8 +22,8 @@ This file tracks the development tasks for the Talía project.
- [x] Implement `onboarding.py` module. - [x] Implement `onboarding.py` module.
- [x] Implement `agenda.py` module. - [x] Implement `agenda.py` module.
- [x] Implement `citas.py` module. - [x] Implement `citas.py` module.
- [ ] Implement `equipo.py` module. - [x] Implement `equipo.py` module.
- [ ] Implement `aprobaciones.py` module. - [x] Implement `aprobaciones.py` module.
- [ ] Implement `servicios.py` module. - [ ] Implement `servicios.py` module.
- [ ] Implement `admin.py` module. - [ ] Implement `admin.py` module.
@@ -41,3 +41,4 @@ This file tracks the development tasks for the Talía project.
- Completed initial project scaffolding. - Completed initial project scaffolding.
- Implemented the core logic for the bot, including the central orchestrator, permissions, and onboarding. - Implemented the core logic for the bot, including the central orchestrator, permissions, and onboarding.
- Implemented the `agenda` and `citas` modules. - Implemented the `agenda` and `citas` modules.
- Implemented the conversational flow for proposing and approving activities.