-
Notifications
You must be signed in to change notification settings - Fork 34
/
printers.py
245 lines (183 loc) · 9.89 KB
/
printers.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import datetime
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update, Message
import job_storage
import utils
import worker
from termin_api import Buro
def get_msg(update: Update) -> Message:
"""
Gets `Message` object which can be used for answers.
It is needed because way to get Message is different for callback updates and normal updates
:param update: Update
:return: Message
"""
if update.message:
return update.message
else:
return update.callback_query.message
def print_subscription_status(update, context):
msg = get_msg(update)
chat_id = str(update.effective_chat.id)
subscription = job_storage.get_job(chat_id)
if subscription:
subscription_limit = subscription.kwargs['created_at'] + datetime.timedelta(days=7)
subscription_limit_date_time = subscription_limit.strftime("%d-%m-%Y %H:%M:%S")
deadline = subscription.kwargs['deadline'].strftime("%d-%m-%Y") if 'deadline' in subscription.kwargs else '-'
department = Buro.get_buro_by_id(subscription.kwargs['buro'])
msg.reply_text(
f'Current subscription details:\n\n - Department: {department.get_name()} \n - Type: {subscription.kwargs["termin"]} \n - Interval: {subscription.trigger.interval} \n - Until: {subscription_limit_date_time} \n - Not later than: {deadline} \n')
print_unsubscribe_button(chat_id)
def notify_about_termins(chat_id, buro, termin, created_at, deadline=None):
"""
Checks for available termins and prints them if any
"""
department = Buro.get_buro_by_id(buro)
if department is None:
return
bot = utils.get_bot()
appointments = worker.get_available_appointments(department, termin, user_id=str(chat_id))
if appointments is None:
bot.send_message(chat_id=chat_id,
text=f'Seems like appointment title <{termin}> is not accepted by the buro <{department.get_name()}> any more\n'
'Please check of issues on Github and create one if not reported yet '
'(https://github.com/okainov/munich-scripts/issues/new)\n'
'In the meantime, we\'ve removed this subscription in order to prevent sending '
'more of such useless messages :( Please come back later'
)
job_storage.remove_subscription(chat_id)
if deadline is not None:
appointments = [(caption, date, time) for caption, date, time in appointments if
datetime.datetime.strptime(date, '%Y-%m-%d') <= deadline]
if len(appointments) > 0:
for caption, date, time in appointments:
bot.send_message(chat_id=chat_id,
text=f'The nearest appointments at {caption} are on {date}:\n'
'%s' % '\n'.join(time))
bot.send_message(chat_id=chat_id, text=f'Please book your appointment here: {department.get_frame_url()}')
print_unsubscribe_button(chat_id)
def print_subscription_status_for_termin(update, context):
msg = get_msg(update)
chat_id = str(update.effective_chat.id)
termin = context.user_data['termin_type']
subscription = job_storage.get_job(chat_id)
if subscription and subscription.kwargs['termin'] == termin:
subscription_limit = subscription.kwargs['created_at'] + datetime.timedelta(days=7)
date_object = subscription_limit.strftime("%d-%m-%Y")
msg.reply_text(
f'Subscription with interval {subscription.trigger.interval}m is already active until {date_object} \n')
print_unsubscribe_button(chat_id)
else:
buttons = [InlineKeyboardButton(text="Subscribe", callback_data="subscribe")]
custom_keyboard = [buttons]
msg.reply_text(
'If you want, you can subscribe for available appointments of this type. '
'After then you will receive regular updates about available appointments for a month',
reply_markup=InlineKeyboardMarkup(custom_keyboard, one_time_keyboard=True))
def print_main_message(update, context):
deps = Buro.__subclasses__()
MAX_BURO_IN_ROW = 2
custom_keyboard = []
buttons = []
for i, dep in enumerate(deps):
buttons.append(InlineKeyboardButton(text=dep.get_name(), callback_data=dep.__name__))
if i % MAX_BURO_IN_ROW == MAX_BURO_IN_ROW - 1:
custom_keyboard.append(buttons)
buttons = []
if buttons:
custom_keyboard.append(buttons)
if 'buro' in context.user_data and 'termin_type' in context.user_data:
custom_keyboard.append([InlineKeyboardButton(text='Reuse last selection', callback_data='_REUSE')])
msg = get_msg(update)
msg.reply_text(
'Here are available departments\. Please select one:',
reply_markup=InlineKeyboardMarkup(custom_keyboard, one_time_keyboard=True), parse_mode='MarkdownV2')
print_subscription_status(update, context)
def print_stat_message(update, context):
chat_id = update.effective_chat.id
utils.get_logger().info(f'[{chat_id}] Displaying statistics', extra={'user': chat_id})
msg = get_msg(update)
all_jobs = [x for x in job_storage.get_jobs() if 'chat_id' in x.kwargs]
if not all_jobs:
msg.reply_text(f'ℹ️ No active subscriptions')
return
average_interval = sum([x.trigger.interval.seconds for x in all_jobs]) / 60 / len(all_jobs)
termin_list = [x.kwargs['termin'] for x in all_jobs]
most_popular_termin = max(set(termin_list), key=lambda x: termin_list.count(x))
msg.reply_text(f'ℹ️ Some piece of statistics:\n\n'
f'{len(all_jobs)} active subscription(s)\n'
f'{average_interval} min average interval\n'
f'{most_popular_termin} is the most popular termin')
def print_termin_type_message(update, context):
buttons = []
msg = get_msg(update)
department = context.user_data['buro']
msg.reply_text(
'Fetching available appointment types...')
if info_message := department.get_info_message():
msg.reply_text(
info_message,
parse_mode='MarkdownV2',
reply_markup=InlineKeyboardMarkup(buttons, one_time_keyboard=True))
for i, x in department.get_typical_appointments():
buttons.append([InlineKeyboardButton(text=x, callback_data=i)])
if department.get_typical_appointments():
buttons.append([InlineKeyboardButton(text='--------------', callback_data='-1')])
for i, x in enumerate(department.get_available_appointment_types()):
buttons.append([InlineKeyboardButton(text=x, callback_data=i)])
msg.reply_text(
'There are several appointment types available. Most used types are on top. Please select one',
reply_markup=InlineKeyboardMarkup(buttons, one_time_keyboard=True))
def print_quering_message(update, context):
msg = get_msg(update)
termin_type_str = context.user_data['termin_type']
msg.reply_text(
f'Great, wait a second while I\'m fetching available appointments for {termin_type_str}...')
print_available_termins(update, context, print_if_none=True)
buttons = [InlineKeyboardButton(text="Return back", callback_data="return")]
custom_keyboard = [buttons]
msg.reply_text(
text='Or just return to the main selection',
reply_markup=InlineKeyboardMarkup(custom_keyboard, one_time_keyboard=True))
def print_available_termins(update, context, print_if_none=False):
"""
Checks for available termins and prints them if any
"""
department = context.user_data['buro']
termin_type_str = context.user_data['termin_type']
msg = get_msg(update)
appointments = worker.get_available_appointments(department, termin_type_str, user_id=str(update.effective_chat.id))
if appointments is None:
msg.reply_text(
f'Seems like appointment title <{termin_type_str}> is not accepted by the buro <{department}> any more\n'
'Possible reasons:\n'
'- The buro has updated their appointments page and bot requires a fix\n'
'- Our data about this appointment is out-of-date\n'
'Please check for issues on Github and create a new one if needed'
' (https://github.com/okainov/munich-scripts/issues/new). '
f'Alternatively, please check buro\'s webpage itself at {department.get_frame_url()}')
if len(appointments) > 0:
for caption, date, time in appointments:
msg.reply_text(f'The nearest appointments at {caption} are on {date}:\n'
'%s' % '\n'.join(time))
msg.reply_text(f'Please book your appointment here: {department.get_frame_url()}')
print_subscription_status_for_termin(update, context)
elif print_if_none:
msg.reply_text('Unfortunately, everything is booked. Please come back in several days :(')
print_subscription_status_for_termin(update, context)
def print_unsubscribe_button(chat_id):
buttons = [InlineKeyboardButton(text="Unsubscribe", callback_data="_STOP")]
custom_keyboard = [buttons]
utils.get_bot().send_message(chat_id,
'To unsubscribe click the button',
reply_markup=InlineKeyboardMarkup(custom_keyboard, one_time_keyboard=True))
def print_deadline_message(update, context):
msg = get_msg(update)
msg.reply_text(
'Please type deadline in days from now. You will not be notified for appointments later than this. '
'Typically this might be used if you\'ve got a termin in a few months already, '
'but want to get an earlier one. If you don\'t know what to type, use 100 or 365.')
def print_subscribe_message(update, context):
msg = get_msg(update)
MIN_CHECK_INTERVAL_MINUTES = utils.get_min_interval()
msg.reply_text(
f'Please type interval in minutes. Interval should greater or equal than {MIN_CHECK_INTERVAL_MINUTES} minutes.')