-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
167 lines (122 loc) · 5.18 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import logging
import os
import json
import random
import datetime
from aiogram import Bot, Dispatcher, types
# Logger initialization and logging level setting
log = logging.getLogger(__name__)
log.setLevel(os.environ.get('LOGGING_LEVEL', 'INFO').upper())
# Handlers
async def start(message: types.Message):
await message.answer('Привет, {}!'.format(message.from_user.first_name))
keyboard_markup = types.ReplyKeyboardMarkup(row_width=1, resize_keyboard=True, one_time_keyboard=True)
btns_text = ('Хоккейную!', 'Беговую!')
keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text))
await message.reply("Какую тренировку показать?", reply_markup=keyboard_markup)
async def hockey_train(message: types.Message):
workout_msg = build_workout()
await message.reply(workout_msg)
async def running_train(message: types.Message):
running_msg = build_running()
await message.reply(running_msg)
# keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
# text_and_data = (
# ('1-ю!', 'first'),
# ('2-ю!', 'second'),
# )
# in real life for the callback_data the callback data factory should be used
# here the raw string is used for the simplicity
# row_btns = (types.InlineKeyboardButton(text, callback_data=data) for text, data in text_and_data)
# keyboard_markup.row(*row_btns)
# await message.reply("Какую неделю из 12 недельного плана подготовки вывести?", reply_markup=keyboard_markup)
# Functions for Yandex.Cloud
async def register_handlers(dp: Dispatcher):
"""Registration all handlers before processing update."""
dp.register_message_handler(start, commands=['start'])
dp.register_message_handler(hockey_train, text='Хоккейную!')
dp.register_message_handler(running_train, text='Беговую!')
log.debug('Handlers are registered.')
async def process_event(event, dp: Dispatcher):
"""
Converting an Yandex.Cloud functions event to an update and
handling tha update.
"""
update = json.loads(event['body'])
log.debug('Update: ' + str(update))
Bot.set_current(dp.bot)
update = types.Update.to_object(update)
await dp.process_update(update)
async def handler(event, context):
"""Yandex.Cloud functions handler."""
if event['httpMethod'] == 'POST':
# Bot and dispatcher initialization
bot = Bot(os.environ.get('TELEGRAM_TOKEN'))
dp = Dispatcher(bot)
await register_handlers(dp)
await process_event(event, dp)
return {'statusCode': 200, 'body': 'ok'}
return {'statusCode': 405}
# Hockey functions
def build_workout():
"""
Builds the workout for the day.
:return: A string representation of the workout.
"""
"""
TO DO:
Change exercises for format{"value": "Разминка в стиле мистера Бина", "link": "https://ya.ru", "set": "10x3"},
"""
with open("data/exercise_inventory.json", "r") as f:
exercises_set = json.load(f)
f.close()
with open("data/days_sets.json", "r") as f:
sets = json.load(f)
f.close()
with open("data/workout_sets.json", "r") as f:
workout_sets = json.load(f)
f.close()
msg_intro = "Тренировка на сегодня: \n"
if today_day() in {"TUESDAY", "THURSDAY"}:
workout_msg = "Сегодня лёд в Арене 8:00! 🏒"
elif today_day() in {"FRIDAY"}:
workout_msg = "Сегодня лёд в Арене в 22:00! 🏒"
elif today_day() in {"SATURDAY"}:
workout_msg = "Сегодня отдых"
else:
today_set = workout_sets[today_day()]
exercise_msg = "\n".join([k + ":\n" + "".join([" ▪️ " + l + "\n" for l in v]) for k, v in today_set.items()])
workout_msg = "\n".join([msg_intro, exercise_msg])
# Реализация формирование тренировок через пересечение и случайного выбора
# today_set = sets[today_day()]
# workout_dict = dict_intersection(today_set, exercises_set)
# workout = {k: random.choice(v) for k, v in workout_dict.items()}
#
# exercise_msg = "\n".join([k + ":\n" + v + "\n" for k, v in workout.items()])
# workout_msg = "\n".join([msg_intro, exercise_msg])
return workout_msg
def today_day():
"""Return today in text format"""
weekdays = {1: "MONDAY",
2: "TUESDAY",
3: "WEDNESDAY",
4: "THURSDAY",
5: "FRIDAY",
6: "SATURDAY",
7: "SUNDAY"}
return weekdays[datetime.date.today().isoweekday()]
def dict_intersection(d1, d2):
"""Math intersection for Python dictionary"""
return dict((key, d2[key] or d1[key]) for key in set(d1) & set(d2))
# Running functions
def build_running():
"""
Builds the workout for the week.
:return: A string representation of the workout.
"""
with open("data/run.json", "r") as f:
week_runs = json.load(f)
f.close()
run = week_runs["1-я неделя"]
run_msg = "\n".join([k + ":\n" + v + "\n" for k, v in run.items()])
return run_msg