Skip to content
Snippets Groups Projects
Commit 7e103ca2 authored by fmk17's avatar fmk17
Browse files

Add logging, invalid_button

parent 7bb49ab5
Branches
No related tags found
No related merge requests found
from crawler import Location, Meal from crawler import Location, Meal
from collections import namedtuple from collections import namedtuple
from pprint import pformat
import sqlite3 import sqlite3
import logging
logger = logging.getLogger("database")
Schedule = namedtuple('Schedule', 'time, day_week, location, meal, user_id, created_at') Schedule = namedtuple('Schedule', 'time, day_week, location, meal, user_id, created_at')
...@@ -35,7 +39,7 @@ def get_schedules_for_user(user_id): ...@@ -35,7 +39,7 @@ def get_schedules_for_user(user_id):
row[5] row[5]
) for row in rows] ) for row in rows]
def insert_schedule(schedule): def upsert_schedule(schedule):
cur = connection.execute(''' cur = connection.execute('''
SELECT created_at SELECT created_at
FROM schedule FROM schedule
...@@ -49,6 +53,7 @@ def insert_schedule(schedule): ...@@ -49,6 +53,7 @@ def insert_schedule(schedule):
)) ))
row = cur.fetchone() row = cur.fetchone()
if not row: if not row:
logging.info(f"Inserting {pformat(schedule)}")
connection.execute(''' connection.execute('''
INSERT INTO schedule INSERT INTO schedule
(time, day_week, location, meal, user_id, created_at) (time, day_week, location, meal, user_id, created_at)
...@@ -62,13 +67,18 @@ def insert_schedule(schedule): ...@@ -62,13 +67,18 @@ def insert_schedule(schedule):
schedule.user_id, schedule.user_id,
schedule.created_at schedule.created_at
)) ))
else:
logging.info(f"Already inserted {pformat(schedule)}")
def get_schedules_matching_time(time): def get_schedules_matching_time(datetime):
time = datetime.strftime('%H:%M')
day_week = datetime.weekday()
logging.info(f"Getting schedules matching time {time} and day_week {day_week}")
cur = connection.execute(''' cur = connection.execute('''
SELECT time, day_week, location, meal, user_id, created_at SELECT time, day_week, location, meal, user_id, created_at
FROM schedule FROM schedule
WHERE time = ? and day_week = ? WHERE time = ? and day_week = ?
''', (time.strftime('%H:%M'), time.weekday())) ''', (time, day_week))
rows = cur.fetchall() rows = cur.fetchall()
return [Schedule( return [Schedule(
row[0], row[0],
......
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
from dotenv import load_dotenv from dotenv import load_dotenv
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.constants import PARSEMODE_HTML from telegram.constants import PARSEMODE_HTML
from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler from telegram.ext import Updater, CommandHandler, CallbackContext, CallbackQueryHandler, InvalidCallbackData
from crawler import get_menus_by_days, Location, Meal from crawler import get_menus_by_days, Location, Meal
from database import get_schedules_matching_time, insert_schedule, get_schedules_for_user, Schedule, delete_all_schedules_from_user from database import get_schedules_matching_time, upsert_schedule, get_schedules_for_user, Schedule, delete_all_schedules_from_user
from datetime import datetime, timedelta, date from datetime import datetime, timedelta, date
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
...@@ -31,7 +31,7 @@ logger = logging.getLogger("bot") ...@@ -31,7 +31,7 @@ logger = logging.getLogger("bot")
def start(update: Update, context: CallbackContext) -> None: def start(update: Update, context: CallbackContext) -> None:
update.message.reply_text(''' update.message.reply_text('''
Olá, eu sou o RU UFPR Bot, o robô de <a href="https://gitlab.c3sl.ufpr.br/caad/ru-bot-telegram">código aberto</a> mantido pelo <a href="https://caad.inf.ufpr.br/">CAAD (Centro Acadêmico Alexandre Direne)</a> que te mostra o cardápio do Restaurante Universitário da UFPR! Aqui vão os meus comandos: Olá, eu sou o RU UFPR Bot, o robô de <a href="https://gitlab.c3sl.ufpr.br/caad/ru-bot-telegram">código aberto licenciado sob AGPL</a> mantido pelo <a href="https://caad.inf.ufpr.br/">CAAD (Centro Acadêmico Alexandre Direne)</a> que te mostra o cardápio do Restaurante Universitário da UFPR! Aqui vão os meus comandos:
- /agendar · Configura notificações de cardápio - /agendar · Configura notificações de cardápio
- /cardapio_central · Mostra o cardápio do RU Central - /cardapio_central · Mostra o cardápio do RU Central
...@@ -184,7 +184,7 @@ def agendar_antes_abertura(update: Update, context: CallbackContext) -> None: ...@@ -184,7 +184,7 @@ def agendar_antes_abertura(update: Update, context: CallbackContext) -> None:
time = TIME_BEFORE_OPENING_BY_MEAL[meal] time = TIME_BEFORE_OPENING_BY_MEAL[meal]
schedule = Schedule(time=time, day_week=day_week, location=data.location, meal=meal, user_id=update.effective_user.id, created_at=datetime.now()) schedule = Schedule(time=time, day_week=day_week, location=data.location, meal=meal, user_id=update.effective_user.id, created_at=datetime.now())
logger.info(f"User {update.effective_user.id} {update.effective_user.first_name} {update.effective_user.last_name} {update.effective_user.username} added schedule {pformat(schedule)}") logger.info(f"User {update.effective_user.id} {update.effective_user.first_name} {update.effective_user.last_name} {update.effective_user.username} added schedule {pformat(schedule)}")
insert_schedule(schedule) upsert_schedule(schedule)
body, keyboard = agendar(update.effective_user.id) body, keyboard = agendar(update.effective_user.id)
update.callback_query.message.edit_text(body, reply_markup=keyboard, parse_mode=PARSEMODE_HTML) update.callback_query.message.edit_text(body, reply_markup=keyboard, parse_mode=PARSEMODE_HTML)
return return
...@@ -245,8 +245,12 @@ def remover_todas_notificacoes_ok(update: Update, context: CallbackContext) -> N ...@@ -245,8 +245,12 @@ def remover_todas_notificacoes_ok(update: Update, context: CallbackContext) -> N
update.callback_query.message.edit_text(body, reply_markup=keyboard, parse_mode=PARSEMODE_HTML) update.callback_query.message.edit_text(body, reply_markup=keyboard, parse_mode=PARSEMODE_HTML)
logger.info(f"User {update.effective_user.id} {update.effective_user.first_name} {update.effective_user.last_name} {update.effective_user.username} removed all notifications") logger.info(f"User {update.effective_user.id} {update.effective_user.first_name} {update.effective_user.last_name} {update.effective_user.username} removed all notifications")
def invalid_button(update: Update, context: CallbackContext) -> None:
update.callback_query.answer(text="Essa mensagem não é mais válida", show_alert=True)
def send_scheduled(context: CallbackContext) -> None: def send_scheduled(context: CallbackContext) -> None:
time = context.job.next_t - timedelta(minutes=EVERY_X_MINUTES) time = context.job.next_t - timedelta(minutes=EVERY_X_MINUTES)
logging.info(f"Getting schedules matching {time}")
schedules = get_schedules_matching_time(time) schedules = get_schedules_matching_time(time)
for schedule in schedules: for schedule in schedules:
days, update_time = get_menus_by_days(schedule.location) days, update_time = get_menus_by_days(schedule.location)
...@@ -281,6 +285,7 @@ def main() -> None: ...@@ -281,6 +285,7 @@ def main() -> None:
updater.dispatcher.add_handler(CallbackQueryHandler(remover_todas_notificacoes_ok, pattern=RemoveTodasNotificacoesOk)) updater.dispatcher.add_handler(CallbackQueryHandler(remover_todas_notificacoes_ok, pattern=RemoveTodasNotificacoesOk))
updater.dispatcher.add_handler(CallbackQueryHandler(agendar_callback, pattern=Agendar)) updater.dispatcher.add_handler(CallbackQueryHandler(agendar_callback, pattern=Agendar))
updater.dispatcher.add_handler(CallbackQueryHandler(agendar_antes_abertura, pattern=AgendarAntesAbertura)) updater.dispatcher.add_handler(CallbackQueryHandler(agendar_antes_abertura, pattern=AgendarAntesAbertura))
updater.dispatcher.add_handler(CallbackQueryHandler(invalid_button, pattern=InvalidCallbackData))
tm = datetime.now() tm = datetime.now()
tm = tm - timedelta(minutes=tm.minute % EVERY_X_MINUTES, seconds=tm.second, microseconds=tm.microsecond) tm = tm - timedelta(minutes=tm.minute % EVERY_X_MINUTES, seconds=tm.second, microseconds=tm.microsecond)
tm = tm + timedelta(minutes=EVERY_X_MINUTES) tm = tm + timedelta(minutes=EVERY_X_MINUTES)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment