Ejemplo n.º 1
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     subject_acro = tracker.get_slot("subject_acronym").upper()
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     teachers_info = API_raco().get_subject_teachers(acronym=subject_acro,
                                                     language=user_lang)
     teachers_info = Subject_teachers(subject_acro, teachers_info,
                                      user_lang)
     if teachers_info.amount <= 4:
         for response in teachers_info.get_offices():
             dispatcher.utter_message("{}".format(response))
     else:
         answers = {
             'ca': "Aquests són els professors de {}. Qui t'interessa?!\n",
             'es': 'Éstos son los profesores de {}. ¿Quién te interesa?\n',
             'en': "These are {}'s teachers. Who are you interested in?\n"
         }
         answer = answers[user_lang].format(subject_acro)
         for teacher in teachers_info.get_names():
             answer = answer + teacher + '\n'
         dispatcher.utter_message("{}".format(answer))
         return [SlotSet("matches", True)]
     return [SlotSet("matches", False)]
Ejemplo n.º 2
0
 def __init__(self, mh, delay, thread_logging = True):
     self.api = API_raco()
     self.message_handler = mh
     self.thread_logging = thread_logging
     self.chats = self.message_handler.chats
     self.delay = delay
     self.thread = None
     self.polling = True
     self.last_check = datetime.datetime.now()
     self.retrieve_timestamp()
     log("Marca temporal cargada: {}".format(self.last_check))
Ejemplo n.º 3
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     access_token = Chats().get_chat_lite(chat_id)['access_token']
     schedule = API_raco().get_schedule(access_token=access_token,
                                        language=user_lang)
     schedule = Schedule(schedule, user_lang)
     answer = schedule.get_response()
     if isinstance(answer, list):
         dispatcher.utter_message("{}".format(answer[0]))
     else:
         dispatcher.utter_message("{}".format(answer))
     return []
Ejemplo n.º 4
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     subject_acro = tracker.get_slot("subject_acronym").upper()
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     teachers_info = API_raco().get_subject_teachers(acronym=subject_acro,
                                                     language=user_lang)
     teachers_info = Subject_teachers(subject_acro, teachers_info,
                                      user_lang)
     answers = {
         'ca': "Aquests són els professors de {}:\n",
         'es': 'Éstos son los profesores de {}:\n',
         'en': "These are {}'s teachers:\n"
     }
     answer = answers[user_lang].format(subject_acro)
     for teacher in teachers_info.get_names():
         answer = answer + teacher + '\n'
     dispatcher.utter_message("{}".format(answer))
     return []
Ejemplo n.º 5
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     subject_acro = tracker.get_slot("subject_acronym").upper()
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     access_token = Chats().get_chat_lite(chat_id)['access_token']
     response = API_raco().get_schedule(access_token, user_lang,
                                        subject_acro)
     for data in response:
         lecture = Lecture(data, user_lang)
         dispatcher.utter_message("{}".format(lecture))
     return []
Ejemplo n.º 6
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     subject_acro = tracker.get_slot("subject_acronym").upper()
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     access_token = Chats().get_chat_lite(chat_id)['access_token']
     if not API_raco().user_enrolled_subject(subject_acro, access_token,
                                             user_lang):
         response = str(Not_understood(user_lang, 'not_enrolled'))
         if '{}' in response:
             dispatcher.utter_message(response.format(subject_acro))
         else:
             dispatcher.utter_message(response)
         print(colored("El usuario NO está matriculado", 'red'))
         return [SlotSet("subject_enrollment", False)]
     else:
         print(colored("El usuario está matriculado", 'green'))
         return [SlotSet("subject_enrollment", True)]
Ejemplo n.º 7
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     subject_acro = tracker.get_slot("subject_acronym")
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     if subject_acro:
         subject_acro = subject_acro.upper()
         if not API_raco().subject_exists(subject_acro):
             dispatcher.utter_message(
                 str(Not_understood(user_lang, 'wrong_subject')))
         else:
             print(colored("Asignatura existe", 'green'))
             return [SlotSet("subject_existance", True)]
     else:
         dispatcher.utter_message("{}".format(
             Not_understood(user_lang, 'not_understand')))
     print(colored("Asignatura NO existe", 'red'))
     return [SlotSet("subject_existance", False)]
Ejemplo n.º 8
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     chat_id = tracker.sender_id
     subject_acro = tracker.get_slot("subject_acronym")
     user_lang = Chats().get_chat_lite(chat_id)['language']
     access_token = Chats().get_chat_lite(chat_id)['access_token']
     if subject_acro: acro_filter = subject_acro
     else: acro_filter = None
     pracs = list(API_raco().get_practiques(access_token=access_token,
                                            language=user_lang))
     p_e = Practical_schedule(pracs, user_lang)
     pracs = list(p_e.get_closest_pracs(range=62, acro_filter=acro_filter))
     if pracs:
         for prac in pracs:
             dispatcher.utter_message("{}".format(prac))
         tracker._reset_slots()
         return []
     dispatcher.utter_message("{}".format(
         Not_understood(user_lang, 'not_pracs')))
     return []
Ejemplo n.º 9
0
 def run(self, dispatcher, tracker, domain):
     print("\nEjecutando acción:\t{}".format(
         colored(self.name(), 'yellow', attrs=['bold'])))
     print("Representación de los slots:")
     color_print_slots(tracker)
     subject_acro = tracker.get_slot("subject_acronym").upper()
     group = tracker.get_slot("group")
     chat_id = tracker.sender_id
     user_lang = Chats().get_chat_lite(chat_id)['language']
     response = list(API_raco().get_free_spots(subject_acro, user_lang))
     if not response:
         dispatcher.utter_message("{}".format(
             Not_understood(
                 user_lang,
                 'not_enrollment_possible')).format(subject_acro))
         return []
     s_s = Subject_spots(response, user_lang)
     if group:
         dispatcher.utter_message("{}".format(s_s.get_group_spots(group)))
     else:
         for group in s_s.group_info.keys():
             dispatcher.utter_message("{}".format(
                 s_s.get_group_spots(group)))
     return []
