Skip to content

Commit 7f46646

Browse files
committed
wip
1 parent f2275ea commit 7f46646

3 files changed

Lines changed: 78 additions & 48 deletions

File tree

bot_logic.py

Lines changed: 30 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import pytz
77
import datetime
88
import random
9+
from contextlib import contextmanager
910

1011
# Non STL imports
1112
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
@@ -39,16 +40,31 @@
3940
bsasTz = pytz.timezone("America/Argentina/Buenos_Aires")
4041

4142

43+
@contextmanager
44+
def get_session():
45+
"""Provide a transactional scope around a series of operations."""
46+
session = Session()
47+
try:
48+
yield session
49+
session.commit()
50+
except:
51+
session.rollback()
52+
raise
53+
finally:
54+
session.close()
55+
56+
4257
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
4358
await update.message.reply_text(
4459
"Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!")
4560

4661

4762
async def help(update: Update, context: ContextTypes.DEFAULT_TYPE):
4863
message_text = "Comandos disponibles:\n"
49-
for name, command_info in sorted(COMMANDS.items()):
50-
if 'description' in command_info and command_info['description']:
51-
message_text += f"/{name} - {command_info['description']}\n"
64+
with get_session() as session:
65+
commands = session.query(Command).filter_by(enabled=True).order_by(Command.name).all()
66+
for command in commands:
67+
message_text += f"/{command.name} - {command.description}\n"
5268
await update.message.reply_text(message_text)
5369

5470

@@ -57,8 +73,7 @@ async def estasvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
5773

5874

5975
async def list_buttons(update: Update, context: ContextTypes.DEFAULT_TYPE, listable_type):
60-
session = Session()
61-
try:
76+
with get_session() as session:
6277
buttons = session.query(listable_type).filter_by(validated=True).order_by(listable_type.name).all()
6378
keyboard = []
6479
columns = 3
@@ -71,8 +86,6 @@ async def list_buttons(update: Update, context: ContextTypes.DEFAULT_TYPE, lista
7186
reply_markup = InlineKeyboardMarkup(keyboard)
7287
await update.message.reply_text(text="Grupos: ", disable_web_page_preview=True,
7388
reply_markup=reply_markup)
74-
finally:
75-
session.close()
7689

7790

7891
async def listar(update: Update, context: ContextTypes.DEFAULT_TYPE):
@@ -92,16 +105,13 @@ async def listarotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
92105

93106

94107
async def cubawiki(update: Update, context: ContextTypes.DEFAULT_TYPE):
95-
session = Session()
96-
try:
108+
with get_session() as session:
97109
group = session.query(Obligatoria).filter(
98110
Obligatoria.chat_id == str(update.message.chat.id),
99111
Obligatoria.cubawiki_url != None
100112
).first()
101113
if group:
102114
await update.message.reply_text(group.cubawiki_url)
103-
finally:
104-
session.close()
105115

106116

107117
async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, listable_type):
@@ -115,14 +125,11 @@ async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, l
115125
" <nombre>|<link>")
116126
return
117127

118-
session = Session()
119-
try:
128+
with get_session() as session:
120129
group = listable_type(name=name, url=url)
121130
session.add(group)
122-
session.commit()
131+
session.flush()
123132
group_id = group.id
124-
finally:
125-
session.close()
126133

