예제 #1
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __show_day(self):
        """
        Shows timetable for whole day
        """
        if not self._check_day():
            return

        # Add week day as title
        result = self.responses['week_days'][self.day] + "\n"
        # Generate message body
        for lesson_number in self.timetable[self.week][self.day]:
            lesson = self.timetable[self.week][self.day][lesson_number]
            result += str(lesson_number) + ": " + lesson['discipline']['name'] + \
                (" (" + types[lesson['type']] + ")" if lesson['type'] else "") + " - "

            # Add rooms to response
            result += self.generate_rooms_string(lesson['rooms'])

            # If "T" parameter
            if self.show_teacher:
                if lesson['teachers']:
                    for teacher in lesson['teachers']:
                        result += "— " + teacher['name'] + "\n"
                else:
                    result += "— " + self.responses['no_teacher'] + "\n"

        reply(self.chat_id, msg=result)
예제 #2
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __init__(self, chat_id, message, teacher_id=None):
        try:
            super().__init__(chat_id, message)
            if self.is_wrong_parameter:
                raise StopExecution

            if teacher_id:
                self.teacher_id = teacher_id
            else:
                command = message.split()[0].split('@')[0]
                if self.show_teacher or (self.group_id != 0 and command != "/setgroup"):
                    reply(self.chat_id, msg=self.responses['wrong_parameter_for_teacher'])
                    self.is_wrong_parameter = True
                    raise StopExecution

                if self.teacher_id == 0:
                    chat = Chat.objects.get(pk=chat_id)
                    self.teacher_id = chat.teacher_id

            # Get teacher timetable
            raw_response = requests.get(TIMETABLE_URL + "teachers/%i/timetable.json" % self.teacher_id)
            if raw_response.status_code == 200:
                response = raw_response.json()
                self.timetable = response['data']
                self.timetable = utils.prettify(self.timetable)
            else:
                if command not in ['/setgroup', '/setteacher']:
                    reply(self.chat_id, msg=self.responses['get_tt_error'])
                    self.is_wrong_parameter = True

        except StopExecution:
            pass
예제 #3
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __init__(self, chat_id, message):
        try:
            super().__init__(chat_id, message)
            if self.is_wrong_parameter:
                raise StopExecution

            # Check if group was set (by /setgroup or passed as parameter)
            if self.group_id == 0:
                chat = Chat.objects.get(pk=chat_id)
                self.group_id = chat.group_id

                if self.group_id == 0:
                    reply(self.chat_id, msg=self.responses['empty_group'])
                    self.is_wrong_parameter = True
                    raise StopExecution

            # Get group timetable
            raw_response = requests.get(TIMETABLE_URL + "groups/%i/timetable.json" % self.group_id)
            if raw_response.status_code == 200:
                response = raw_response.json()
                self.timetable = response['data']
                self.timetable = utils.prettify(self.timetable)
            else:
                reply(self.chat_id, msg=self.responses['no_timetable_for_group'])
                self.is_wrong_parameter = True
        except StopExecution:
            pass
예제 #4
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def answer_teacher_query(self, is_teachertt=False):
        raw_response = requests.get(TIMETABLE_URL + "teachers/?search=%s" % self.teacher_query)

        # Check teacher existance
        if raw_response.status_code != 200:
            reply(self.chat_id, self.responses['unknown_teacher'])
            return

        # List all teachers that satisfy requirements
        response = raw_response.json()
        teachers = response['results']
        if response['count'] == 1:
            self.teacher_id = teachers[0]['id']
            if is_teachertt:
                self.show_teacher_tt()
            else:
                self.setteacher_id()
        else:
            keyboard = []
            if is_teachertt:
                result = self.responses['teacher_tt']
            else:
                result = self.responses['setteacher_filter'].format(self.teacher_query)
            for teacher in teachers:
                row = []
                if is_teachertt:
                    row.append("/teacher %i" % teacher['id'])
                else:
                    row.append("/setteacher %i" % teacher['id'])
                keyboard.append(row)
                result += teacher['name'] + ' - ' + str(teacher['id']) + '\n'
            reply(self.chat_id, msg=result, keyboard=keyboard)
예제 #5
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def tt(self):
        # To specify lesson number
        if self.lesson_number != 0:
            if self.day != 0 and self.week != 0:
                self.__show_lesson()
                return
            else:
                reply(self.chat_id, msg=self.responses['no_week_or_day'])
                return

        week_range = [self.week]
        if self.week == 0:
            if self.day != 0:
                reply(self.chat_id, msg=self.responses['no_week'])
                return
            week_range = list(range(1, 3))

        for self.week in week_range:
            reply(self.chat_id, msg="Week #" + str(self.week) + ":")
            if self.day == 0:
                for self.day in range(1, 7):
                    self.__show_day()
                self.day = 0
            else:
                self.__show_day()
