Skip to content

Commit cafb87f

Browse files
committed
Refactor: code smells and typings
- Replace tuple return in update_group_url with GroupUrlResult dataclass - Fix bare excepts across the codebase - Remove unused exception variables - Remove unused imports and fix re-exports in bot_logic.py
1 parent cc65517 commit cafb87f

12 files changed

Lines changed: 39 additions & 34 deletions

bot_logic.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@
22
from handlers.basic import start, help_command, estasvivo, colaborar
33
from handlers.info import campusvivo, flan, flanviejo, aulas, cuandovence, listarlabos
44
from handlers.admin import checodepers, checodeppers, sugerirNoticia, get_logs, joder, movergrupo
5-
from handlers.groups import listar, listaroptativa, listareci, listarotro, cubawiki, agregargrupo, agregaroptativa, agregarotros, agregareci, sugerirgrupo, sugeriroptativa, sugerireci, sugerirotro, actualizar_grupos, _update_groups
6-
from handlers.callbacks import button
7-
from handlers.crons import felizdia, actualizarRiver
5+
from handlers.groups import listar, listaroptativa, listareci, listarotro, cubawiki, agregargrupo, agregaroptativa, agregarotros, agregareci, sugerirgrupo, sugeriroptativa, sugerireci, sugerirotro, actualizar_grupos
86

