def dept_command(msg): person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") args = msg.text.split()[1:] if len(args) == 1: if args[0] == 'list': if not person.head: return tb.reply_to(msg, "У вас нема доступа до цієї команди") students_with_dept = session.query(Student).filter(Student.has_debt).all() if len(students_with_dept) > 0: return tb.send_message( msg.chat.id, "Студенти які мають борг:\n" f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(students_with_dept)))}", parse_mode='Markdown' ) else: return tb.send_message(msg.chat.id, "Немає студентів з боргом") else: return tb.send_message(msg.chat.id, "Незнайомий аргумент, доступні: <list>") if person.head: return tb.send_message(msg.chat.id, "У керівника не може бути боргу 😂") tb.send_message( msg.chat.id, "У вас є борг по практиці" if person.student.has_debt else 'У вас немає боргу по практиці' )
def meeting_notify(): today = datetime.today() meetings_with_head = session.query(MeetingWithHead).all() for meeting_with_head in meetings_with_head: faculty = meeting_with_head.head.faculty practice_term_start_date = faculty.practice_term.start_date.strptime( "%Y-%m-%d") days_left_to_practice_start = (practice_term_start_date - today).days if 0 < days_left_to_practice_start <= 7: for group in faculty.groups: for student in group.students: if student.person.telegram_id: tb.send_message( student.person.telegram_id, f"Зустріч з керівником практики запланована на:\n\n" f"*Дата*\n" f"{meeting_with_head.meeting.date}\n" f"*Час початку*\n" f"{meeting_with_head.meeting.start_time}\n" f"*Час завершення*\n" f"{meeting_with_head.meeting.end_time}\n" f"*Місце проведення*\n" f"{meeting_with_head.meeting.place}", parse_mode='Markdown', )
def exam_meeting_notify(): today = datetime.today() exam_meetings = session.query(ExamMeeting).all() for exam_meeting in exam_meetings: faculty = exam_meeting.head.faculty practice_term_start_date = faculty.practice_term.start_date.strptime( "%Y-%m-%d") days_left_to_practice_start = (practice_term_start_date - today).days if 0 < days_left_to_practice_start <= 7: for group in faculty.groups: for student in group.students: if student.person.telegram_id: tb.send_message( student.person.telegram_id, f"Термін екзамену:\n\n" f"*Дата*\n" f"{exam_meeting.meeting.date}\n" f"*Час початку*\n" f"{exam_meeting.meeting.start_time}\n" f"*Час завершення*\n" f"{exam_meeting.meeting.end_time}\n" f"*Місце проведення*\n" f"{exam_meeting.meeting.place}", parse_mode='Markdown', )
def delete(self, id): content = session.query(Address).filter(Address.id == id).first() if not content: abort(404, message="Content {} doesn't exist".format(id)) session.delete(content) session.commit() return {}, 204
def delete(self, id): address = session.query(Address).filter(Address.id == id).first() if not address: abort(404, message="Address {} doesn't exist".format(id)) session.delete(address) session.commit() return {}, 204
def delete(self, id): box = session.query(Box).filter(Box.id == id).first() if not box: abort(404, message="Box {} doesn't exist".format(id)) session.delete(box) session.commit() return {}, 204
def selected_place(): documents = [ open(os.path.join(os.path.dirname(os.getcwd()), 'паспорт_бази_практики.docx'), "rb"), open(os.path.join(os.path.dirname(os.getcwd()), 'договір.docx'), "rb") ] today = datetime.today() faculties = session.query(Faculty).all() for faculty in faculties: practice_term_start_date = faculty.practice_term.start_date.strptime("%Y-%m-%d") days_left_to_practice_start = (practice_term_start_date - today).days if 0 < days_left_to_practice_start <= 14: for group in faculty.groups: for student in group.students: if student.person.telegram_id: tb.send_message( student.person.telegram_id, "Ви ще не вибрали місце практики, " "будь ласка ознайомтесь з переліком завдяки команді /places list " "та виберіть один з доступних варіантів завдяки команді /places take.\n\n" "Також оформить наступний перелік документів:", parse_mode='Markdown', ) tb.send_media_group(student.person.telegram_id, [InputMediaDocument(doc) for doc in documents])
def inform_command(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") if person.student: return tb.send_message(msg.chat.id, "Ця команда для керівників практики!") not_informed_students = [] informed_students = [] args = msg.text.split()[1:] if len(args) > 1: inform_message = ' '.join(args) for group in person.faculty.groups: for student in group.students: if not student.person.telegram_id: not_informed_students.append(student) continue tb.send_message(student.person.telegram_id, inform_message) informed_students.append(student) tb.send_message( msg.chat.id, f"Інформованих студентів: {len(informed_students)}\n" "Не отримали повідомленя: \n" f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(not_informed_students)))}", parse_mode='Markdown')
def getAllPlaces(): places = session.query(Place).all() if len(places) == 0: return jsonify(message="Not Found"), 404 if places is not None: return jsonify([_placeDict(place) for place in places]), 200
def graph(): get_latest = session.query(Attachment) \ .filter(Attachment.key == "graph.harian") \ .order_by(Attachment.created.desc()) \ .first() scr_png = b64decode(get_latest.attachment) scr_img = Image(blob=scr_png) return Response(scr_img.make_blob(), mimetype='image/jpeg')
def getAllStories(): stories = session.query(Story).all() if len(stories) == 0: return jsonify(message="Not Found"), 404 if stories is not None: return jsonify([_storyDict(story) for story in stories]), 200
def send_welcome(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if person: return tb.send_message(msg.chat.id, f"Привіт {person.fullname} 😊") tb.send_message(msg.chat.id, "Привіт, ким ти є?", reply_markup=identity_markup)
def places_command(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") args = msg.text.split()[1:] if len(args) == 1: if args[0] == 'list': places = session.query(PlaceOfPractice).all() return tb.send_message( msg.chat.id, "Доступні місця практики:\n" f"{os.linesep.join((f'{i + 1}. {place.name}' for (i, place) in enumerate(places)))}", parse_mode='Markdown') elif args[0] == 'take': if person.head: return tb.send_message(msg.chat.id, "Що, керівник, хочеш на практику?)") return tb.send_message(msg.chat.id, "Вкажіть номер практики:", reply_markup=ForceReply(selective=False)) elif args[0] == 'taken': if person.student: return tb.send_message( msg.chat.id, "В тебе немає доступу до цієї команди! 😡") determined_students = session.query(Student).filter( Student.place_of_practice).all() the_rest = session.query(Student).filter( not Student.place_of_practice).all() return tb.send_message( msg.chat.id, f"Вибрали місце практики: {len(determined_students)}\n" f"Не вибрали місце практики:\n" f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(the_rest)))}", parse_mode='Markdown') return tb.send_message( msg.chat.id, "Незнайомий аргумент, доступні: <list>, <take>, <taken>")
def put(self, id): address = session.query(Address).filter(Address.id == id).first() if not address: abort(404, message="Address {} doesn't exist".format(id)) ADDRESS_ARGS = valid_request_arguments['Address'] parsed_args = parser.parse_args() for addr_arg in ADDRESS_ARGS: if addr_arg in parsed_args and parsed_args[addr_arg]: setattr(address, addr_arg, parsed_args[addr_arg]) session.commit() return address, 201
def getUser(user_id): user = session.query(User).get(user_id) if user is not None: return jsonify({ "id": user.id, "name": user.name, "email": user.email, "birthdate": time.mktime(user.birthdate.timetuple()), "phone": user.phone, "created": time.mktime(user.created.timetuple()) }), 200 return jsonify(message="Not Found"), 404
def put(self, id): box = session.query(Box).filter(Box.id == id).first() if not box: abort(404, message="Box {} doesn't exist".format(id)) parsed_args = parser.parse_args() BOX_ARGS = valid_request_arguments['Box'] for box_arg in BOX_ARGS: if box_arg in parsed_args and parsed_args[box_arg]: setattr(box, box_arg, parsed_args[box_arg]) session.commit() return box, 201
def put(self, id): content = session.query(Content).filter(Content.id == id).first() if not content: abort(404, message="Address {} doesn't exist".format(id)) CONTENT_ARGS = valid_request_arguments['Content'] parsed_args = parser.parse_args() for addr_arg in CONTENT_ARGS: if addr_arg in parsed_args and parsed_args[addr_arg]: setattr(content, addr_arg, parsed_args[addr_arg]) session.commit() return content, 201
def get_person_fullname(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not msg.text.isdigit(): return tb.send_message( msg.chat.id, "Введіть порядковий номер місця практики зі списку доступних місць" ) place = session.query(PlaceOfPractice).filter( PlaceOfPractice.id == int(msg.text)).first() if not place: return tb.send_message( msg.chat.id, "Не знайдено жодного місця практики за цим номером") person.student.place_of_practice = place session.commit() tb.send_message(msg.chat.id, f"Ви успішно вибрали _{place.name}_ місцем практики", parse_mode='Markdown')
def queryPlaces(): body = request.get_json() places = session.query(Place) \ .filter(or_(Place.name.like(f'%{body.get("name")}%'), Place.lng == body.get("long"), Place.lat == body.get("lat")) ) \ .all() if len(places) == 0: return jsonify(message="Not Found"), 404 if places is not None: return jsonify([_placeDict(place) for place in places]), 200
def get_paginated_users( rows_per_page: int, page_number: int ) -> tuple[list[GitHubUserOrm], int, int]: """ :param rows_per_page: How many rows will a table page contain :param page_number: The actual page number to fetch :return: The user list, with the rows and page info """ rows = rows_per_page if rows_per_page > 0 else 1 page = page_number if page_number > 0 else 1 raw_users = session.query(GitHubUserOrm).limit(rows).offset((page - 1) * rows).all() return [GitHubUser.from_orm(user).dict() for user in raw_users], rows, page
def head_command(msg): person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") if person.head: return tb.send_message(msg.chat.id, "Ви все про себе знаєте 😊") faculty = person.student.group.faculty tb.send_message( msg.chat.id, f"Керівником практики факультету *{faculty.short}* є" f"[{faculty.head.person.fullname}](https://t.me/user?id={faculty.head.person.telegram_id})", parse_mode='Markdown' )
def getAllPlaces(): diff = (datetime.utcnow() - timedelta(days=2)) if request.args.get("days"): diff = (datetime.utcnow() - timedelta(days=int(request.args.get("days")))) if request.args.get("hours"): diff = (datetime.utcnow() - timedelta(days=int(request.args.get("hours")))) places = session.query(Place).all() if len(places) == 0: return jsonify(message="Not Found"), 404 if places is not None: return jsonify([_placeDict(place) for place in places]), 200
def schedule_command(msg): person = session.query(Person).filter( Person.telegram_id == msg.chat.id).first() if not person: return tb.send_message(msg.chat.id, "Ви не зареєстровані") args = msg.text.split()[1:] if len(args) == 1: if args[0] == 'change': if person.student: return tb.send_message( msg.chat.id, "В тебе немає доступу до цієї команди! 😡") return tb.send_message(msg.chat.id, "Очікую файл розкладу", reply_markup=ForceReply(selective=False)) elif args[0] == 'show': schedule = None if person.student: schedule = person.student.group.faculty.schedule elif person.head: schedule = person.head.faculty.schedule if not schedule: return tb.send_message(msg.chat.id, "Розкладу поки що немає 😢") return tb.send_message( msg.chat.id, f"Розклад консультацій від *{schedule.created_date.strftime('%Y-%m-%d')}*:\n\n" "\n".join( (f"*Дата*\n" f"{schedule_meeting.meeting.date}\n" f"*Час початку*\n" f"{schedule_meeting.meeting.start_time}\n" f"*Час завершення*\n" f"{schedule_meeting.meeting.end_time}\n" f"*Місце проведення*\n" f"{schedule_meeting.meeting.place}\n" for schedule_meeting in schedule.schedule_meetings)), parse_mode='Markdown') return tb.send_message(msg.chat.id, "Незнайомий аргумент, доступні: <change>, <show>")
def id(): req = requests.get(KAWAL_COVID) data = req.json() updated = parser.parse(data['metadata']['lastUpdatedAt']) \ .replace(tzinfo=None) alldata = session.query(Status) \ .filter(Status.country_id == "id") \ .order_by(Status.created.desc()).all() dbDate = "" if len(alldata) > 0: getData = [_id_beauty(data, row) for row in alldata] dbDate = parser.parse(getData[0]["metadata"]["last_updated"]) \ .replace(tzinfo=None) if not updated == dbDate: new_status = Status(confirmed=data['confirmed']['value'], deaths=data['deaths']['value'], recovered=data['recovered']['value'], active_care=data['activeCare']['value'], country_id="id", created=updated, updated=updated) session.add(new_status) for index, row in enumerate(getData): if not row['confirmed']['diff'] == 0 and \ not row['deaths']['diff'] == 0 and \ not row['recovered']['diff'] == 0 and \ not row['active_care']['diff'] == 0: row['metadata']['last_updated'] = \ getData[index-1]['metadata']['last_updated'] return _response(row, 200) return _response(getData[0], 200) else: new_status = Status(confirmed=data['confirmed']['value'], deaths=data['deaths']['value'], recovered=data['recovered']['value'], active_care=data['activeCare']['value'], country_id="id", created=updated, updated=updated) session.add(new_status) return _response(_id_beauty(data, 0), 200)
def get_schedule_file(msg): person = session.query(Person).filter( func.lower(Person.fullname) == func.lower(msg.text)).first() if not person: return tb.send_message( msg.chat.id, f"Такого ПІБ немає у базі, зв'яжіться з [адміністратором](https://t.me/Regis322)", parse_mode='Markdown') if person.telegram_id: return tb.send_message( msg.chat.id, "Людина за цим ПІБ вже зареэстрована, зв'яжіться з [адміністратором](https://t.me/Regis322)", parse_mode='Markdown') person.telegram_id = msg.chat.id session.add(person) session.commit() tb.send_message(msg.chat.id, "Ваш ПІБ знайдено у базі, ваш телеграм під'єднано")
def practice_terms(): today = datetime.today() faculties = session.query(Faculty).all() for faculty in faculties: practice_term_start_date = faculty.practice_term.start_date.strptime( "%Y-%m-%d") practice_term_end_date = faculty.practice_term.start_date.strptime( "%Y-%m-%d") days_left_to_practice_start = (practice_term_start_date - today).days if 0 < days_left_to_practice_start <= 3: for group in faculty.groups: for student in group.students: if student.person.telegram_id: tb.send_message( student.person.telegram_id, f"Кількість днів до початку практики: {days_left_to_practice_start}\n\n" f"*Дата початку практики*\n" f"{practice_term_end_date}\n\n" f"*Дата завершення практики*\n" f"{practice_term_end_date}", parse_mode='Markdown')
def id(): req = requests.get("https://kawalcovid19.harippe.id/api/summary") data = req.json() updated = parser.parse(data['metadata']['lastUpdatedAt']) \ .replace(tzinfo=None) alldata = session.query(Status).order_by(Status.id.desc()).all() dbDate = "" if len(alldata) > 0: getData = [_id_beauty(data, row) for row in alldata] dbDate = parser.parse(getData[0]["metadata"]["last_updated"]) \ .replace(tzinfo=None) if not updated == dbDate: new_status = Status(confirmed=data['confirmed']['value'], deaths=data['deaths']['value'], recovered=data['recovered']['value'], active_care=data['activeCare']['value'], country_id="id", created=updated, updated=updated) session.add(new_status) for row in getData: if not row['confirmed']['diff'] == 0 and \ not row['deaths']['diff'] == 0 and \ not row['recovered']['diff'] == 0 and \ not row['active_care']['diff'] == 0: return jsonify(row), 200 return jsonify(getData[0]), 200 else: new_status = Status(confirmed=data['confirmed']['value'], deaths=data['deaths']['value'], recovered=data['recovered']['value'], active_care=data['activeCare']['value'], country_id="id", created=updated, updated=updated) session.add(new_status) return jsonify(_id_beauty(data, 0)), 200
def getPlace(place_id): place = session.query(Place).get(place_id) if place is not None: return jsonify(_placeDict(place)), 200 return jsonify(message="Not Found"), 404
def _odi_api(state): req = requests.get(ODI_API) if not req.status_code == 200: jsonify({"message": f"Error when trying to crawl {ODI_API}"}), 404 prov = {prov["provinsi"]: prov for prov in req.json()["data"]} hasil = prov[DAERAH[state]] todayIsNone = True result = _default_resp() result['metadata'] = { "source": "https://indonesia-covid-19.mathdro.id/", "province": DAERAH[state].upper() } get_state = session.query(Status) \ .filter(Status.country_id == f"id.{state}") \ .order_by(Status.created.desc()) \ .all() if len(get_state) > 0: for row in get_state: if not row.created.date() == datetime.utcnow().date(): result["total_sembuh"]["diff"] = \ hasil["kasusSemb"] - row.recovered result["total_positif"]["diff"] = \ hasil["kasusPosi"] - row.confirmed result["total_meninggal"]["diff"] = \ hasil["kasusMeni"] - row.deaths result["metadata"]["diff_date"] = \ row.created.isoformat() result["metadata"]["source_date"] = \ datetime.utcnow().isoformat() break else: todayIsNone = False result["metadata"]["source_date"] = \ row.created.isoformat() if todayIsNone: new_status = Status(confirmed=hasil["kasusPosi"], deaths=hasil["kasusMeni"], recovered=hasil["kasusSemb"], active_care=0, country_id=f"id.{state}", created=datetime.utcnow(), updated=datetime.utcnow()) session.add(new_status) result["metadata"]["source_date"] = \ datetime.utcnow().isoformat() result["total_sembuh"]["value"] = hasil["kasusSemb"] result["total_positif"]["value"] = hasil["kasusPosi"] result["total_meninggal"]["value"] = hasil["kasusMeni"] if len(result) == 0: jsonify({"message": "Not Found"}), 404 if is_bot(): return jsonify(message=bot.province(result)), 200 else: return jsonify(result), 200
def get_schedule_file(msg): person = session.query(Person).filter(Person.telegram_id == msg.chat.id).first() # FILE SIZE CHECK if msg.document.file_size > 500000: return tb.send_message(msg.chat.id, "Файл великого розміру (0.5mb max)") # DOWNLOADING THE FILE tg_cloud_file = tb.get_file(msg.document.file_id) binary_data = tb.download_file(tg_cloud_file.file_path) # CREATING TEMPORARY FILE WRAPPER schedule_file = TemporaryFile() schedule_file.write(binary_data) # DELETING CURRENT SCHEDULE FROM DB if person.head.faculty.schedule: session.delete(person.head.faculty.schedule) session.commit() # PARSING TABLE WITH DAYS OF PRACTICE schedule = Schedule(faculty=person.head.faculty) try: schedule_sheet = openpyxl.load_workbook(schedule_file).active for row_idx in range(2, schedule_sheet.max_row + 1): schedule.schedule_meetings.append( ScheduleMeeting( schedule=schedule, meeting=Meeting( date=schedule_sheet.cell(row_idx, 1).value.strftime("%Y-%m-%d"), start_time=schedule_sheet.cell(row_idx, 2).value.strftime("%H:%M"), end_time=schedule_sheet.cell(row_idx, 3).value.strftime("%H:%M"), place=schedule_sheet.cell(row_idx, 4).value, ) ) ) except (ValueError, TypeError): tb.reply_to(msg, "Помилка у парсингу файла") schedule_file.close() return # INSERTING NEW SCHEDULE TO DB person.head.faculty.schedule = schedule session.commit() # NOTIFYING FOR SUCCESS AND CLEANING UP tb.reply_to(msg, "Успішно завантажено новий розклад!") schedule_file.close() # INFORMING THE STUDENTS WITH NEW SCHEDULE BY SENDING THE FILE not_informed_students = [] informed_students = [] for group in person.head.faculty.groups: for student in group.students: if not student.person.telegram_id: not_informed_students.append(student) continue tb.send_document( student.person.telegram_id, msg.document.file_id, caption="Шановний студент! Розклад консультацій змінено, лови актуальний" ) informed_students.append(student) # NOTIFYING ABOUT THE RESULTS ABOUT STUDENTS INFORMATION tb.send_message( msg.chat.id, f"Інформованих студентів: {len(informed_students)}\n" "Не отримали повідомленя: \n" f"{os.linesep.join((f'{i + 1}. {student.person.fullname}' for (i, student) in enumerate(not_informed_students)))}", parse_mode='Markdown' )