예제 #6
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __show_lesson(self, show_time_to_end=False):
        """
        Shows only one lesson
        """
        if not self._check_day():
            return

        # Check lesson existance
        if self.lesson_number not in self.timetable[self.week][self.day]:
            reply(self.chat_id, msg=self.responses['no_lesson'])
            return

        # Generating message body
        lesson = self.timetable[self.week][self.day][self.lesson_number]

        result = self.responses['week_days'][self.day] + ":\n" + \
                 str(self.lesson_number) + ": " + lesson['discipline']['name'] + " - " + \
                 self.generate_rooms_string(lesson['rooms'])

        # Show teacher
        if self.show_teacher:
            if lesson['teachers']:
                for teacher in lesson['teachers']:
                    result += "— " + teacher['name'] + "\n"
            else:
                result += "— " + self.responses['no_teacher'] + "\n"

        # Add showing time to the end or lesson for /now command
        if show_time_to_end:
            now = datetime.datetime.now()
            time_to_end = str(int((pairs[self.lesson_number + 1] - now).total_seconds() // 60))
            reply(self.chat_id, msg=result + self.responses['minutes_left'].format(time_to_end))
        else:
            reply(self.chat_id, msg=result)
예제 #7
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __read_parameters(self, message):
        """
        Transform command parameters to class fields
        """
        if len(message.split()) > 1:
            for token in message.split()[1:]:
                self.parameters.append(token)
                if re.match("[A-zА-яіє]{2,4}-?[A-zА-яіє]{0,2}[0-9]{2,3}[A-zА-яіє]?\(?[A-zА-яіє]*\)?", token):
                    token = transliterate(token)
                    group_name = token
                    if '-' not in token:
                        number_position = re.search("\d", token).start()
                        group_name = token[:number_position] + '-' + token[number_position:]

                    self.group_id = utils.get_group_id_by_name(group_name)
                    if self.group_id == -2:
                        self.group_name = group_name
                        self.parameters.pop()
                elif re.match("[w][1|2]{1,1}", token):
                    self.week = int(token[1])
                elif re.match("[w]{1,1}", token):
                    self.week = 2 - datetime.date.today().isocalendar()[1] % 2
                elif utils.get_week_day(token):
                    self.day = utils.get_week_day(token)
                #elif re.match("[1-6]{1,1}", token):
                #    self.lesson_number = int(token)
                elif re.match("[t]{1,1}", token):
                    self.show_teacher = True
                elif re.match("[0-9]+", token):
                    #self.teacher_id = int(token)
                    if int(token) < 7:
                        self.lesson_number = int(token)
                    else:
                        self.teacher_id = int(token)
                elif re.match("[A-zА-яіє]+", token):
                    self.teacher_query += token if not self.teacher_query else (" " + token)
                else:
                    reply(self.chat_id, msg=self.responses['wrong_parameter'])
                    self.is_wrong_parameter = True
예제 #8
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def who(self):
        # Check lesson existance
        self._check_day()
        if self.lesson_number not in self.timetable[self.week][self.day]:
            reply(self.chat_id, msg=self.responses['no_lesson'])

        lesson = self.timetable[self.week][self.day][self.lesson_number]

        # Check if teachers set in timetable
        if not lesson['teachers']:
            reply(self.chat_id, msg=self.responses['no_teacher'])

        result = ""
        for teacher in lesson['teachers']:
            result += teacher['full_name'] + "\n"

        reply(self.chat_id, msg=result)
예제 #9
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def _check_day(self):
        # Custom reply for sunday
        if self.day == 7:
            reply(self.chat_id, self.responses['sunday'])
            return False

        # Check day existance
        if self.week not in self.timetable or\
           self.day not in self.timetable[self.week] or\
           not self.timetable[self.week][self.day]:
            if not self.show_full_week:
                reply(self.chat_id, msg=self.responses['get_tt_error'])
            return False
        elif self.day not in self.timetable[self.week] or self.timetable[self.week][self.day] == {}:
            if not self.show_full_week:
                reply(self.chat_id, msg=self.responses['get_tt_error'])
            return False
        return True
예제 #10
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def where(self):
        if not self._check_day():
            return

        # Check lesson existance
        if self.lesson_number not in self.timetable[self.week][self.day]:
            reply(self.chat_id, msg=self.responses['no_lesson'])
            return

        lesson = self.timetable[self.week][self.day][self.lesson_number]

        # Check if room set in timetable
        if not lesson['rooms']:
            reply(self.chat_id, msg=self.responses['no_room'])
            return

        coordinates = {}
        for room in lesson['rooms']:
            coordinates['longitude'] = float(room['building']['longitude'])
            coordinates['latitude'] = float(room['building']['latitude'])
            reply(self.chat_id, location=coordinates)
예제 #11
0
파일: views.py 프로젝트: Alidal/kpibot
def index(request):
    chat = Chat()
    message = ""
    chat_id = ""
    try:
        data = json.loads(request.body.decode("utf-8"))
        chat_id = data["message"]["chat"]["id"]
        user_id = data["message"]["from"]["id"]
        message = data["message"]["text"]
        chat = Chat.objects.get(pk=chat_id)
    # If chat not in database
    except Chat.DoesNotExist:
        chat = Chat(chat_id=chat_id)
        chat.save()
    except Exception:
        return HttpResponse()

    # Set user language
    responses = ru if chat.language == "ru" else ua
    # Make commands and parameters case insensitive
    message = message.lower()

    try:
        # Check command existance
        command = message.split()[0].split("@")[0]
        if command not in commands:
            return HttpResponse()

        # Statistics
        track(miscellaneous.key.BOTAN_TOKEN, user_id, {get_group_name_by_id(chat.group_id): 1}, "Group")
        track(miscellaneous.key.BOTAN_TOKEN, user_id, {}, command)

        # If command doesn't need timetable
        if command == "/start" or command == "/help":
            reply(chat_id, msg=responses["instructions"])
        elif command == "/authors":
            reply(chat_id, msg=responses["authors"])
        elif command == "/week":
            reply(chat_id, msg=responses["week"].format(2 - datetime.date.today().isocalendar()[1] % 2))
        elif command == "/time":
            reply(chat_id, msg=time)
        elif command == "/changelang":
            if chat.language == "ru":
                chat.language = "ua"
                reply(chat_id, msg=ua["change_lang"])
            else:
                chat.language = "ru"
                reply(chat_id, msg=ru["change_lang"])
            chat.save()

        if command in no_timetable_commands:
            return HttpResponse()

        # If command require timetable
        tt = TeacherTimetable(chat_id, message) if chat.group_id == -1 else GroupTimetable(chat_id, message)

        # Check wrong parameter and access error
        if tt.is_wrong_parameter:
            return HttpResponse()

        # Command processing
        getattr(tt, command[1:])()
    except:
        pass
    finally:
        return HttpResponse()
예제 #12
0
파일: timetable.py 프로젝트: Alidal/kpibot
    def __check_parameters(self, command, parameters_number):
        if parameters_number > commands[command]:
            reply(self.chat_id, self.responses['wrong_parameters_number'])
        elif command != "/tt" and (self.week != 0 or self.day != 0):# or self.lesson_number != 0):
            reply(self.chat_id, msg=self.responses['wrong_parameter'])
        elif (command != "/setteacher" and command != "/teacher") and (self.teacher_query != "" or self.teacher_id != 0):
            reply(self.chat_id, msg=self.responses['wrong_parameter'])
        elif (command == "/setteacher" or command == "/teacher") and self.teacher_id == 0 and self.teacher_query == "":
            reply(self.chat_id, msg=self.responses['no_required_parameter'])
        elif command == "/setgroup" and self.group_id == -1:
            reply(self.chat_id, msg=self.responses['unknown_group'])
        elif command == "/setgroup" and self.group_id == 0:
            reply(self.chat_id, msg=self.responses['no_required_parameter'])
        elif self.group_id == -2:
            query = Group.objects.filter(group_name__icontains=self.group_name + "(")
            keyboard = []
            for item in query:
                row = []
                row.append("{0} {1} ".format(command, item.group_name) + " ".join(self.parameters))
                keyboard.append(row)
            reply(self.chat_id, msg=self.responses['same_group'], keyboard=keyboard)

        elif command == "/tt" and self.day == 0:
            self.show_full_week = True
            self.is_wrong_parameter = False
        else:
            self.is_wrong_parameter = False
예제 #13
0
파일: timetable.py 프로젝트: Alidal/kpibot
 def who(self):
     """
     /who command isn't allowed in teachers mode. So we overload it, to send error
     """
     reply(self.chat_id, msg=self.responses['wrong_command_for_tm'])
예제 #14
0
파일: timetable.py 프로젝트: Alidal/kpibot
 def setteacher_id(self):
     c = Chat(chat_id=self.chat_id,
              group_id=-1,
              teacher_id=self.teacher_id)
     c.save()
     reply(self.chat_id, msg=self.responses['setteacher_success'])
예제 #15
0
파일: timetable.py 프로젝트: Alidal/kpibot
 def setgroup(self):
     c = Chat(chat_id=self.chat_id,
              group_id=self.group_id,
              teacher_id=0)
     c.save()
     reply(self.chat_id, msg=self.responses['setgroup_success'])