Skip to content

Commit d4b2901

Browse files
committed
wip
1 parent 7f46646 commit d4b2901

3 files changed

Lines changed: 49 additions & 11 deletions

File tree

bot_logic.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
# Globals ...... yes, globals
3737
logger = logging.getLogger("DCUBABOT")
3838
admin_ids = [ROZEN_CHATID, DGARRO_CHATID] # @Rozen, @dgarro
39-
command_handlers = {}
4039
bsasTz = pytz.timezone("America/Argentina/Buenos_Aires")
4140

4241

@@ -59,7 +58,7 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
5958
"Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!")
6059

6160

62-
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
61+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
6362
message_text = "Comandos disponibles:\n"
6463
with get_session() as session:
6564
commands = session.query(Command).filter_by(enabled=True).order_by(Command.name).all()
@@ -324,7 +323,7 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
324323
'description': 'Inicia el bot.'
325324
},
326325
'help': {
327-
'handler': help,
326+
'handler': help_command,
328327
'description': 'Muestra este mensaje de ayuda.'
329328
},
330329
'estasvivo': {

main.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,46 @@
11
import telegram
22
import os
3-
from telegram.ext import Application, CommandHandler, CallbackQueryHandler
4-
from bot_logic import COMMANDS, button # Assuming 'button' is now in bot_logic
3+
import logging
4+
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, MessageHandler, filters
5+
6+
from bot_logic import COMMANDS, button
57
from models import init_db
68

9+
async def log_update(update, context):
10+
"""Log every update received by the bot."""
11+
logger = logging.getLogger("DCUBABOT")
12+
user = update.effective_user
13+
chat = update.effective_chat
14+
15+
log_message = f"Update received. User: {user.id} ({user.username}) in chat: {chat.id} ({chat.title})."
16+
if update.message and update.message.text:
17+
log_message += f" Message: {update.message.text}"
18+
elif update.callback_query:
19+
log_message += f" Callback Query: {update.callback_query.data}"
20+
21+
logger.info(log_message)
22+
23+
724
def main():
825
"""Start the bot."""
26+
logging.basicConfig(
27+
level=logging.INFO,
28+
format='[%(asctime)s] - [%(name)s] - [%(levelname)s] - %(message)s',
29+
filename="bots.log"
30+
)
31+
32+
init_db()
933

1034
application = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
1135

36+
# Add the logging middleware handler with a high priority
37+
application.add_handler(MessageHandler(filters.ALL, log_update), group=-1)
1238

1339
for command_name, command_info in COMMANDS.items():
14-
application.add_handler(CommandHandler(command_name, command_info['handler']))
40+
application.add_handler(CommandHandler(command_name, command_info['handler']))
1541

16-
# Register the callback query handler for buttons
1742
application.add_handler(CallbackQueryHandler(button))
1843

19-
20-
init_db()
21-
22-
# The WEBHOOK_URL is now guaranteed to be set by the CI/CD pipeline.
2344
webhook_url = os.environ["WEBHOOK_URL"]
2445

2546
# Start the Bot

utils/logging.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import logging
2+
from functools import wraps
3+
4+
def log_command(func):
5+
"""A decorator to log command usage."""
6+
@wraps(func)
7+
async def wrapper(update, context, *args, **kwargs):
8+
logger = logging.getLogger("DCUBABOT")
9+
command_name = func.__name__
10+
user = update.effective_user
11+
chat = update.effective_chat
12+
logger.info(f"Command '{command_name}' triggered by user {user.id} ({user.username}) in chat {chat.id} ({chat.title})")
13+
try:
14+
return await func(update, context, *args, **kwargs)
15+
except Exception as e:
16+
logger.error(f"Error in command '{command_name}': {e}", exc_info=True)
17+
raise
18+
return wrapper

0 commit comments

Comments
 (0)