Conversation
… automation - Created a sample .env file to guide users in setting up environment variables. - Added a Makefile to streamline the build, run, and test processes using Docker. - Updated README.md to reflect new setup instructions and improve documentation clarity.
- Introduced a comprehensive guide for the PyCamp_Bot project, detailing setup, development environment, command structure, database models, and typical workflows. - Included instructions for local installation, Docker usage, testing, and linting to enhance developer onboarding and project clarity.
…entry DSN placeholder - Changed TOKEN format to 'bot_token:your_bot_token_here' for better clarity. - Removed the placeholder for SENTRY_DATA_SOURCE_NAME to indicate it is not required.
- Modified the pip install command to include development dependencies by using '.[dev]' instead of just '.' for a more comprehensive setup.
- Added .claude/settings.local.json to .gitignore to prevent local configuration files from being tracked in version control.
- Introduced multiple test files to cover various functionalities including authentication, database export to JSON, management of PyCamp, and voting logic. - Added tests for the `get_admins_username` function to ensure correct retrieval of admin usernames. - Implemented tests for the `export_db_2_json` function to validate the structure and content of the exported data. - Created tests for managing PyCamp instances, including activation and duration calculations. - Developed tests for the `Vote` model to ensure proper creation and counting of votes, including handling of unique constraints.
- Changed the implementation of the set_as_only_active method to convert the active selection into a list before processing. - Added a conditional check to ensure bulk updates are only called if there are active instances, improving efficiency.
- Added a new `test-cov` command to the Makefile for running tests with coverage reporting. - Updated comments in the Makefile to clarify the usage of commands within the Docker container and the requirements for running tests.
- Revised the testing section to emphasize that project commands are executed within the Docker container using the Makefile. - Added a new section for local testing with an active virtual environment, detailing the usage of pytest commands directly. - Clarified the recommended approach for running tests with Docker.
- Updated the Makefile to mount the project directory as a volume for the `run`, `test`, and `test-cov` commands, allowing for real-time code updates without rebuilding the Docker image. - Improved comments to clarify the requirements and functionality of each command within the Docker container.
- Introduced multiple test files covering various functionalities including announcements, authentication, project management, voting, and wizard commands. - Implemented tests for user permissions, project lifecycle, and interaction with the database to ensure robust functionality. - Enhanced test coverage for asynchronous operations and mock interactions with the Telegram bot API.
- Updated the method of retrieving the username from the callback query to use `query.from_user.username` for accuracy. - Adjusted the project name retrieval to use `query.message.text` for consistency. - Enhanced project creation logic to associate the project with the user who initiated the vote, ensuring proper ownership in the database.
Parse the "completa" flag from context.args instead of splitting message.text, so the full wizard schedule (including past days) is shown reliably when the command is sent with @bot or from clients that format the message differently. Update tests to pass context with args.
- Implemented the '/borrar_cronograma' command for admins to delete the current schedule, prompting for confirmation before proceeding. - Updated help messages and documentation to include the new command. - Added tests to ensure proper functionality and permission checks for the new command.
… set The query used INNER JOIN with Slot, so only projects with an assigned slot were returned. Before running the schedule step all projects have slot=NULL and every vote was excluded. Switched to LEFT OUTER JOIN with Slot and handle the no-slot case by showing a "Sin asignar" section with project name and owner.
Updated the create_slot function to await the make_schedule call, ensuring proper asynchronous execution and preventing potential issues with scheduling operations.
Updated the active_needed function to use async/await syntax, allowing for proper asynchronous handling of commands. Modified the message sending logic to utilize the context object for improved clarity. Additionally, adjusted the reply text in list_pycampistas to include a total count of participants.
…ction Updated the error message in the schedule_wizards function to include the username of the admin when a BadRequest occurs, ensuring clearer logging and debugging information.
Included the installation of git in the Dockerfile to support the de/mostrar_version command, ensuring necessary tools are available for version management. Updated the package list and cleaned up temporary files to maintain a lean image.
Added an admin check to the vote_count function to restrict access to authorized users only. Updated tests to verify that only admins can execute the command and included cases for non-admin users to receive appropriate error messages. This enhances security and ensures proper permission handling in the voting process.
- Introduced a new test file for the `show_version` command in `devtools.py`, verifying the output for clean and dirty worktrees, as well as Sentry configuration. - Expanded tests in `manage_pycamp.py` to include scenarios for rejecting empty names, deactivating previous camps, and blocking non-admin users. - Added tests for listing participants in active camps, documenting a known bug in the process. - Enhanced overall test coverage for command functionalities and user permissions.
…limbing - Use max(1, total_participants) when computing most_voted_cost to prevent ZeroDivisionError when there are no participants. - Return current_state when neighboors is empty so hill_climbing does not call max() on an empty sequence (e.g. initial state with no projects).
- Updated the `aux_resolve_show_all` function to handle an additional 'futuros' argument, allowing users to view only upcoming slots. - Adjusted the time comparison for future slots to use Argentina's timezone, ensuring accurate scheduling. - Improved user feedback messages for empty agendas, clarifying the options available for viewing the schedule. - Refactored message sending logic to enhance clarity and user experience.
- Introduced two new tests to verify that when there are no available slots, the bot sends appropriate hints in plain text without MarkdownV2 formatting. - Updated the `aux_resolve_show_all` function to return true for no parameters and false for the 'futuros' argument, enhancing command behavior consistency. - These changes improve user experience by providing clearer feedback in scenarios with no available slots.
🔧 Resumen de Fixes (de la Rama
|
| Commit | Problema | Solución |
|---|---|---|
| f11c886 | ❌ /ver_agenda_magx crashea |
✅ Pasar context en lugar de update.message |
| b7a96b9 | ❌ Division por cero en scheduler | ✅ Validar participantes y proyectos vacíos |
| 668c545 | ❌ No ve votos en proyectos sin slot | ✅ Cambiar a LEFT OUTER JOIN |
| ad57851 | ❌ Schedule no se ejecuta | ✅ Agregar await a make_schedule() |
📅 Cronología de Fixes
1️⃣ Optimización de base de datos
Commit: eefc83b
El problema que resolvió:
- Cada vez que cambias cuál PyCamp estaba "activo", se hacía una actualización masiva innecesaria en la BD
- Era ineficiente y potencialmente lento
Cómo se arregló:
- Se añadió un chequeo: "si no hay nada para actualizar, no hagas la query"
- Resultado: operaciones más rápidas y eficientes
2️⃣ Votos no se registraban bien
Commit: 42d6914
El problema que resolvió:
- Al clickear un botón de votación, el bot no conseguía el nombre de usuario o el proyecto correctamente
- Las votaciones fallaban silenciosamente
Cómo se arregló:
- Cambiar dónde obtenía el username: ahora usa
query.from_user.username(fuente correcta) - Cambiar dónde obtenía el nombre del proyecto: ahora usa
query.message.text(fuente correcta) - Resultado: votaciones funcionan correctamente
3️⃣ Error en los logs de anuncios
Commit: ad60178
El problema que resolvió:
- El comando
/anunciosmostraba un error de Python porque usaba un método obsoleto - Método
warn()no existe más en Python 3.10+
Cómo se arregló:
- Cambiar
logger.warn()porlogger.warning()(el nombre correcto) - Resultado: los logs se escriben sin errores
4️⃣ No ves votos en nuevos proyectos ⭐
Commit: 668c545
El problema que resolvió:
/mis_proyectosno mostraba tus proyectos si aún no tenían horario asignado- Los nuevos proyectos aparecían pero sin contar los votos
Cómo se arregló:
- Cambiar la estrategia de la query de base de datos:
- Antes: INNER JOIN → solo proyectos con slot
- Ahora: LEFT OUTER JOIN → todos los proyectos, con una sección "Sin asignar" para los que no tienen horario
- Resultado: ves todos tus proyectos con sus votos, aunque no tengan horario aún
5️⃣ Schedule no se ejecutaba
Commit: ad57851
El problema que resolvió:
- Al crear un slot horario, la función
make_schedule()se llamaba pero no se esperaba completamente - El código asincrónico no funcionaba correctamente
Cómo se arregló:
- Agregar
awaitantes demake_schedule() - Resultado: el scheduler espera a que termine correctamente antes de continuar
6️⃣ Mensajes de error sin contexto
Commit: 5205dc2
El problema que resolvió:
- Cuando había un error al enviar el horario de wizards, el mensaje de error no decía quién lo intentó
- Difícil de debuggear
Cómo se arregló:
- Incluir el username del admin en el mensaje de error
- Resultado: logs más útiles para entender qué pasó
7️⃣ Nueva funcionalidad: Ver total de votos
Commit: 017f05c
Qué se agregó:
- Comando
/vote_countpara que los admins vean cuántos votos tiene cada proyecto en total - Protegido: solo pueden ejecutarlo los admins
Utilidad: Los organizadores pueden monitorear el progreso de votación
8️⃣ Crash al calcular horarios ⚠️ CRÍTICO
Commit: b7a96b9
El problema que resolvió:
- El scheduler se caía (Division by Zero) cuando:
- No había participantes registrados
- No había ningún proyecto aún
- Error:
max()sobre lista vacía
Cómo se arregló:
- Cambiar
total_participantspormax(1, total_participants)para evitar dividir por cero - Si no hay vecinos (estados alternativos), retornar el estado actual en lugar de llamar a
max()en lista vacía - Resultado: el scheduler funciona incluso con estado inicial vacío
9️⃣ Mejora: Ver solo slots futuros
Commit: ec8d90e
Qué cambió:
/ver_agenda_magxahora entiende dos formas de uso:/ver_agenda_magx→ muestra todos los slots/ver_agenda_magx futuros→ solo los próximos slots
- Usar timezone de Argentina en las comparaciones (no UTC)
- Mensajes mejorados para agendas vacías
Experiencia: Más control sobre qué horarios ver
🔟 HOTFIX: /ver_agenda_magx crashea 🚨
Commit: f11c886
El problema que resolvió:
- El commit anterior mejoró
/ver_agenda_magxpero introdujo un bug - Al clickear, el comando crashea con
AttributeError - Razón: se estaba pasando
update.messageen lugar decontextupdate.messageno tiene atributo.args(que es donde está el parámetro "futuros")- Solo
contexttiene.args
Cómo se arregló:
- Revertir a pasar
contexten lugar deupdate.message - Resultado:
/ver_agenda_magxfunciona de nuevo, y ahora con la funcionalidad mejorada
📊 Resumen por categoría
🐛 Bugs Críticos (Que reventaban funcionalidad)
b7a96b9- Division by zero en schedulerf11c886-/ver_agenda_magxcrasheaad57851- Schedule no se ejecuta
🔄 Bugs de Lógica (Datos incorrectos)
42d6914- Votos no se registraban668c545- No veías tus proyectos en/mis_proyectos
📝 Bugs Menores (Errores de código)
ad60178- Error en logging5205dc2- Error message incompleto
✨ Mejoras
017f05c- Nuevo comando/vote_countec8d90e- Mejora a/ver_agenda_magx(vista de futuros)eefc83b- Optimización de BD
✅ Resultado final
Después de estos 10 commits:
✔️ Votaciones funcionan correctamente
✔️ Ves todos tus proyectos con votos (aunque no tengan horario)
✔️ El scheduler no se cae
✔️ /ver_agenda_magx muestra slots (completo o solo futuros)
✔️ Los logs son claros y útiles
✔️ Los admins pueden contar votos totales
✔️ La base de datos es más eficiente
El bot está mucho más estable y con mejor experiencia de usuario. 🎉
Intentando "testear", este branch master contiene
IMPORTANTE:
Estos son todos los cambios juntos!!
Si solo se quiere incluir algunos, los desglosé en otros PRs