From ef9e0f37dc1d4e690088a33ae51c2b9a1f63fd6d Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:06:24 +0300 Subject: [PATCH 01/11] Simplify chained comparison --- itmoapp/components/utils.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/itmoapp/components/utils.py b/itmoapp/components/utils.py index 6762b22..c80e4ca 100644 --- a/itmoapp/components/utils.py +++ b/itmoapp/components/utils.py @@ -18,10 +18,10 @@ def endings(count, form1, form2, form5): n = count % 100 n1 = count % 10 - if n > 10 and n < 20: + if 10 < n < 20: return form5 - if n1 > 1 and n1 < 5: + if 1 < n1 < 5: return form2 if n1 == 1: From 69fcd51f4ac3a9c91170027f7a7ae394cdfd6368 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:06:59 +0300 Subject: [PATCH 02/11] improvements --- itmoapp/states/settings.py | 41 -------------------------------------- itmoapp/states/start.py | 2 +- 2 files changed, 1 insertion(+), 42 deletions(-) diff --git a/itmoapp/states/settings.py b/itmoapp/states/settings.py index 4c11fa4..c542be8 100644 --- a/itmoapp/states/settings.py +++ b/itmoapp/states/settings.py @@ -20,47 +20,6 @@ async def before(self, payload, data): async def process(self, payload, data): # todo - # message = "Я подобрал несколько направлений, куда у тебя есть возможность поступить.\n" \ - # "Для возврата в меню нажми /itmo_start." - # - # await self.sdk.send_text_to_chat( - # payload["chat"], - # message - # ) - # - # # Prepare data - # programs_data = [] - # - # # Prepate text for each program - # for program in data: - # # Compose link - # link = "http://abit.ifmo.ru/program/{}/".format(program['id']) - # - # program_requests = "{} {}".format( - # program['requests'], - # Utils.endings(int(program['requests']), "заявление", "заявления", "заявлений") - # ) - # - # program_value = "{} {}".format( - # program['value'], - # Utils.endings(int(program['value']), "место", "места", "мест") - # ) - # - # program_message = "{}\n" \ - # "Проходной балл: {}\n" \ - # "{} на {}\n" \ - # "\n".format( - # link, - # program['name'], - # program['score'], - # program_requests, - # program_value - # ) - # - # programs_data.append(program_message) - # - # # Send message with buttons - # await self.queries.create(payload, programs_data, 'pagination') # Go to start await self.controller.goto(payload, "menu") diff --git a/itmoapp/states/start.py b/itmoapp/states/start.py index a32d6de..d351733 100644 --- a/itmoapp/states/start.py +++ b/itmoapp/states/start.py @@ -17,7 +17,7 @@ async def process(self, payload, data): return await self.controller.goto(payload, 'menu') # User is not authorized - message = "Привет. Я буду держать тебя в курсе твоего состояния поступления в ИТМО." + message = "Привет. Я буду держать в курсе твоего состояния поступления в ИТМО." await self.sdk.send_text_to_chat( payload["chat"], From f1cf1384e46ec8381d67e7642ff4dea273c6b494 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:07:44 +0300 Subject: [PATCH 03/11] fix "find" params --- itmoapp/models/student.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/itmoapp/models/student.py b/itmoapp/models/student.py index 36c3aeb..a83d740 100644 --- a/itmoapp/models/student.py +++ b/itmoapp/models/student.py @@ -30,7 +30,7 @@ def save(self): self.collection, # Find params - {'chat_id': self.chat}, + {'chat': self.chat}, # Data to be saved data_to_save, From 4a90395789649b2b1b990f0e87cd8369771abda1 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:08:05 +0300 Subject: [PATCH 04/11] add field programs --- itmoapp/models/student.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/itmoapp/models/student.py b/itmoapp/models/student.py index a83d740..4c7b29f 100644 --- a/itmoapp/models/student.py +++ b/itmoapp/models/student.py @@ -10,6 +10,7 @@ def __init__(self, sdk, payload, data=None, chat=None): self.id = None self.name = None self.scores = None + self.programs = None self.collection = Utils.create_collection_name(STUDENTS_COLLECTION_NAME, payload) if chat is not None: @@ -22,7 +23,8 @@ def save(self): 'chat': self.chat, 'id': self.id, 'name': self.name, - 'scores': self.scores + 'scores': self.scores, + 'programs': self.programs } self.sdk.db.update( @@ -52,7 +54,7 @@ def __get(self, chat): """ Get user data from db - :param string chat: + :param string chat: chat_hash from payload :return: """ result = self.sdk.db.find_one(self.collection, {'chat': chat}) @@ -67,6 +69,4 @@ def __fill_model(self, data): self.id = data.get('id') self.name = data.get('name') self.scores = data.get('scores') - - # def get_positions(self): - # pass + self.programs = data.get('programs') From 9a19a2f41c97d174361edb1574168518972732bd Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:08:34 +0300 Subject: [PATCH 05/11] add payload params --- itmoapp/components/methods.py | 23 ++++++++++++++++++++--- itmoapp/states/ratings.py | 2 +- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/itmoapp/components/methods.py b/itmoapp/components/methods.py index 61b68c2..8de9493 100644 --- a/itmoapp/components/methods.py +++ b/itmoapp/components/methods.py @@ -6,13 +6,25 @@ class Methods: def __init__(self, sdk): self.sdk = sdk - def check_rating_positions(self, student_id): + def check_rating_positions(self, student_id, payload): + """ + Check ratings positions update for target student + + :param string student_id: + :param payload: + :return list ratings: + """ + from models import Student + + # Get Student + student = Student(self.sdk, payload, chat=payload['chat']) + + # if student.programs: + ratings = ApiServer().request('getUserPositions', {'id': student_id}) - # todo get user positions from db old_position = 19 - self.sdk.log("RATINGING: {}".format(ratings)) for idx, program in enumerate(ratings): """ { @@ -33,6 +45,11 @@ def check_rating_positions(self, student_id): self.sdk.log("RATINGING: {}".format(ratings)) + # todo update user's saved programs + + student.programs = ratings + student.save() + return ratings async def loggy(self, payload): diff --git a/itmoapp/states/ratings.py b/itmoapp/states/ratings.py index f39c386..cf2a42a 100644 --- a/itmoapp/states/ratings.py +++ b/itmoapp/states/ratings.py @@ -20,7 +20,7 @@ async def before(self, payload, data): async def process(self, payload, data): student = Student(self.sdk, payload, chat=payload['chat']) - ratings = Methods(self.sdk).check_rating_positions(student.id) + ratings = Methods(self.sdk).check_rating_positions(student.id, payload) self.sdk.log("API Server response for getUserPositions: {}".format(ratings)) message = "Список направлений, куда ты подал документы на поступление" From e52228290df112b340f67630d196725d45a3c539 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 09:57:17 +0300 Subject: [PATCH 06/11] update ids --- sample-api-server/app/routes.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sample-api-server/app/routes.js b/sample-api-server/app/routes.js index 3355194..29e0c1b 100644 --- a/sample-api-server/app/routes.js +++ b/sample-api-server/app/routes.js @@ -101,14 +101,14 @@ const getUserPositions = (req, res) => { }, { "program": "Световая инженерия", - "id": 10555, + "id": 10556, "position": 88, "users": 430, "value": 25 }, { "program": "Интеллектуальная робототехника", - "id": 10555, + "id": 10557, "position": 17, "users": 125, "value": 56 From 91bcf9078d2132baef1c11887531e5c6353afc3d Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 10:12:22 +0300 Subject: [PATCH 07/11] save ratins positions to db --- itmoapp/components/methods.py | 34 +++++++++++++++++---------------- itmoapp/states/ratings.py | 23 ++++++++-------------- sample-api-server/app/routes.js | 6 +++--- 3 files changed, 29 insertions(+), 34 deletions(-) diff --git a/itmoapp/components/methods.py b/itmoapp/components/methods.py index 8de9493..ac07701 100644 --- a/itmoapp/components/methods.py +++ b/itmoapp/components/methods.py @@ -6,7 +6,7 @@ class Methods: def __init__(self, sdk): self.sdk = sdk - def check_rating_positions(self, student_id, payload): + def check_rating_positions(self, payload): """ Check ratings positions update for target student @@ -16,16 +16,16 @@ def check_rating_positions(self, student_id, payload): """ from models import Student - # Get Student + # Get Student's data from db student = Student(self.sdk, payload, chat=payload['chat']) - # if student.programs: + # Send request to api server + ratings = ApiServer().request('getUserPositions', {'id': student.id}) - ratings = ApiServer().request('getUserPositions', {'id': student_id}) + # Prepare new ratings dictionary + new_ratings = {} - old_position = 19 - - for idx, program in enumerate(ratings): + for program in ratings: """ { 'program': 'Прикладная и компьютерная оптика', @@ -35,22 +35,24 @@ def check_rating_positions(self, student_id, payload): 'value': 120 } """ + program_id = program['id'] - # todo compare positions with saved in db - program['position_diff'] = old_position - program['position'] - - ratings[idx] = program + program['position_diff'] = 0 - self.sdk.log("APROGRAM: {}".format(program)) + try: + # Get user's last position + last_position = student.programs[str(program_id)]['position'] - self.sdk.log("RATINGING: {}".format(ratings)) + program['position_diff'] = last_position - program['position'] + except Exception as e: + pass - # todo update user's saved programs + new_ratings[str(program_id)] = program - student.programs = ratings + student.programs = new_ratings student.save() - return ratings + return new_ratings async def loggy(self, payload): self.sdk.log("Scheduled function loggy() with payload {}".format(payload)) diff --git a/itmoapp/states/ratings.py b/itmoapp/states/ratings.py index cf2a42a..0c41fe5 100644 --- a/itmoapp/states/ratings.py +++ b/itmoapp/states/ratings.py @@ -1,6 +1,5 @@ from .base import Base -from components import ApiServer, Methods, Utils -from models import Student +from components import Methods, Utils class StateRatings(Base): @@ -18,10 +17,6 @@ async def before(self, payload, data): await self.controller.process(payload, data) async def process(self, payload, data): - student = Student(self.sdk, payload, chat=payload['chat']) - - ratings = Methods(self.sdk).check_rating_positions(student.id, payload) - self.sdk.log("API Server response for getUserPositions: {}".format(ratings)) message = "Список направлений, куда ты подал документы на поступление" @@ -31,18 +26,16 @@ async def process(self, payload, data): bot=payload.get('bot', None) ) + ratings = Methods(self.sdk).check_rating_positions(payload) + self.sdk.log("API Server response for getUserPositions: {}".format(ratings)) + # Prepare data programs_data = [] # Prepare text for each program - for program in ratings: + for program_id, program in ratings.items(): # Compose link - link = "http://abit.ifmo.ru/program/{}/".format(program['id']) - - # program_requests = "{} {}".format( - # program['users'], - # Utils.endings(int(program['users']), "заявление", "заявления", "заявлений") - # ) + link = "http://abit.ifmo.ru/program/{}/".format(program_id) program_value = "{} {}".format( program['value'], @@ -54,9 +47,9 @@ async def process(self, payload, data): if program['position_diff'] > 0: diff = "+{} 👍".format(program['position_diff']) elif program['position_diff'] < 0: - diff = "{} 🔻".format(program['position_diff']) + diff = "{} 👎".format(program['position_diff']) else: - diff = "0 🔸" + diff = "+0" program_message = "{}\n".format(link, program['program']) + \ "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ diff --git a/sample-api-server/app/routes.js b/sample-api-server/app/routes.js index 29e0c1b..c87e7ad 100644 --- a/sample-api-server/app/routes.js +++ b/sample-api-server/app/routes.js @@ -95,21 +95,21 @@ const getUserPositions = (req, res) => { { "program": "Прикладная и компьютерная оптика", "id": 10555, - "position": 13, + "position": random(67), "users": 67, "value": 120 }, { "program": "Световая инженерия", "id": 10556, - "position": 88, + "position": random(430), "users": 430, "value": 25 }, { "program": "Интеллектуальная робототехника", "id": 10557, - "position": 17, + "position": random(125), "users": 125, "value": 56 } From c2299f10b705469654a0b21f8edb4e823e6e3b20 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 11:37:41 +0300 Subject: [PATCH 08/11] improvements --- itmoapp/commands/help.py | 9 +++++++-- itmoapp/components/utils.py | 4 ++-- itmoapp/states/ask_auth_correctness.py | 4 ++-- itmoapp/states/ask_scores.py | 2 +- itmoapp/states/auth.py | 4 ++-- itmoapp/states/calc.py | 21 ++++++++++++++++----- itmoapp/states/greeting.py | 25 ++++++++++++------------- itmoapp/states/menu.py | 6 +++--- itmoapp/states/ratings.py | 24 +++++++++++++++++------- itmoapp/states/start.py | 2 +- sample-api-server/app/routes.js | 9 +++++---- 11 files changed, 68 insertions(+), 42 deletions(-) diff --git a/itmoapp/commands/help.py b/itmoapp/commands/help.py index ba7c490..75f54ef 100644 --- a/itmoapp/commands/help.py +++ b/itmoapp/commands/help.py @@ -6,8 +6,13 @@ class CommandHelp(CommandBase): async def __call__(self, payload): self.sdk.log("/itmo_help handler fired with payload {}".format(payload)) - message = "Этот бот помогает абитуриенту отслеживать состояние поступления " \ - "в Университет ИТМО и подбирать направления по результатам ЕГЭ.\n" \ + # message = "Бот помогает абитуриенту отслеживать состояние поступления " \ + # "в Университет ИТМО и подбирать направления по результатам ЕГЭ.\n" \ + # "\n" \ + # "Техподдержка team@ifmo.su" + + message = "Бот помогает абитуриенту отслеживать состояние поступления " \ + "в Университет ИТМО.\n" \ "\n" \ "Техподдержка team@ifmo.su" diff --git a/itmoapp/components/utils.py b/itmoapp/components/utils.py index c80e4ca..56b1e61 100644 --- a/itmoapp/components/utils.py +++ b/itmoapp/components/utils.py @@ -51,8 +51,8 @@ def satisfaction_emoji(percentage): emoji = { "100": "😎", "90": "😄", - "80": "😏", - "70": "🙂", + "80": "🙂", + "70": "😏", "60": "😐", "50": "🙁", "40": "😒", diff --git a/itmoapp/states/ask_auth_correctness.py b/itmoapp/states/ask_auth_correctness.py index f3a2c27..4c115ab 100644 --- a/itmoapp/states/ask_auth_correctness.py +++ b/itmoapp/states/ask_auth_correctness.py @@ -25,7 +25,7 @@ async def before(self, payload, data): # Go back to auth state return await self.controller.goto(payload, "auth") - message = "Тебя зовут {}?".format(user_name) + message = "Вас зовут {}?".format(user_name) buttons = [ [ @@ -74,7 +74,7 @@ async def process(self, payload, data): return await self.controller.goto(payload, "menu") # If user answer "no" - message = "Попробуй авторизоваться еще раз." + message = "Попробуйте авторизоваться еще раз." await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/ask_scores.py b/itmoapp/states/ask_scores.py index 3c439fd..e201b98 100644 --- a/itmoapp/states/ask_scores.py +++ b/itmoapp/states/ask_scores.py @@ -4,7 +4,7 @@ class StateAskScores(Base): async def before(self, payload, data): - message = "Пришли мне список своих баллов в формате:\n" \ + message = "Пришлите мне список своих баллов в формате:\n" \ "\n" \ "Математика 80\n" \ "Русский язык 78\n" \ diff --git a/itmoapp/states/auth.py b/itmoapp/states/auth.py index b77e021..90b3a02 100644 --- a/itmoapp/states/auth.py +++ b/itmoapp/states/auth.py @@ -5,7 +5,7 @@ class StateAuth(Base): async def before(self, payload, data): - message = "Введи номер заявления" + message = "Введите номер заявления" await self.sdk.send_text_to_chat( payload["chat"], @@ -23,7 +23,7 @@ async def process(self, payload, data): try: user_id = int(user_id) except Exception as e: - message = "Номер состоит только из цифры" + message = "Номер должен состоять только из цифр" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/calc.py b/itmoapp/states/calc.py index cfcfb56..61f2e97 100644 --- a/itmoapp/states/calc.py +++ b/itmoapp/states/calc.py @@ -6,7 +6,7 @@ class StateCalc(Base): async def before(self, payload, data): - message = "Минутку." + message = "Минутку" await self.sdk.send_text_to_chat( payload["chat"], @@ -23,7 +23,7 @@ async def before(self, payload, data): await self.controller.process(payload, programs) async def process(self, payload, data): - message = "Я подобрал несколько направлений, куда у тебя есть возможность поступить." + message = "Я подобрал несколько направлений, куда у вас есть возможность поступить." await self.sdk.send_text_to_chat( payload["chat"], @@ -46,7 +46,12 @@ async def process(self, payload, data): program_value = "{} {}".format( program['value'], - Utils.endings(int(program['value']), "место", "места", "мест") + Utils.endings( + int(program['value']), + "бюджетное место", + "бюджетных места", + "бюджетных мест" + ) ) chance = int(float(program['value']) / float(program['possible_place']) * 100) @@ -54,7 +59,13 @@ async def process(self, payload, data): program_message = "{}\n".format(link, program['name']) + \ "Проходной балл: {}\n".format(program['score']) + \ "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ - "Твое заявление было бы {} из {} в рейтинге на {}\n".format(program['possible_place'], program['requests'], program_value) + \ + "Ваше заявление было бы {} из {}\n".format( + program['possible_place'], + program['requests'] + ) + \ + "{}\n".format( + program_value + ) + \ "\n" programs_data.append(program_message) @@ -62,7 +73,7 @@ async def process(self, payload, data): # Send message with buttons await self.queries.create(payload, programs_data, 'pagination') - message = "Для возврата в меню нажми /itmo_start." + message = "Нажмите /itmo_start для возврата в меню" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/greeting.py b/itmoapp/states/greeting.py index dd774ed..aa7ddc0 100644 --- a/itmoapp/states/greeting.py +++ b/itmoapp/states/greeting.py @@ -19,7 +19,7 @@ def __init__(self, state_controller): } async def before(self, payload, data): - message = "Ты уже подал заявление?" + message = "Вы уже подали заявление?" buttons = [ [ @@ -45,7 +45,6 @@ async def before(self, payload, data): async def process(self, payload, data): self.sdk.log("State Greeting processor fired with payload {}".format(payload)) - # TODO remove keyboard text = payload['text'] @@ -53,17 +52,17 @@ async def process(self, payload, data): # Go to auth return await self.controller.goto(payload, 'auth') - elif text in self.response_phrases['no']: - message = 'Я могу помочь подобрать направления по твоим результатам ЕГЭ.' - - await self.sdk.send_text_to_chat( - payload["chat"], - message, - bot=payload.get('bot', None) - ) - - # Ask scores - return await self.controller.goto(payload, 'ask_scores') + # elif text in self.response_phrases['no']: + # message = 'Я могу помочь подобрать направления по вашим результатам ЕГЭ.' + # + # await self.sdk.send_text_to_chat( + # payload["chat"], + # message, + # bot=payload.get('bot', None) + # ) + # + # # Ask scores + # return await self.controller.goto(payload, 'ask_scores') message = 'Не понимаю' diff --git a/itmoapp/states/menu.py b/itmoapp/states/menu.py index 964952a..2ba8d94 100644 --- a/itmoapp/states/menu.py +++ b/itmoapp/states/menu.py @@ -12,7 +12,7 @@ def __init__(self, state_controller): self.response_phrases = { "ratings": [ - "Мои позиции в рейтингах" + "Мои вступительные испытания" ], "EGE_calc": [ @@ -29,7 +29,7 @@ def __init__(self, state_controller): } async def before(self, payload, data): - message = "Что тебя интересует?" + message = "Что вас интересует?" buttons = [ [ @@ -87,7 +87,7 @@ async def process(self, payload, data): self.sdk.scheduler.remove(payload) # Send message - message = "Если понадоблюсь, выполни команду /itmo_start." + message = "Если понадоблюсь, нажмите /itmo_start" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/ratings.py b/itmoapp/states/ratings.py index 0c41fe5..6d392c2 100644 --- a/itmoapp/states/ratings.py +++ b/itmoapp/states/ratings.py @@ -5,7 +5,7 @@ class StateRatings(Base): async def before(self, payload, data): - message = "Минутку." + message = "Минутку" await self.sdk.send_text_to_chat( payload["chat"], @@ -18,7 +18,7 @@ async def before(self, payload, data): async def process(self, payload, data): - message = "Список направлений, куда ты подал документы на поступление" + message = "Список направлений, куда вы подали документы на поступление" await self.sdk.send_text_to_chat( payload["chat"], @@ -39,7 +39,12 @@ async def process(self, payload, data): program_value = "{} {}".format( program['value'], - Utils.endings(int(program['value']), "место", "места", "мест") + Utils.endings( + int(program['value']), + "бюджетное место", + "бюджетных места", + "бюджетных мест" + ) ) chance = int(float(program['value']) / float(program['position']) * 100) @@ -47,13 +52,18 @@ async def process(self, payload, data): if program['position_diff'] > 0: diff = "+{} 👍".format(program['position_diff']) elif program['position_diff'] < 0: - diff = "{} 👎".format(program['position_diff']) + diff = "{} 🔻".format(program['position_diff']) else: - diff = "+0" + diff = None program_message = "{}\n".format(link, program['program']) + \ "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ - "Твое заявление {} ({}) из {} в рейтинге на {}\n".format(program['position'], diff, program['users'], program_value) + \ + "Ваше заявление {}{} из {}.\n".format( + program['position'], + " ({})".format(diff) if diff else "", + program['users'] + ) + \ + "{}\n".format(program_value) + \ "\n" programs_data.append(program_message) @@ -61,7 +71,7 @@ async def process(self, payload, data): # Send message with buttons await self.queries.create(payload, programs_data, 'pagination') - message = "Для возврата в меню нажми /itmo_start." + message = "Нажмите /itmo_start для возврата в меню" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/start.py b/itmoapp/states/start.py index d351733..50771e8 100644 --- a/itmoapp/states/start.py +++ b/itmoapp/states/start.py @@ -17,7 +17,7 @@ async def process(self, payload, data): return await self.controller.goto(payload, 'menu') # User is not authorized - message = "Привет. Я буду держать в курсе твоего состояния поступления в ИТМО." + message = "Привет. Я буду держать вас в курсе статуса ваших вступительных заявлений." await self.sdk.send_text_to_chat( payload["chat"], diff --git a/sample-api-server/app/routes.js b/sample-api-server/app/routes.js index c87e7ad..b1cfeed 100644 --- a/sample-api-server/app/routes.js +++ b/sample-api-server/app/routes.js @@ -95,21 +95,21 @@ const getUserPositions = (req, res) => { { "program": "Прикладная и компьютерная оптика", "id": 10555, - "position": random(67), + "position": random(1, 67), "users": 67, "value": 120 }, { "program": "Световая инженерия", "id": 10556, - "position": random(430), + "position": random(1, 430), "users": 430, "value": 25 }, { "program": "Интеллектуальная робототехника", "id": 10557, - "position": random(125), + "position": random(1, 125), "users": 125, "value": 56 } @@ -208,7 +208,8 @@ const getProgramsByScores = (req, res) => { programs = []; for (let i = 0; i < 64; i++) { - let name = Math.random().toString(36).replace(/w+/g, '').substr(0, 25), + // let name = Math.random().toString(36).replace(/w+/g, '').substr(0, 25), + let name = "Название направления №" + i + "", id = random(10500, 10600), score = random(180, 310), requests = random(10, 400), From afef74f4ba2bb06be30dbecce2db383275de873a Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 13:44:26 +0300 Subject: [PATCH 09/11] update text --- itmoapp/states/menu.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/itmoapp/states/menu.py b/itmoapp/states/menu.py index 2ba8d94..3e72e96 100644 --- a/itmoapp/states/menu.py +++ b/itmoapp/states/menu.py @@ -12,7 +12,7 @@ def __init__(self, state_controller): self.response_phrases = { "ratings": [ - "Мои вступительные испытания" + "Мои вступительные заявления" ], "EGE_calc": [ From d01bda0b3508df9d10180b97a4e163e86d32b097 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 13:46:34 +0300 Subject: [PATCH 10/11] update text --- itmoapp/states/ratings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/itmoapp/states/ratings.py b/itmoapp/states/ratings.py index 6d392c2..2466e77 100644 --- a/itmoapp/states/ratings.py +++ b/itmoapp/states/ratings.py @@ -18,7 +18,7 @@ async def before(self, payload, data): async def process(self, payload, data): - message = "Список направлений, куда вы подали документы на поступление" + message = "Направления, на которые вы подали документы." await self.sdk.send_text_to_chat( payload["chat"], From cdd2dc6d7f2af9cf88243e349f295baa92ec8ed3 Mon Sep 17 00:00:00 2001 From: Taly Date: Thu, 5 Jul 2018 15:17:25 +0300 Subject: [PATCH 11/11] Evening digest --- itmoapp/components/methods.py | 70 ++++++++++++++++++++++++-- itmoapp/main.py | 2 +- itmoapp/states/ask_auth_correctness.py | 3 +- itmoapp/states/calc.py | 4 +- itmoapp/states/menu.py | 2 +- itmoapp/states/ratings.py | 45 +---------------- itmoapp/states/start.py | 2 +- 7 files changed, 74 insertions(+), 54 deletions(-) diff --git a/itmoapp/components/methods.py b/itmoapp/components/methods.py index ac07701..36ec9a1 100644 --- a/itmoapp/components/methods.py +++ b/itmoapp/components/methods.py @@ -1,4 +1,5 @@ from . import ApiServer +import random class Methods: @@ -54,12 +55,73 @@ def check_rating_positions(self, payload): return new_ratings - async def loggy(self, payload): - self.sdk.log("Scheduled function loggy() with payload {}".format(payload)) - message = "[daily report]" + async def report_ratings(self, payload): + from queries import Query + from components import Utils + + ratings = self.check_rating_positions(payload) + self.sdk.log("API Server response for getUserPositions: {}".format(ratings)) + + # Prepare data + programs_data = [] + + # Prepare text for each program + for program_id, program in ratings.items(): + # Compose link + link = "http://abit.ifmo.ru/program/{}/".format(program_id) + + program_value = "{} {}".format( + program['value'], + Utils.endings( + int(program['value']), + "бюджетное место", + "бюджетных места", + "бюджетных мест" + ) + ) + + chance = min(int(float(program['value']) / float(program['position']) * 100), 100) + + if program['position_diff'] > 0: + diff = "+{} ⬆️️".format(program['position_diff']) + elif program['position_diff'] < 0: + diff = "{} 🔻".format(program['position_diff']) + else: + diff = None + + program_message = "{}\n".format(link, program['program']) + \ + "Ваше заявление {} из {}{}.\n".format( + program['position'], + program['users'], + " ({})".format(diff) if diff else "" + ) + \ + "{}\n".format(program_value) + \ + "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ + "\n" + + programs_data.append(program_message) + + # Send message with buttons + await Query(self.sdk).create(payload, programs_data, 'pagination') + + async def evening_digest(self, payload): + self.sdk.log("Run scheduled function evening_digest() with payload {}".format(payload)) + + messages = [ + "Вечерний дайджест.", + "Пришло время для вечернего дайджеста.", + "Привет. Вот статус ваших заявлений на сегодняшний день.", + "Информация о поданных заявлениях к этому часу.", + "Добрейшего вечерочка. Так обстоят дела с вашими заявлениями:", + "Самое время узнать, как обстоят дела с вашими заявлениями.", + "По итогам дня ваши заявления имеют такие позиции.", + "Привет. Посмотрим, что с вашими позициями." + ] await self.sdk.send_text_to_chat( payload["chat"], - message, + random.choice(messages), bot=payload.get('bot', None) ) + + await self.report_ratings(payload) diff --git a/itmoapp/main.py b/itmoapp/main.py index 38ade93..79b4b9e 100644 --- a/itmoapp/main.py +++ b/itmoapp/main.py @@ -44,7 +44,7 @@ def __init__(self): self.sdk.set_callback_query_handler(self.process_callback_query) # Restore jobs in scheduler - self.sdk.scheduler.restore(Methods(self.sdk).loggy) + self.sdk.scheduler.restore(Methods(self.sdk).evening_digest) # Set up and run webserver self.webserver = Webserver(self.sdk) diff --git a/itmoapp/states/ask_auth_correctness.py b/itmoapp/states/ask_auth_correctness.py index 4c115ab..84c6f44 100644 --- a/itmoapp/states/ask_auth_correctness.py +++ b/itmoapp/states/ask_auth_correctness.py @@ -64,10 +64,11 @@ async def process(self, payload, data): # Add checking for User's positions in ratings self.sdk.log("Scheduler for {}:{} was added".format(payload['bot'], payload['chat'])) self.sdk.scheduler.add( - Methods(self.sdk).loggy, + Methods(self.sdk).evening_digest, payload, args=[payload], trigger_params={'hour': '21'} + # trigger_params={'minute': '*/1'} ) # Go to menu diff --git a/itmoapp/states/calc.py b/itmoapp/states/calc.py index 61f2e97..b5a17e4 100644 --- a/itmoapp/states/calc.py +++ b/itmoapp/states/calc.py @@ -54,11 +54,10 @@ async def process(self, payload, data): ) ) - chance = int(float(program['value']) / float(program['possible_place']) * 100) + chance = min(int(float(program['value']) / float(program['possible_place']) * 100), 100) program_message = "{}\n".format(link, program['name']) + \ "Проходной балл: {}\n".format(program['score']) + \ - "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ "Ваше заявление было бы {} из {}\n".format( program['possible_place'], program['requests'] @@ -66,6 +65,7 @@ async def process(self, payload, data): "{}\n".format( program_value ) + \ + "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ "\n" programs_data.append(program_message) diff --git a/itmoapp/states/menu.py b/itmoapp/states/menu.py index 3e72e96..1e0b457 100644 --- a/itmoapp/states/menu.py +++ b/itmoapp/states/menu.py @@ -87,7 +87,7 @@ async def process(self, payload, data): self.sdk.scheduler.remove(payload) # Send message - message = "Если понадоблюсь, нажмите /itmo_start" + message = "Если понадоблюсь, выполните /itmo_start" await self.sdk.send_text_to_chat( payload["chat"], diff --git a/itmoapp/states/ratings.py b/itmoapp/states/ratings.py index 2466e77..f4f5dea 100644 --- a/itmoapp/states/ratings.py +++ b/itmoapp/states/ratings.py @@ -26,50 +26,7 @@ async def process(self, payload, data): bot=payload.get('bot', None) ) - ratings = Methods(self.sdk).check_rating_positions(payload) - self.sdk.log("API Server response for getUserPositions: {}".format(ratings)) - - # Prepare data - programs_data = [] - - # Prepare text for each program - for program_id, program in ratings.items(): - # Compose link - link = "http://abit.ifmo.ru/program/{}/".format(program_id) - - program_value = "{} {}".format( - program['value'], - Utils.endings( - int(program['value']), - "бюджетное место", - "бюджетных места", - "бюджетных мест" - ) - ) - - chance = int(float(program['value']) / float(program['position']) * 100) - - if program['position_diff'] > 0: - diff = "+{} 👍".format(program['position_diff']) - elif program['position_diff'] < 0: - diff = "{} 🔻".format(program['position_diff']) - else: - diff = None - - program_message = "{}\n".format(link, program['program']) + \ - "Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \ - "Ваше заявление {}{} из {}.\n".format( - program['position'], - " ({})".format(diff) if diff else "", - program['users'] - ) + \ - "{}\n".format(program_value) + \ - "\n" - - programs_data.append(program_message) - - # Send message with buttons - await self.queries.create(payload, programs_data, 'pagination') + await Methods(self.sdk).report_ratings(payload) message = "Нажмите /itmo_start для возврата в меню" diff --git a/itmoapp/states/start.py b/itmoapp/states/start.py index 50771e8..e1c57ee 100644 --- a/itmoapp/states/start.py +++ b/itmoapp/states/start.py @@ -17,7 +17,7 @@ async def process(self, payload, data): return await self.controller.goto(payload, 'menu') # User is not authorized - message = "Привет. Я буду держать вас в курсе статуса ваших вступительных заявлений." + message = "Привет. Я расскажу про статус ваших вступительных заявлений." await self.sdk.send_text_to_chat( payload["chat"],