127134
keyboard = [
128135
[
@@ -240,8 +247,7 @@ async def colaborar(update: Update, context: ContextTypes.DEFAULT_TYPE):
240247
# Manda una imagen a partir de su path al chat del update dado
241248
async def mandar_imagen(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
242249
await context.bot.send_chat_action(chat_id=chat_id, action=ChatAction.UPLOAD_PHOTO)
243-
session = Session()
244-
try:
250+
with get_session() as session:
245251
file = session.query(File).filter_by(path=file_path).first()
246252
if file:
247253
msg = await context.bot.send_photo(
@@ -252,17 +258,13 @@ async def mandar_imagen(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
252258
chat_id=chat_id, photo=f, allow_sending_without_reply=True)
253259
new_file = File(path=file_path, file_id=msg.photo[0].file_id)
254260
session.add(new_file)
255-
session.commit()
256-
finally:
257-
session.close()
258261

259262

260263
# Manda un documento a partir de su path al chat del update dado
261264
async def mandar_pdf(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
262265
await context.bot.send_chat_action(
263266
chat_id=chat_id, action=ChatAction.UPLOAD_DOCUMENT)
264-
session = Session()
265-
try:
267+
with get_session() as session:
266268
file = session.query(File).filter_by(path=file_path).first()
267269
if file:
268270
msg = await context.bot.send_document(
@@ -273,9 +275,6 @@ async def mandar_pdf(chat_id, context: ContextTypes.DEFAULT_TYPE, file_path):
273275
chat_id=chat_id, document=f, allow_sending_without_reply=True)
274276
new_file = File(path=file_path, file_id=msg.document.file_id)
275277
session.add(new_file)
276-
session.commit()
277-
finally:
278-
session.close()
279278

280279

281280
# Responde una imagen a partir de su path al chat del update dado
@@ -293,18 +292,15 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
293292
message = query.message
294293
buttonType, id, action = query.data.split("|")
295294

296-
session = Session()
297-
try:
295+
with get_session() as session:
298296
if buttonType == "Listable":
299297
group = session.query(Listable).filter_by(id=int(id)).first()
300298
if group:
301299
if action == "1":
302300
group.validated = True
303-
session.commit()
304301
action_text = "\n¡Aceptado!"
305302
else:
306303
session.delete(group)
307-
session.commit()
308304
action_text = "\n¡Rechazado!"
309305
await query.edit_message_text(text=message.text + action_text)
310306

@@ -313,17 +309,13 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
313309
if noticia:
314310
if action == "1":
315311
noticia.validated = True
316-
session.commit()
317312
action_text = "\n¡Aceptado!"
318313
await context.bot.send_message(chat_id=NOTICIAS_CHATID,
319314
text=noticia.text, parse_mode=ParseMode.MARKDOWN)
320315
else:
321316
session.delete(noticia)
322-
session.commit()
323317
action_text = "\n¡Rechazado!"
324318
await query.edit_message_text(text=message.text + action_text)
325-
finally:
326-
session.close()
327319

328320

329321
COMMANDS = {
@@ -375,6 +367,10 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
375367
'handler': sugerirotro,
376368
'description': 'Sugiere un grupo de otra categoría.'
377369
},
370+
'agregargrupo': {
371+
'handler': agregargrupo,
372+
'description': 'Muestra ayuda para sugerir un grupo.'
373+
},
378374
'campusvivo': {
379375
'handler': campusvivo,
380376
'description': 'Verifica si el Campus Virtual está funcionando.'

deletablecommandhandler.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
#!/usr/bin/python3
22
# -*- coding: utf-8 -*-
33

4+
import datetime
45
from telegram.ext import CommandHandler
56
from telegram.error import BadRequest
6-
from models import *
7+
from models import Session, SentMessage
78
import logging
89
logger = logging.getLogger("DCUBABOT")
910

@@ -18,21 +19,37 @@ def handle_update(self, update, dispatcher, check_result, context=None):
1819
context.sent_messages = []
1920
super().handle_update(update, dispatcher, check_result, context)
2021

21-
with db_session:
22+
session = Session()
23+
try:
2224
# Delete previous messages sent with the command in the group
23-
for message in select(m for m in SentMessage if
24-
m.command == self.command[0] and
25-
m.chat_id == update.effective_chat.id):
25+
messages_to_delete = session.query(SentMessage).filter_by(
26+
command=self.command[0],
27+
chat_id=update.effective_chat.id
28+
).all()
29+
30+
for message in messages_to_delete:
2631
if self._message_in_time_range(message):
2732
try:
2833
context.bot.delete_message(chat_id=message.chat_id,
2934
message_id=message.message_id)
3035
except BadRequest as e:
31-
logger.info("Menssage already deleted, tabunn")
32-
message.delete()
36+
logger.info("Message already deleted, tabunn")
37+
session.delete(message)
3338

3439
# Insert new sent messages for later delete (only in groups)
3540
for message in context.sent_messages:
3641
if message.chat.type != "private":
37-
SentMessage(command=self.command[0], chat_id=message.chat.id,
38-
message_id=message.message_id)
42+
new_message = SentMessage(
43+
command=self.command[0],
44+
chat_id=message.chat.id,
45+
message_id=message.message_id,
46+
timestamp=datetime.datetime.utcnow()
47+
)
48+
session.add(new_message)
49+
50+
session.commit()
51+
except Exception as e:
52+
session.rollback()
53+
logger.error(f"Error in DeletableCommandHandler: {e}")
54+
finally:
55+
session.close()

orga2Utils.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,29 @@
11
#!/usr/bin/python3
22
# -*- coding: utf-8 -*-
33

4+
from contextlib import contextmanager
5+
from sqlalchemy.orm import sessionmaker
6+
from sqlalchemy import func
47
# Local imports
5-
from models import *
8+
from models import AsmInstruction, Noitip, Session
9+
10+
@contextmanager
11+
def get_session():
12+
"""Provide a transactional scope around a series of operations."""
13+
session = Session()
14+
try:
15+
yield session
16+
session.commit()
17+
except:
18+
session.rollback()
19+
raise
20+
finally:
21+
session.close()
622

723

824
def noitip(update, context):
9-
with db_session:
10-
random_noitip = Noitip.select_random(1)[0].text
25+
with get_session() as session:
26+
random_noitip = session.query(Noitip).order_by(func.random()).first().text
1127
msg = update.message.reply_text(random_noitip, quote=False)
1228
context.sent_messages.append(msg)
1329

@@ -20,8 +36,9 @@ def asm(update, context):
2036
return
2137

2238
mnemonic = " ".join(context.args).upper()
23-
with db_session:
24-
possibles = [i for i in list(AsmInstruction.select())
39+
with get_session() as session:
40+
all_instructions = session.query(AsmInstruction).all()
41+
possibles = [i for i in all_instructions
2542
if levenshtein(mnemonic, i.mnemonic.upper()) < 2]
2643
if not possibles:
2744
msg = update.message.reply_text(

0 commit comments

Comments
 (0)