Ejemplo n.º 10
0
class Notification_thread(object):

    """This class enables multithreading capabilities by using an extra thread to scan looking for
    notifications for users.

        Attributes:
            api(:class:`Fibot.api.api_raco.API_raco`): Object that accesses the info at Raco's API_raco
            message_handler(:class:`Fibot.message_handler.Message_handler`): Object that allows interaction with users
            chats(:class:`Fibot.chats.Chats`): Chat records of users.
            delay(:obj:`int`): Amount of seconds between scans.
            thread(:class:`threading.Timer`): Thread that does the scanning.
            polling(:obj:`bool`): Object that indicates if polling has to be done
            last_check(:class:`datetime.datetime`): datetime of the last check for notifications
    """
    def __init__(self, mh, delay, thread_logging = True):
        self.api = API_raco()
        self.message_handler = mh
        self.thread_logging = thread_logging
        self.chats = self.message_handler.chats
        self.delay = delay
        self.thread = None
        self.polling = True
        self.last_check = datetime.datetime.now()
        self.retrieve_timestamp()
        log("Marca temporal cargada: {}".format(self.last_check))

    """
        Saves the timestamp when the last scan was done
    """
    def dump_timestamp(self):
        to_save = str(self.last_check)
        with open('Data/timestamp.txt', 'w') as file:
            file.write(to_save)
        return

    """
        Retrieves and stores the timestamp when the last scan was done
    """
    def retrieve_timestamp(self):
        with open('Data/timestamp.txt', 'r') as file:
            timestamp = file.readline()
            date, time = timestamp.split(' ')
            year, month, day = date.split('-')
            hour, minute, second = time.split(':')
            self.last_check = datetime.datetime(int(year),int(month), int(day), int(hour), int(minute), int(second))
        return

    """
        This function defines the new timer and starts it (effectively allows the scanning)
    """
    def run(self):
        if self.polling:
            self.thread = Timer(self.delay, self.poll)
            self.thread.start()

    """
        Does a scan over all users, and then returns to the activation function
    """
    def poll(self):
        self.chats.load()
        if self.thread_logging: log("N_Thread: Última comprobación hecha: {}\n".format(datetime.datetime.now()))
        if self.thread_logging: log("N_Thread: Escaneando notificaciones...\n")
        last_avis = self.last_check
        for student_id in self.chats.chats.keys():
            student = self.chats.get_chat(student_id)
            if student['notifications']:
                if self.thread_logging: log("N_Thread: Escaneando a {}.\n".format(student['name']))
                access_token = student['access_token']
                user_lang = student['language']
                avisos = self.api.get_avisos(access_token)
                if avisos:
                    filtered = self.filter(avisos)
                    for avis in filtered:
                        message = Notification(avis, user_lang).get_notif()
                        self.message_handler.send_message(student_id, message, typing=True)
                        if self.thread_logging: log("N_Thread: Se ha enviado la notificación!")
                        last_avis = max(last_avis, self.get_date(avis))
        self.last_check = last_avis
        self.dump_timestamp()
        if self.thread_logging: log("N_Thread: Última notificación recibida: {}".format(self.last_check))
        self.run()

    """
        Parameters:
            avisos(:obj:`list`): List of publications for a user

        This function filters the publications so that they were not sent previously,
        And also the #'d assig notifications.
    """
    def filter(self, avisos):
        result = []
        if not avisos: return []
        for avis in avisos:
            if not self.last_check: result.append(avis)
            elif self.get_date(avis) > self.last_check:
                if self.thread_logging: log("N_Thread: Hay una nueva publicación!")
                if '#' in avis['codi_assig']: pass
                else: result.append(avis)
        return result

    """
        Parameters:
            avis(:obj:`dict`): One publication

        This function returns the date of a publication. It also converts it to datetime.
        so it returns (:class:`datetime.datetime`)

        2018-03-01T00:00:00 -> datetime(year, month, day, hour, minute, second)
    """
    def get_date(self, avis):
        avis_date = avis['data_modificacio']
        avis_date_day, avis_date_hour = avis_date.split('T')
        year, month, day = avis_date_day.split('-')
        hour, minute, second = avis_date_hour.split(':')
        return datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), int(second))

    """
        Allows polling
    """
    def stop_polling(self):
        self.polling = False

    """
        Forbids polling
    """
    def start_polling(self):
        self.polling = True
        self.run()
Ejemplo n.º 11
0
from Fibot.chats import Chats
from Fibot.api.api_raco import API_raco
from Fibot.Data.data_types.exam import Exam_schedule
from Fibot.Data.data_types.practical_work import Practical_schedule
from pprint import pprint

c = Chats()
c.load()
a = API_raco()
a_t = c.get_chat('349611162')['access_token']
user_lang = c.get_chat('349611162')['language']
exams = list(a.get_exams_user(a_t))
e_e = Exam_schedule(exams, user_lang)

pprint(list(e_e.get_closest_exams(range=50)))

pracs = list(a.get_practiques(a_t))
p_e = Practical_schedule(pracs, user_lang)

pprint(list(p_e.get_closest_pracs(range=50)))