Skip to content

Commit 4868a03

Browse files
committed
wip
1 parent 00504d8 commit 4868a03

2 files changed

Lines changed: 162 additions & 94 deletions

File tree

bot_logic.py

Lines changed: 162 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import datetime
88
import random
99
from contextlib import contextmanager
10+
from time import sleep
1011

1112
# Non STL imports
1213
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
@@ -66,7 +67,10 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
6667
with get_session() as session:
6768
commands = session.query(Command).filter_by(enabled=True).order_by(Command.name).all()
6869
for command in commands:
69-
message_text += f"/{command.name} - {command.description}\n"
70+
if command.description:
71+
message_text += f"/{command.name} - {command.description}\n"
72+
else:
73+
message_text += f"/{command.name}\n"
7074
await update.message.reply_text(message_text)
7175

7276

@@ -149,29 +153,20 @@ async def suggest_listable(update: Update, context: ContextTypes.DEFAULT_TYPE, l
149153

150154

151155
async def sugerirgrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
152-
await suggest_listable(update, context, Obligatoria)
156+
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregargrupo")
153157

154158

155159
async def sugeriroptativa(update: Update, context: ContextTypes.DEFAULT_TYPE):
156-
await suggest_listable(update, context, Optativa)
160+
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregaroptativa")
157161

158162

159163
async def sugerireci(update: Update, context: ContextTypes.DEFAULT_TYPE):
160-
await suggest_listable(update, context, ECI)
164+
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregareci")
161165

162166

163167
async def sugerirotro(update: Update, context: ContextTypes.DEFAULT_TYPE):
164-
await suggest_listable(update, context, Otro)
168+
await update.message.reply_text("Este comando esta deprecado, para agregar un grupo por favor agregá el bot al grupo y escribí /agregarotro")
165169

166-
async def agregargrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
167-
await update.message.reply_text(
168-
"Para sugerir un grupo, usá uno de los siguientes comandos, dependiendo de la categoría del grupo:\n"
169-
"/sugerirgrupo - Materia obligatoria\n"
170-
"/sugeriroptativa - Materia optativa\n"
171-
"/sugerireci - ECI\n"
172-
"/sugerirotro - Otra categoría\n\n"
173-
"El formato es: /comando <nombre>|<link>"
174-
)
175170

176171
async def campusvivo(update: Update, context: ContextTypes.DEFAULT_TYPE):
177172
msg = await update.message.reply_text("Bancá que me fijo...")
@@ -320,6 +315,124 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
320315
await query.edit_message_text(text=message.text + action_text)
321316

322317

318+
async def agregar(update: Update, context: ContextTypes.DEFAULT_TYPE, grouptype, groupString):
319+
try:
320+
url = await context.bot.export_chat_invite_link(
321+
chat_id=update.message.chat.id)
322+
name = update.message.chat.title
323+
chat_id = str(update.message.chat.id)
324+
except: # TODO: filter excepts
325+
await update.message.reply_text(
326+
text=f"Mirá, no puedo hacerle un link a este grupo, proba haciendome admin")
327+
return
328+
with get_session() as session:
329+
group = session.query(grouptype).filter_by(chat_id=chat_id).first()
330+
if group:
331+
group.url = url
332+
group.name = name
333+
await update.message.reply_text(
334+
text=f"Datos del grupo actualizados")
335+
return
336+
group = grouptype(name=name, url=url, chat_id=chat_id)
337+
session.add(group)
338+
session.flush()
339+
group_id = group.id
340+
keyboard = [
341+
[
342+
InlineKeyboardButton(
343+
text="Aceptar", callback_data=f"Listable|{group_id}|1"),
344+
InlineKeyboardButton(
345+
text="Rechazar", callback_data=f"Listable|{group_id}|0")
346+
]
347+
]
348+
reply_markup = InlineKeyboardMarkup(keyboard)
349+
await context.bot.send_message(chat_id=ROZEN_CHATID,
350+
text=f"{groupString}: {name}\n{url}",
351+
reply_markup=reply_markup)
352+
await update.message.reply_text("OK, se lo mando a Rozen.")
353+
354+
355+
async def agregargrupo(update: Update, context: ContextTypes.DEFAULT_TYPE):
356+
await agregar(update, context, Grupo, "grupo")
357+
358+
359+
async def agregaroptativa(update: Update, context: ContextTypes.DEFAULT_TYPE):
360+
await agregar(update, context, GrupoOptativa, "optativa")
361+
362+
363+
async def agregarotros(update: Update, context: ContextTypes.DEFAULT_TYPE):
364+
await agregar(update, context, GrupoOtros, "otro")
365+
366+
367+
async def agregareci(update: Update, context: ContextTypes.DEFAULT_TYPE):
368+
await agregar(update, context, ECI, "eci")
369+
370+
371+
async def sugerirNoticia(update: Update, context: ContextTypes.DEFAULT_TYPE):
372+
user = update.message.from_user
373+
name = user.first_name
374+
texto = " ".join(context.args)
375+
if not texto:
376+
await update.message.reply_text(
377+
text="Loc@, pusisiste algo mal, la idea es q pongas:\n "
378+
"/sugerirNoticia <texto>")
379+
return
380+
with get_session() as session:
381+
noticia = Noticia(text=texto)
382+
session.add(noticia)
383+
session.flush()
384+
noticia_id = noticia.id
385+
keyboard = [
386+
[
387+
InlineKeyboardButton("Aceptar", callback_data=f"Noticia|{noticia_id}|1"),
388+
InlineKeyboardButton("Rechazar", callback_data=f"Noticia|{noticia_id}|0")
389+
]
390+
]
391+
reply_markup = InlineKeyboardMarkup(keyboard)
392+
await context.bot.send_message(chat_id=ROZEN_CHATID, text=f"Noticia-{name}: {texto}",
393+
reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
394+
await update.message.reply_text(text="Ok, se lo pregunto a Rozen")
395+
396+
397+
async def update_group_url(context: ContextTypes.DEFAULT_TYPE, chat_id: str) -> (str, str, bool):
398+
try:
399+
url = await context.bot.export_chat_invite_link(chat_id=chat_id)
400+
return chat_id, url, True # too GO-like huh?
401+
except Exception:
402+
logger.error(f"Could not create invite link for {chat_id}", exc_info=True)
403+
return None, None, False # too GO-like huh?
404+
405+
406+
async def _update_groups(context: ContextTypes.DEFAULT_TYPE):
407+
logger.info("Starting update_groups job")
408+
with get_session() as session:
409+
chats = list(session.query(Listable).filter_by(validated=True).all())
410+
logger.info(f"Found {len(chats)} groups to update")
411+
412+
for chat in chats:
413+
sleep(1)
414+
chat_id, url, validated = await update_group_url(context, chat.chat_id)
415+
if not validated:
416+
logger.warning(f"Failed to update URL for group '{chat.name}'. De-validating.")
417+
with get_session() as session:
418+
c = session.query(Listable).filter_by(id=chat.id).first()
419+
c.validated = False
420+
await context.bot.send_message(chat_id=DC_GROUP_CHATID, text=f"El grupo {chat.name} murió 💀")
421+
else:
422+
logger.info(f"Updating URL for group '{chat.name}'")
423+
with get_session() as session:
424+
c = session.query(Listable).filter_by(id=chat.id).first()
425+
c.url = url
426+
logger.info("Finished update_groups job")
427+
428+
429+
async def actualizar_grupos(update: Update, context: ContextTypes.DEFAULT_TYPE):
430+
logger.info(f"Manual update of groups triggered by {update.effective_user.id}")
431+
await update.message.reply_text("Actualizando grupos...")
432+
await _update_groups(context)
433+
await update.message.reply_text("¡Grupos actualizados!")
434+
435+
323436
COMMANDS = {
324437
'start': {
325438
'handler': start,
@@ -353,25 +466,26 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
353466
'handler': cubawiki,
354467
'description': 'Devuelve el link a la Cubawiki de la materia (si estás en el grupo de la materia).'
355468
},
356-
'sugerirgrupo': {
357-
'handler': sugerirgrupo,
358-
'description': 'Sugiere un grupo de una materia obligatoria.'
469+
470+
'agregargrupo': {
471+
'handler': agregargrupo,
472+
'description': 'Agrega el grupo actual a la lista de grupos de materias obligatorias.'
359473
},
360-
'sugeriroptativa': {
361-
'handler': sugeriroptativa,
362-
'description': 'Sugiere un grupo de una materia optativa.'
474+
'agregaroptativa': {
475+
'handler': agregaroptativa,
476+
'description': 'Agrega el grupo actual a la lista de grupos de materias optativas.'
363477
},
364-
'sugerireci': {
365-
'handler': sugerireci,
366-
'description': 'Sugiere un grupo de una ECI.'
478+
'agregareci': {
479+
'handler': agregareci,
480+
'description': 'Agrega el grupo actual a la lista de grupos de ECI.'
367481
},
368-
'sugerirotro': {
369-
'handler': sugerirotro,
370-
'description': 'Sugiere un grupo de otra categoría.'
482+
'agregarotros': {
483+
'handler': agregarotros,
484+
'description': 'Agrega el grupo actual a la lista de otros grupos.'
371485
},
372-
'agregargrupo': {
373-
'handler': agregargrupo,
374-
'description': 'Muestra ayuda para sugerir un grupo.'
486+
'sugerirnoticia': {
487+
'handler': sugerirNoticia,
488+
'description': 'Sugiere una noticia para el canal de noticias.'
375489
},
376490
'campusvivo': {
377491
'handler': campusvivo,
@@ -413,4 +527,23 @@ async def button(update: Update, context: ContextTypes.DEFAULT_TYPE):
413527
'handler': colaborar,
414528
'description': 'Muestra el link al repositorio de Github del bot.'
415529
},
530+
'actualizar_grupos': {
531+
'handler': actualizar_grupos,
532+
'description': 'Actualiza los links de todos los grupos.'
533+
},
534+
#deprecated
535+
'sugerirgrupo': {
536+
'handler': sugerirgrupo,
537+
},
538+
'sugeriroptativa': {
539+
'handler': sugeriroptativa,
540+
},
541+
'sugerireci': {
542+
'handler': sugerireci,
543+
},
544+
'sugerirotro': {
545+
'handler': sugerirotro,
546+
},
547+
#hidden
548+
416549
}

dcubabot.py

Lines changed: 0 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -144,50 +144,6 @@ def felizdia(context):
144144
context.bot.send_message(chat_id=chat_id, text=felizdia_text(today))
145145

146146

147-
def suggest_listable(update, context, listable_type):
148-
try:
149-
name, url = " ".join(context.args).split("|")
150-
if not (name and url):
151-
raise Exception("not userneim")
152-
except Exception:
153-
msg = update.message.reply_text("Hiciste algo mal, la idea es que pongas:\n" +
154-
update.message.text.split()[0] +
155-
" <nombre>|<link>",
156-
quote=False)
157-
context.sent_messages.append(msg)
158-
return
159-
with db_session:
160-
group = listable_type(name=name, url=url)
161-
keyboard = [
162-
[
163-
InlineKeyboardButton(
164-
text="Aceptar", callback_data=f"Listable|{group.id}|1"),
165-
InlineKeyboardButton(
166-
text="Rechazar", callback_data=f"Listable|{group.id}|0")
167-
]
168-
]
169-
reply_markup = InlineKeyboardMarkup(keyboard)
170-
context.bot.sendMessage(chat_id=ROZEN_CHATID,
171-
text=listable_type.__name__ + ": " + name + "\n" + url,
172-
reply_markup=reply_markup)
173-
msg = update.message.reply_text("OK, se lo mando a Rozen.", quote=False)
174-
context.sent_messages.append(msg)
175-
176-
177-
def sugerirgrupo(update, context):
178-
suggest_listable(update, context, Obligatoria)
179-
180-
181-
def sugeriroptativa(update, context):
182-
suggest_listable(update, context, Optativa)
183-
184-
185-
def sugerireci(update, context):
186-
suggest_listable(update, context, ECI)
187-
188-
189-
def sugerirotro(update, context):
190-
suggest_listable(update, context, Otro)
191147

192148

193149
def listarlabos(update, context):
@@ -209,27 +165,6 @@ def aulas(update, context):
209165
responder_documento(update, context, 'files/0I-aulas.pdf')
210166

211167

212-
def togglecommand(update, context):
213-
if context.args and update.message.from_user.id in admin_ids:
214-
command_name = context.args[0]
215-
if command_name not in command_handlers:
216-
update.message.reply_text(text=f"No existe el comando /{command_name}.",
217-
quote=False)
218-
return
219-
with db_session:
220-
command = Command.get(name=command_name)
221-
command.enabled = not command.enabled
222-
if command.enabled:
223-
action = "activado"
224-
context.dispatcher.add_handler(command_handlers[command_name])
225-
else:
226-
action = "desactivado"
227-
context.dispatcher.remove_handler(
228-
command_handlers[command_name])
229-
update.message.reply_text(text=f"Comando /{command_name} {action}.",
230-
quote=False)
231-
232-
233168
def sugerir(update, context):
234169
update.message.reply_text(
235170
text=f"Ahora en mas las sugerencias las vamos a tomar en github:\n "

0 commit comments

Comments
 (0)