97
COMMANDS = {
108
'joder': {

cron.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
import datetime
77
from telegram.ext import Application
88
from tg_ids import ROZEN_CHATID
9-
from bot_logic import _update_groups, felizdia, actualizarRiver
9+
from handlers.groups import _update_groups
10+
from handlers.crons import felizdia, actualizarRiver
1011
from handlers.db import get_session
1112
from models import ProcessedUpdate
1213

@@ -31,19 +32,19 @@ async def run_update():
3132

3233
try:
3334
await felizdia(application)
34-
except Exception as e:
35+
except Exception:
3536
error_msg = f"Error en felizdia:\n{traceback.format_exc()}"
3637
await application.bot.send_message(chat_id=ROZEN_CHATID, text=error_msg[:4000])
3738

3839
try:
3940
await actualizarRiver(application)
40-
except Exception as e:
41+
except Exception:
4142
error_msg = f"Error en actualizarRiver:\n{traceback.format_exc()}"
4243
await application.bot.send_message(chat_id=ROZEN_CHATID, text=error_msg[:4000])
4344

4445
try:
4546
await _update_groups(application)
46-
except Exception as e:
47+
except Exception:
4748
error_msg = f"Error en update_groups:\n{traceback.format_exc()}"
4849
await application.bot.send_message(chat_id=ROZEN_CHATID, text=error_msg[:4000])
4950

@@ -55,7 +56,7 @@ async def run_update():
5556
chat_id=ROZEN_CHATID,
5657
text=f"Cron job finalizado. RAM máxima utilizada: {memory_mb:.2f} MB"
5758
)
58-
except Exception as e:
59+
except Exception:
5960
logging.error(f"Failed to send memory report: {e}")
6061

6162
asyncio.run(run_update())

handlers/db.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ def get_session():
1010
try:
1111
yield session
1212
session.commit()
13-
except:
13+
except Exception:
1414
session.rollback()
1515
raise
1616
finally:

handlers/groups.py

Lines changed: 23 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ async def agregar(update: Update, context: ContextTypes.DEFAULT_TYPE, grouptype,
9292
chat_id=update.message.chat.id)
9393
name = update.message.chat.title
9494
chat_id = str(update.message.chat.id)
95-
except:
95+
except Exception:
9696
await update.message.reply_text(
9797
text=f"Mirá, no puedo hacerle un link a este grupo, proba haciendome admin")
9898
return
@@ -134,17 +134,25 @@ async def agregareci(update: Update, context: ContextTypes.DEFAULT_TYPE):
134134
await agregar(update, context, ECI, "eci")
135135

136136
from telegram.error import Forbidden, BadRequest, RetryAfter, ChatMigrated
137+
from dataclasses import dataclass
138+
139+
@dataclass
140+
class GroupUrlResult:
141+
chat_id: str | None
142+
url: str | None
143+
title: str | None
144+
validated: bool | None
137145

138-
async def update_group_url(context: ContextTypes.DEFAULT_TYPE, chat_id: str, max_retries: int = 3) -> tuple[str, str, str, bool]:
146+
async def update_group_url(context: ContextTypes.DEFAULT_TYPE, chat_id: str, max_retries: int = 3) -> GroupUrlResult:
139147
base_delay = 1
140148
for attempt in range(max_retries):
141149
try:
142150
url = await context.bot.export_chat_invite_link(chat_id=chat_id)
143151
chat = await context.bot.get_chat(chat_id=chat_id)
144-
return chat_id, url, chat.title, True
152+
return GroupUrlResult(chat_id=chat_id, url=url, title=chat.title, validated=True)
145153
except (Forbidden, BadRequest) as e:
146154
logger.error(f"Bot is no longer allowed to create invite link for {chat_id}: {e}")
147-
return None, None, None, False
155+
return GroupUrlResult(chat_id=None, url=None, title=None, validated=False)
148156
except ChatMigrated as e:
149157
logger.info(f"Group {chat_id} migrated to {e.new_chat_id}. Retrying with new chat id.")
150158
return await update_group_url(context, str(e.new_chat_id), max_retries)
@@ -158,7 +166,7 @@ async def update_group_url(context: ContextTypes.DEFAULT_TYPE, chat_id: str, max
158166
await asyncio.sleep(wait_time)
159167

160168
logger.error(f"Max retries reached for {chat_id}. Failing gracefully.")
161-
return None, None, None, None
169+
return GroupUrlResult(chat_id=None, url=None, title=None, validated=None)
162170

163171
async def _update_groups(context: ContextTypes.DEFAULT_TYPE):
164172
logger.info("Starting update_groups job")
@@ -175,11 +183,11 @@ async def _update_groups(context: ContextTypes.DEFAULT_TYPE):
175183

176184
for chat_chat_id, db_entries in chats_by_id.items():
177185
await asyncio.sleep(1)
178-
chat_id, url, title, validated = await update_group_url(context, chat_chat_id)
186+
result = await update_group_url(context, chat_chat_id)
179187

180188
primary_name = db_entries[0][1]
181189

182-
if validated is False:
190+
if result.validated is False:
183191
logger.warning(f"Failed to update URL for group '{primary_name}'. De-validating.")
184192
with get_session() as session:
185193
for db_id, _ in db_entries:
@@ -190,19 +198,19 @@ async def _update_groups(context: ContextTypes.DEFAULT_TYPE):
190198
await context.bot.send_message(chat_id=DC_GROUP_CHATID, text=f"El grupo {primary_name} murió 💀")
191199
except Exception as e:
192200
logger.error(f"Failed to send death message for {primary_name}: {e}")
193-
elif validated is True:
201+
elif result.validated is True:
194202
logger.info(f"Updating URL for group '{primary_name}'")
195203
with get_session() as session:
196204
for db_id, _ in db_entries:
197205
c = session.query(Listable).filter_by(id=db_id).first()
198206
if c:
199-
c.url = url
200-
if title and c.name != title:
201-
logger.info(f"Updating name for group '{primary_name}' to '{title}'")
202-
c.name = title
203-
if str(c.chat_id) != str(chat_id):
204-
logger.info(f"Updating chat_id for group '{primary_name}' from {c.chat_id} to {chat_id}")
205-
c.chat_id = str(chat_id)
207+
c.url = result.url
208+
if result.title and c.name != result.title:
209+
logger.info(f"Updating name for group '{primary_name}' to '{result.title}'")
210+
c.name = result.title
211+
if str(c.chat_id) != str(result.chat_id):
212+
logger.info(f"Updating chat_id for group '{primary_name}' from {c.chat_id} to {result.chat_id}")
213+
c.chat_id = str(result.chat_id)
206214
logger.info("Finished update_groups job")
207215

208216
from handlers.admin import admin_ids

main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
from fastapi import FastAPI, Request, Response
1010
import uvicorn
1111

12-
from bot_logic import COMMANDS, button
12+
from bot_logic import COMMANDS
13+
from handlers.callbacks import button
1314
from tg_ids import ROZEN_CHATID
1415
from handlers.db import get_session
1516
from models import ProcessedUpdate

models.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import os
55
import datetime
6-
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, Date, Text, ForeignKey
6+
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, Date, Text
77
from sqlalchemy.orm import sessionmaker, declarative_base
88
from sqlalchemy.types import BigInteger
99

utils/campus.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def is_campus_up():
2222
msg = "Hubo un error de conexión, debe estar caído. Espero no sea época de parciales..."
2323
except requests.exceptions.HTTPError:
2424
msg = f"Recibí una respuesta del campus con error. {response.status_code}: {response.reason}"
25-
except:
25+
except Exception:
2626
msg = "Hubo un error y no tengo idea de qué fue. Rezale a Shannon."
2727

2828
return msg

utils/conciertos.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def parse(evento):
2323
titulo,
2424
fecha,
2525
)
26-
except:
26+
except Exception:
2727
return None
2828

2929
def fetch_conciertos():

utils/deletablecommandhandler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def handle_update(self, update, dispatcher, check_result, context=None):
3232
try:
3333
context.bot.delete_message(chat_id=message.chat_id,
3434
message_id=message.message_id)
35-
except BadRequest as e:
35+
except BadRequest:
3636
logger.info("Message already deleted, tabunn")
3737
session.delete(message)
3838

utils/orga2Utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# -*- coding: utf-8 -*-
33

44
from contextlib import contextmanager
5-
from sqlalchemy.orm import sessionmaker
65
from sqlalchemy import func
76
# Local imports
87
import models
@@ -16,7 +15,7 @@ def get_session():
1615
try:
1716
yield session
1817
session.commit()
19-
except:
18+
except Exception:
2019
session.rollback()
2120
raise
2221
finally:

0 commit comments

Comments
 (0)