Skip to content

Commit 8d1aa44

Browse files
authored
Fix: replace update.message with update.effective_message to prevent AttributeError (#89)
1 parent 6fa68a4 commit 8d1aa44

8 files changed

Lines changed: 50 additions & 50 deletions

File tree

docs/onboarding.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ from telegram.ext import ContextTypes
6666
async def micomando(update: Update, context: ContextTypes.DEFAULT_TYPE):
6767
"""Descripción breve de lo que hace el comando."""
6868
# Lógica del comando...
69-
await update.message.reply_text("¡Hola! Este es mi nuevo comando.")
69+
await update.effective_message.reply_text("¡Hola! Este es mi nuevo comando.")
7070
```
7171

7272
### 2. Registrar el comando en `bot_logic.py`

handlers/admin.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,17 @@ async def joder(update: Update, context: ContextTypes.DEFAULT_TYPE):
1717
return
1818

1919
if not context.args:
20-
await update.message.reply_text("Uso: /joder <mensaje>")
20+
await update.effective_message.reply_text("Uso: /joder <mensaje>")
2121
return
2222

2323
message = " ".join(context.args)
2424
formatted_message = f"@rozen dice: {message}"
2525
try:
2626
await context.bot.send_message(chat_id=DC_GROUP_CHATID, text=formatted_message)
27-
await update.message.reply_text("Mensaje enviado exitosamente al grupo general.")
27+
await update.effective_message.reply_text("Mensaje enviado exitosamente al grupo general.")
2828
except Exception as e:
2929
logger.error(f"Failed to send joder message: {e}")
30-
await update.message.reply_text(f"Error al enviar el mensaje: {e}")
30+
await update.effective_message.reply_text(f"Error al enviar el mensaje: {e}")
3131

3232
import math
3333

@@ -64,7 +64,7 @@ async def movergrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
6464

6565
with get_session() as session:
6666
reply_markup = get_movergrupo_keyboard(session, page=0)
67-
await update.message.reply_text(
67+
await update.effective_message.reply_text(
6868
"Seleccioná el grupo que querés recategorizar:",
6969
reply_markup=reply_markup
7070
)
@@ -74,9 +74,9 @@ async def checodepers(update: Update, context: ContextTypes.DEFAULT_TYPE):
7474
ejemplo = """ Ejemplo de uso:
7575
/checodepers Hola, tengo un mensaje mucho muy importante que me gustaria que respondan
7676
"""
77-
await update.message.reply_text(ejemplo)
77+
await update.effective_message.reply_text(ejemplo)
7878
return
79-
user = update.message.from_user
79+
user = update.effective_user
8080
try:
8181
if not user.username:
8282
raise Exception("not userneim")
@@ -86,24 +86,24 @@ async def checodepers(update: Update, context: ContextTypes.DEFAULT_TYPE):
8686
except Exception:
8787
try:
8888
await context.bot.forward_message(
89-
CODEPERS_CHATID, update.message.chat_id, update.message.message_id)
89+
CODEPERS_CHATID, update.effective_chat.id, update.effective_message.message_id)
9090
logger.info(f"Malio sal {str(user)}")
9191
except Exception as e:
92-
await update.message.reply_text(
92+
await update.effective_message.reply_text(
9393
"La verdad me re rompí, avisale a roz asi ve que onda")
9494
logger.error(e)
9595
return
96-
await update.message.reply_text("OK, se lo mando a les codepers.")
96+
await update.effective_message.reply_text("OK, se lo mando a les codepers.")
9797

9898
async def checodeppers(update: Update, context: ContextTypes.DEFAULT_TYPE):
9999
await checodepers(update, context)
100100

101101
async def sugerirNoticia(update: Update, context: ContextTypes.DEFAULT_TYPE):
102-
user = update.message.from_user
102+
user = update.effective_user
103103
name = user.first_name
104104
texto = " ".join(context.args)
105105
if not texto:
106-
await update.message.reply_text(
106+
await update.effective_message.reply_text(
107107
text="Loc@, pusisiste algo mal, la idea es q pongas:\n "
108108
"/sugerirNoticia <texto>")
109109
return
@@ -121,7 +121,7 @@ async def sugerirNoticia(update: Update, context: ContextTypes.DEFAULT_TYPE):
121121
reply_markup = InlineKeyboardMarkup(keyboard)
122122
await context.bot.send_message(chat_id=ROZEN_CHATID, text=f"Noticia-{name}: {texto}",
123123
reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
124-
await update.message.reply_text(text="Ok, se lo pregunto a Rozen")
124+
await update.effective_message.reply_text(text="Ok, se lo pregunto a Rozen")
125125

126126
async def get_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
127127
user_id = update.effective_user.id
@@ -134,7 +134,7 @@ async def get_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
134134
import json
135135
import io
136136

137-
await update.message.reply_text("Buscando errores en Google Cloud Logging...")
137+
await update.effective_message.reply_text("Buscando errores en Google Cloud Logging...")
138138
client = gcp_logging.Client()
139139

140140
filter_str = 'severity>=ERROR AND (resource.type="cloud_run_revision" OR resource.type="cloud_run_job")'
@@ -158,7 +158,7 @@ async def get_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
158158
log_msgs.append(log_data)
159159

160160
if not log_msgs:
161-
await update.message.reply_text("✅ No se encontraron errores recientes en GCP.")
161+
await update.effective_message.reply_text("✅ No se encontraron errores recientes en GCP.")
162162
return
163163

164164
logs_json_str = json.dumps(log_msgs, indent=2, ensure_ascii=False)
@@ -171,4 +171,4 @@ async def get_logs(update: Update, context: ContextTypes.DEFAULT_TYPE):
171171
caption="Acá tenés el archivo con los últimos errores registrados en GCP 🕵️‍♂️"
172172
)
173173
except Exception as e:
174-
await update.message.reply_text(f"Error al leer logs (¿falta permiso roles/logging.viewer en la Service Account?): {e}")
174+
await update.effective_message.reply_text(f"Error al leer logs (¿falta permiso roles/logging.viewer en la Service Account?): {e}")

handlers/basic.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from handlers.db import get_session
66

77
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
8-
await update.message.reply_text(
8+
await update.effective_message.reply_text(
99
"Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!")
1010

1111
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -17,11 +17,11 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
1717
message_text += f"/{command.name} - {command.description}\n"
1818
else:
1919
message_text += f"/{command.name}\n"
20-
await update.message.reply_text(message_text)
20+
await update.effective_message.reply_text(message_text)
2121

2222
async def estasvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
23-
await update.message.reply_text(f"Sí, estoy vivo y corriendo en Python {sys.version.split()[0]}")
23+
await update.effective_message.reply_text(f"Sí, estoy vivo y corriendo en Python {sys.version.split()[0]}")
2424

2525
async def colaborar(update: Update, context: ContextTypes.DEFAULT_TYPE):
26-
await update.message.reply_text(
26+
await update.effective_message.reply_text(
2727
"Se puede colaborar con el DCUBA bot en https://github.com/comcomUBA/dcubabot")

handlers/groups.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ async def list_buttons(update: Update, context: ContextTypes.DEFAULT_TYPE, lista
2020

2121
keyboard.append(row)
2222
reply_markup = InlineKeyboardMarkup(keyboard)
23-
await update.message.reply_text(text="Grupos: ", disable_web_page_preview=True,
23+
await update.effective_message.reply_text(text="Grupos: ", disable_web_page_preview=True,
2424
reply_markup=reply_markup)
2525

2626
async def listar(update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -38,20 +38,20 @@ async def listarotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
3838
async def cubawiki(update: Update, context: ContextTypes.DEFAULT_TYPE):
3939
with get_session() as session:
4040
group = session.query(Obligatoria).filter(
41-
Obligatoria.chat_id == str(update.message.chat.id),
41+
Obligatoria.chat_id == str(update.effective_chat.id),
4242
Obligatoria.cubawiki_url != None
4343
).first()
4444
if group:
45-
await update.message.reply_text(group.cubawiki_url)
45+
await update.effective_message.reply_text(group.cubawiki_url)
4646

4747
async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, listable_type):
4848
try:
4949
name, url = " ".join(context.args).split("|")
5050
if not (name and url):
5151
raise Exception("not userneim")
5252
except Exception:
53-
await update.message.reply_text("Hiciste algo mal, la idea es que pongas:\n" +
54-
update.message.text.split()[0] +
53+
await update.effective_message.reply_text("Hiciste algo mal, la idea es que pongas:\n" +
54+
update.effective_message.text.split()[0] +
5555
" <nombre>|<link>")
5656
return
5757

@@ -71,37 +71,37 @@ async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, l
7171
await context.bot.send_message(chat_id=ROZEN_CHATID,
7272
text=listable_type.__name__ + ": " + name + "\n" + url,
7373
reply_markup=reply_markup)
74-
await update.message.reply_text("OK, se lo mando a Rozen.")
74+
await update.effective_message.reply_text("OK, se lo mando a Rozen.")
7575

7676
async def sugerirgrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
77-
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregargrupo")
77+
await update.effective_message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregargrupo")
7878

7979
async def sugeriroptativa(update: Update, context: ContextTypes.DEFAULT_TYPE):
80-
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregaroptativa")
80+
await update.effective_message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregaroptativa")
8181

8282
async def sugerireci(update: Update, context: ContextTypes.DEFAULT_TYPE):
83-
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregareci")
83+
await update.effective_message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregareci")
8484

8585
async def sugerirotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
86-
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregarotro")
86+
await update.effective_message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregarotro")
8787

8888

8989
async def agregar(update: Update, context: ContextTypes.DEFAULT_TYPE, grouptype, groupString):
9090
try:
9191
url = await context.bot.export_chat_invite_link(
92-
chat_id=update.message.chat.id)
93-
name = update.message.chat.title
94-
chat_id = str(update.message.chat.id)
92+
chat_id=update.effective_chat.id)
93+
name = update.effective_chat.title
94+
chat_id = str(update.effective_chat.id)
9595
except Exception:
96-
await update.message.reply_text(
96+
await update.effective_message.reply_text(
9797
text=f"Mirá, no puedo hacerle un link a este grupo, proba haciendome admin")
9898
return
9999
with get_session() as session:
100100
group = session.query(grouptype).filter_by(chat_id=chat_id).first()
101101
if group:
102102
group.url = url
103103
group.name = name
104-
await update.message.reply_text(
104+
await update.effective_message.reply_text(
105105
text=f"Datos del grupo actualizados")
106106
return
107107
group = grouptype(name=name, url=url, chat_id=chat_id)
@@ -118,7 +118,7 @@ async def agregar(update: Update, context: ContextTypes.DEFAULT_TYPE, grouptype,
118118
await context.bot.send_message(chat_id=ROZEN_CHATID,
119119
text=f"{groupString}: {name}\n{url}",
120120
reply_markup=reply_markup)
121-
await update.message.reply_text("OK, se lo mando a Rozen.")
121+
await update.effective_message.reply_text("OK, se lo mando a Rozen.")
122122

123123

124124
async def agregargrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -261,9 +261,9 @@ async def actualizar_grupos(update: Update, context: ContextTypes.DEFAULT_TYPE):
261261
lock_acquired = await acquire_lock(session, "update_groups", ttl_minutes=15)
262262

263263
if not lock_acquired:
264-
await update.message.reply_text("Ya hay una actualización de grupos en progreso (u ocurrió un error reciente). Por favor, esperá unos minutos a que termine o expire.")
264+
await update.effective_message.reply_text("Ya hay una actualización de grupos en progreso (u ocurrió un error reciente). Por favor, esperá unos minutos a que termine o expire.")
265265
return
266266

267267
logger.info(f"Manual update of groups triggered by {user_id}")
268-
await update.message.reply_text("Actualizando grupos en segundo plano (esto puede demorar varios minutos)...")
268+
await update.effective_message.reply_text("Actualizando grupos en segundo plano (esto puede demorar varios minutos)...")
269269
asyncio.create_task(_background_update(update, context))

handlers/info.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from handlers.media import responder_imagen, responder_documento
77

88
async def campusvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
9-
msg = await update.message.reply_text("Bancá que me fijo...")
9+
msg = await update.effective_message.reply_text("Bancá que me fijo...")
1010
campus_response_text = is_campus_up()
1111
await context.bot.edit_message_text(chat_id=msg.chat_id,
1212
message_id=msg.message_id,
@@ -25,20 +25,20 @@ async def cuandovence(update: Update, context: ContextTypes.DEFAULT_TYPE):
2525
ejemplo = "\nCuatris: 1c, 2c, i, inv, invierno, v, ver, verano.\nEjemplo: /cuandovence verano2010"
2626
if not context.args:
2727
ayuda = "Pasame cuatri y año en que aprobaste los TPs." + ejemplo
28-
await update.message.reply_text(ayuda)
28+
await update.effective_message.reply_text(ayuda)
2929
return
3030
try:
3131
linea_entrada = "".join(context.args).lower()
3232
cuatri, anio = parse_cuatri_y_anio(linea_entrada)
3333
except Exception:
34-
await update.message.reply_text(
34+
await update.effective_message.reply_text(
3535
"¿Me pasás las cosas bien? Es cuatri+año." + ejemplo)
3636
return
3737

3838
vencimiento = calcular_vencimiento(cuatri, anio)
39-
await update.message.reply_text(
39+
await update.effective_message.reply_text(
4040
vencimiento, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
4141

4242
async def listarlabos(update: Update, context: ContextTypes.DEFAULT_TYPE):
4343
msg = "Che, creo que la info de los laboratorios caducó y no tengo esta data. Si tenés alguna fuente de información actualizada o calendarios nuevos, pasásela a @Rozen para que lo pueda agregar."
44-
await update.message.reply_text(text=msg)
44+
await update.effective_message.reply_text(text=msg)

handlers/media.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ async def mandar_pdf(chat_id: str, context: ContextTypes.DEFAULT_TYPE, file_path
5757
file_obj.file_id = msg.document.file_id
5858

5959
async def responder_imagen(update: Update, context: ContextTypes.DEFAULT_TYPE, file_path: str):
60-
await mandar_imagen(update.message.chat_id, context, file_path)
60+
await mandar_imagen(update.effective_chat.id, context, file_path)
6161

6262
async def responder_documento(update: Update, context: ContextTypes.DEFAULT_TYPE, file_path: str):
63-
await mandar_pdf(update.message.chat_id, context, file_path)
63+
await mandar_pdf(update.effective_chat.id, context, file_path)

main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,8 @@ async def log_update(update, context):
6464
elif update.inline_query:
6565
log_parts.append(f"Type: Inline Query (query: {update.inline_query.query})")
6666

67-
if update.message and update.message.text:
68-
log_parts.append(f"Message: {update.message.text}")
67+
if update.effective_message and update.effective_message.text:
68+
log_parts.append(f"Message: {update.effective_message.text}")
6969
elif update.callback_query:
7070
log_parts.append(f"Callback Query: {update.callback_query.data}")
7171

utils/orga2Utils.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,14 @@ def get_session():
2525
async def noitip(update, context):
2626
with get_session() as session:
2727
random_noitip = session.query(models.Noitip).order_by(func.random()).first().text
28-
msg = await update.message.reply_text(random_noitip)
28+
msg = await update.effective_message.reply_text(random_noitip)
2929
if hasattr(context, 'sent_messages'):
3030
context.sent_messages.append(msg)
3131

3232

3333
async def asm(update, context):
3434
if not context.args:
35-
msg = await update.message.reply_text(
35+
msg = await update.effective_message.reply_text(
3636
"No me pasaste ninguna instrucción.")
3737
if hasattr(context, 'sent_messages'):
3838
context.sent_messages.append(msg)
@@ -54,7 +54,7 @@ async def asm(update, context):
5454
response_text = ("No pude encontrar esa instrucción.\n"
5555
"Quizás quisiste decir:\n")
5656
response_text += "\n".join(getasminfo(i) for i in possibles)
57-
msg = await update.message.reply_text(response_text)
57+
msg = await update.effective_message.reply_text(response_text)
5858
if hasattr(context, 'sent_messages'):
5959
context.sent_messages.append(msg)
6060

0 commit comments

Comments
 (0)