Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save last positions #6

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions itmoapp/commands/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -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" \
# "Техподдержка [email protected]"

message = "Бот помогает абитуриенту отслеживать состояние поступления " \
"в Университет ИТМО.\n" \
"\n" \
"Техподдержка [email protected]"

Expand Down
113 changes: 97 additions & 16 deletions itmoapp/components/methods.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,32 @@
from . import ApiServer
import random


class Methods:

def __init__(self, sdk):
self.sdk = sdk

def check_rating_positions(self, student_id):
ratings = ApiServer().request('getUserPositions', {'id': student_id})
def check_rating_positions(self, payload):
"""
Check ratings positions update for target student

# todo get user positions from db
old_position = 19
:param string student_id:
:param payload:
:return list ratings:
"""
from models import Student

self.sdk.log("RATINGING: {}".format(ratings))
for idx, program in enumerate(ratings):
# Get Student's data from db
student = Student(self.sdk, payload, chat=payload['chat'])

# Send request to api server
ratings = ApiServer().request('getUserPositions', {'id': student.id})

# Prepare new ratings dictionary
new_ratings = {}

for program in ratings:
"""
{
'program': 'Прикладная и компьютерная оптика',
Expand All @@ -23,24 +36,92 @@ def check_rating_positions(self, student_id):
'value': 120
}
"""
program_id = program['id']

program['position_diff'] = 0

try:
# Get user's last position
last_position = student.programs[str(program_id)]['position']

program['position_diff'] = last_position - program['position']
except Exception as e:
pass

new_ratings[str(program_id)] = program

student.programs = new_ratings
student.save()

# todo compare positions with saved in db
program['position_diff'] = old_position - program['position']
return new_ratings

ratings[idx] = program
async def report_ratings(self, payload):
from queries import Query
from components import Utils

self.sdk.log("APROGRAM: {}".format(program))
ratings = self.check_rating_positions(payload)
self.sdk.log("API Server response for getUserPositions: {}".format(ratings))

self.sdk.log("RATINGING: {}".format(ratings))
# Prepare data
programs_data = []

return ratings
# Prepare text for each program
for program_id, program in ratings.items():
# Compose link
link = "http://abit.ifmo.ru/program/{}/".format(program_id)

async def loggy(self, payload):
self.sdk.log("Scheduled function loggy() with payload {}".format(payload))
message = "[daily report]"
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 = "<a href=\"{}\">{}</a>\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)
8 changes: 4 additions & 4 deletions itmoapp/components/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -51,8 +51,8 @@ def satisfaction_emoji(percentage):
emoji = {
"100": "😎",
"90": "😄",
"80": "😏",
"70": "🙂",
"80": "🙂",
"70": "😏",
"60": "😐",
"50": "🙁",
"40": "😒",
Expand Down
2 changes: 1 addition & 1 deletion itmoapp/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
12 changes: 6 additions & 6 deletions itmoapp/models/student.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -22,15 +23,16 @@ 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(
# Collection name
self.collection,

# Find params
{'chat_id': self.chat},
{'chat': self.chat},

# Data to be saved
data_to_save,
Expand All @@ -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})
Expand All @@ -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')
7 changes: 4 additions & 3 deletions itmoapp/states/ask_auth_correctness.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
[
Expand Down Expand Up @@ -64,17 +64,18 @@ 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
return await self.controller.goto(payload, "menu")

# If user answer "no"
message = "Попробуй авторизоваться еще раз."
message = "Попробуйте авторизоваться еще раз."

await self.sdk.send_text_to_chat(
payload["chat"],
Expand Down
2 changes: 1 addition & 1 deletion itmoapp/states/ask_scores.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class StateAskScores(Base):

async def before(self, payload, data):
message = "Пришли мне список своих баллов в формате:\n" \
message = "Пришлите мне список своих баллов в формате:\n" \
"\n" \
"Математика 80\n" \
"Русский язык 78\n" \
Expand Down
4 changes: 2 additions & 2 deletions itmoapp/states/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
class StateAuth(Base):

async def before(self, payload, data):
message = "Введи номер заявления"
message = "Введите номер заявления"

await self.sdk.send_text_to_chat(
payload["chat"],
Expand All @@ -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"],
Expand Down
23 changes: 17 additions & 6 deletions itmoapp/states/calc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
class StateCalc(Base):

async def before(self, payload, data):
message = "Минутку."
message = "Минутку"

await self.sdk.send_text_to_chat(
payload["chat"],
Expand All @@ -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"],
Expand All @@ -46,23 +46,34 @@ 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)
chance = min(int(float(program['value']) / float(program['possible_place']) * 100), 100)

program_message = "<a href=\"{}\">{}</a>\n".format(link, program['name']) + \
"Проходной балл: {}\n".format(program['score']) + \
"Ваше заявление было бы {} из {}\n".format(
program['possible_place'],
program['requests']
) + \
"{}\n".format(
program_value
) + \
"Вероятность поступления: {}% {}\n".format(chance, Utils.satisfaction_emoji(chance)) + \
"Твое заявление было бы {} из {} в рейтинге на {}\n".format(program['possible_place'], program['requests'], program_value) + \
"\n"

programs_data.append(program_message)

# 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"],
Expand Down
25 changes: 12 additions & 13 deletions itmoapp/states/greeting.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, state_controller):
}

async def before(self, payload, data):
message = "Ты уже подал заявление?"
message = "Вы уже подали заявление?"

buttons = [
[
Expand All @@ -45,25 +45,24 @@ 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']

if text in self.response_phrases['yes']:
# 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 = 'Не понимаю'

Expand Down
Loading