def Init(self): try: self._NetSchoolShell__api = NetSchoolAPI(self.URL) except Exception as exception: try: print(exception) finally: exception = None del exception
async def _(message: types.CallbackQuery): await bot.answer_callback_query(message.id) user = user_dict[message.from_user.id] today = datetime.date.today() tomorrow = today + datetime.timedelta(days=1) account = account_dict[user.account_id] result = '' async with NetSchoolAPI(account.url, account.login, account.password, (account.oblast, account.okrug, account.sity, account.type, account.school)) as api: diary = await api.get_diary(week_start=tomorrow, week_end=tomorrow) if user.logic == 'rasp': try: for lesson in diary['weekDays'][0]['lessons']: result += '\n' + str(lesson['number']) + '.' + str( lesson['subjectName']) + '(' + str( lesson['startTime']) + '-' + str( lesson['endTime']) + ')' except IndexError: result = 'На завтра расписания нету!' elif user.logic == 'dz': try: for lesson in diary['weekDays'][0]['lessons']: try: result += '\n' + str(lesson['subjectName']) + ': ' + str( lesson['assignments'][0]['assignmentName']) except KeyError: pass except IndexError: result = 'На завтра дз нету!' try: await bot.send_message(message.from_user.id, result) except Exception: await bot.send_message(message.from_user.id, 'Пусто')
async def main(): login_data = { "login": "******", "password": "******", "school": "МАОУ многопрофильный лицей №20" } async with NetSchoolAPI("http://sgo.cit73.ru/", **login_data) as api: print(await api.get_announcements())
async def _(message: types.Message): try: user = user_dict[message.from_user.id] if user.logic == 'login': reg_ex = re.search('(.*) (.*)', message.text) if reg_ex: account_dict[user.account_id].login = reg_ex.group(1) account_dict[user.account_id].password = reg_ex.group(2) user.logic = None try: account = account_dict[user.account_id] account_dict[ user.account_id].url = 'ССЫЛКА НА САЙТ ДНЕВНИКА' account_dict[user.account_id].oblast = 'Регион' account_dict[ user. account_id].okrug = 'Городской округ / Муниципальный район' account_dict[user.account_id].sity = 'Населённый пункт' account_dict[user.account_id].type = 'Тип ОО' account_dict[ user. account_id].school = 'Образовательная организация"' async with NetSchoolAPI( account.url, account.login, account.password, (account.oblast, account.okrug, account.sity, account.type, account.school)) as api: diary = await api.get_diary( week_start=datetime.date.today(), week_end=datetime.date.today()) user.account_id = None keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton('Меню', callback_data='menu')) await bot.send_message( message.from_user.id, 'Успешно!\nТеперь перейдите в меню и выберите там новый аккаунт', reply_markup=keyboard) except Exception as e: user.accounts.remove(user.account_id) user.account_id = None keyboard = InlineKeyboardMarkup() keyboard.add( InlineKeyboardButton('Новый аккаунт', callback_data='new_account')) await bot.send_message(message.from_user.id, 'Ошибка: ' + str(e) + '\nЗаполните по новой', reply_markup=keyboard) else: await bot.send_message( message.from_user.id, 'Не могу найти в твоем сообщении логин или пароль') except Exception as e: pass
async def _(message: types.CallbackQuery): await bot.answer_callback_query(message.id) user = user_dict[message.from_user.id] today = datetime.date.today() tomorrow = today + datetime.timedelta(days=+-1) account = account_dict[user.account_id] result = '' async with NetSchoolAPI(account.url, account.login, account.password, (account.oblast, account.okrug, account.sity, account.type, account.school)) as api: diary = await api.get_diary(week_start=tomorrow, week_end=tomorrow) if user.logic == 'rasp': try: for lesson in diary['weekDays'][0]['lessons']: result += '\n' + str(lesson['number']) + '.' + str( lesson['subjectName']) + '(' + str( lesson['startTime']) + '-' + str( lesson['endTime']) + ')' except IndexError: result = 'На вчера расписания нету!' elif user.logic == 'dz': try: for lesson in diary['weekDays'][0]['lessons']: try: result += '\n' + str(lesson['subjectName']) + ': ' + str( lesson['assignments'][0]['assignmentName']) except KeyError: pass except IndexError: result = 'На вчера домашнего задания нету!' elif user.logic == 'ball': ball = {} try: for lesson in diary['weekDays'][0]['lessons']: try: for assignment in lesson['assignments']: try: ball[lesson['subjectName']] += str( assignment['mark']['mark']) + ' ' except KeyError: ball[lesson['subjectName']] = str( assignment['mark']['mark']) + ' ' except Exception: pass result = 'Оценки за вчера:\n ' + str(ball).replace( '{', '').replace('}', '').replace(',', '\n').replace("'", '') except IndexError: result = 'На вчера оценок нету!' try: await bot.send_message(message.from_user.id, result) except Exception: await bot.send_message(message.from_user.id, 'Пусто')
async def _(message: types.CallbackQuery): await bot.answer_callback_query(message.id) user = user_dict[message.from_user.id] account = account_dict[user.account_id] result = '' async with NetSchoolAPI(account.url, account.login, account.password, (account.oblast, account.okrug, account.sity, account.type, account.school)) as api: diary = await api.get_diary() if user.logic == 'rasp': for day in diary['weekDays']: reg_ex = re.search('(.*)-(.*)-(.*)T00:00:00', day['date']) result += '\n\nДень: ' + reg_ex.group(2) + '-' + reg_ex.group(3) for lesson in day['lessons']: result += '\n' + str(lesson['number']) + '.' + str( lesson['subjectName']) + '(' + str( lesson['startTime']) + '-' + str( lesson['endTime']) + ')' elif user.logic == 'dz': for day in diary['weekDays']: reg_ex = re.search('(.*)-(.*)-(.*)T00:00:00', day['date']) result += '\n\nДень: ' + reg_ex.group(2) + '-' + reg_ex.group(3) for lesson in day['lessons']: try: result += '\n' + str(lesson['subjectName']) + ': ' + str( lesson['assignments'][0]['assignmentName']) except KeyError: pass elif user.logic == 'ball': ball = {} for day in diary['weekDays']: reg_ex = re.search('(.*)-(.*)-(.*)T00:00:00', day['date']) result += '\n\nДень: ' + reg_ex.group(2) + '-' + reg_ex.group(3) for lesson in day['lessons']: try: for assignment in lesson['assignments']: try: ball[lesson['subjectName']] += str( assignment['mark']['mark']) + ' ' except KeyError: ball[lesson['subjectName']] = str( assignment['mark']['mark']) + ' ' except Exception: pass result = 'Оценки за неделю:\n ' + str(ball).replace('{', '').replace( '}', '').replace(',', '\n').replace("'", '') try: await bot.send_message(message.from_user.id, result) except Exception: await bot.send_message(message.from_user.id, 'Пусто')
async def _(message: types.CallbackQuery): await bot.answer_callback_query(message.id) user = user_dict[message.from_user.id] account = account_dict[user.account_id] async with NetSchoolAPI(account.url, account.login, account.password, (account.oblast, account.okrug, account.sity, account.type, account.school)) as api: announcements = await api.get_announcements() result = 'Объявления:\n' for announcement in announcements: result += announcement['name'] + ':\n' + str( announcement['description']) + '\nЗапостили: ' + str( announcement['postDate']) + '\nУдален: ' + str( announcement['deleteDate']) + '\nАвтор: ' + str( announcement['author']['fio']) + '\n\n' cleantext = BeautifulSoup(result, "lxml").text await bot.send_message(message.from_user.id, cleantext, parse_mode='HTML')
async def dnevnik(msg: Message, ctx: Context): api = NetSchoolAPI("http://sgo.cit73.ru") q = Query() user = db.table("login_data").search(q.user_id == ctx.user_uid)[0] await api.login( user["login"].split(":")[0], user["login"].split(":")[1], user["school"], city=user["city"], oo=user["oo"], ) data = await api.get_diary() df = pd.DataFrame(data={}) await ctx.reply("Ваш класс: ") for day in data["weekDays"]: date = dateutil.parser.parse(day["date"]).weekday() for lesson in day["lessons"]: try: hw = lesson["assignments"][0]["assignmentName"] mark = lesson["assignments"][0]["mark"] except KeyError: hw = None mark = None subject = lesson["subjectName"] print(lesson["room"]) room = [int(s) for s in lesson["room"].split("/") if s.isdigit()][0] df = df.append( { "Date": date, "Homework": hw, "Subject": subject, "Mark": mark, "Room": room }, ignore_index=True) df = df.set_index("Date") for name, group in df.groupby("Date"): msg_ = "Уроки на {}\n".format(weektorus[name]) for row in group.iterrows(): data = row[1] msg_ += "{} / {} - {}\n".format(data["Subject"], int(data["Room"]), data["Homework"]) await ctx.reply(msg_)
class NetSchoolShell: URL = '' URL: str DATA = {} DATA: dict diary = () diary: Diary lastDateRequest = datetime.datetime.now() isLoginProcess = False isLoginProcess: bool def Init(self): try: self._NetSchoolShell__api = NetSchoolAPI(self.URL) except Exception as exception: try: print(exception) finally: exception = None del exception def UpdateLoginData(self) -> None: self.DATA = {} response = requests.get(self.URL + '/webapi/prepareloginform') d_data = response.json() for key in d_data.keys(): if type(d_data[key]) == list: for data in d_data[key]: if self.DATA.get(key): self.DATA[key].append( PrepareData(data['id'], data['name'])) else: self.DATA[key] = [ PrepareData(data['id'], data['name']) ] def GetStringListByKey(self, key) -> list: t_list = list() for i in self.DATA[key]: t_list.append(i.name) else: return t_list def Login(self, data: DataLogin): self.isLoginProcess = True try: trio.run(lambda: self._NetSchoolShell__api.login( login=(data.LOGIN), password=(data.PASSWORD), country=(data.COUNTRY), func=(data.FUNC), city=(data.CITY), state=(data.STATE), province=(data.PROVINCE), school=(data.SCHOOL))) except Exception as exception: try: print(exception) finally: exception = None del exception else: self.isLoginProcess = False def GetIsLogin(self) -> bool: return self._NetSchoolShell__api.logged_in def UpdateDiary(self) -> None: dictDiary = trio.run(lambda: self._NetSchoolShell__api.get_diary()) self.ParseDiary(self, dictDiary) def GetDiaryByDate(self, weekStart: datetime.datetime, weekEnd: datetime.datetime = None): dictDiary = trio.run( lambda: self._NetSchoolShell__api.get_diary(weekStart, weekEnd)) self.ParseDiary(self, dictDiary) def ParseDiary(self, dictDiary: dict): self.diary = Diary() self.diary.termName = dictDiary['termName'] self.diary.className = dictDiary['className'] for day in dictDiary['weekDays']: newDay = Day() newDay.date = day['date'] for lesson in day['lessons']: newLesson = Lesson() newLesson.classmeetingId = lesson['classmeetingId'] newLesson.day = lesson['day'] newLesson.number = lesson['number'] newLesson.room = lesson['room'] newLesson.endTime = lesson['endTime'] newLesson.startTime = lesson['startTime'] newLesson.subjectName = lesson['subjectName'] if lesson.get('assignments'): for assigment in lesson['assignments']: newAssigment = Assigment() newAssigment.id = assigment['id'] if assigment['mark'] != None: newAssigment.mark = assigment['mark']['mark'] newAssigment.typeId = assigment['typeId'] newAssigment.weight = assigment['weight'] newAssigment.assignmentName = assigment[ 'assignmentName'] newAssigment.classMeetingId = assigment[ 'classMeetingId'] newAssigment.dueDate = assigment['dueDate'] newLesson.assignments.append(newAssigment) else: newDay.lessons.append(newLesson) else: self.diary.weekDays.append(newDay) def Logout(self): trio.run(lambda: self._NetSchoolShell__api.logout())