-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathschedule.py
More file actions
293 lines (240 loc) · 8.74 KB
/
schedule.py
File metadata and controls
293 lines (240 loc) · 8.74 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import string
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
CallbackQueryHandler,
ConversationHandler,
CommandHandler,
MessageHandler,
filters,
)
from pycamp_bot.models import Project, Slot, Pycampista, Vote
from pycamp_bot.commands.auth import admin_needed, get_admins_username
from pycamp_bot.scheduler.db_to_json import export_db_2_json
from pycamp_bot.scheduler.schedule_calculator import export_scheduled_result
from pycamp_bot.utils import escape_markdown, get_slot_weekday_name
DAY_SLOT_TIME = {
'day':[], # Guarda el codigo del dia ej: ['A','B']
'slot':[], # Guarda la cantidad de slots del dia iterado ej [5] (se sobreescribe)
'time':[], # Guarda la hora a la que empieza el dia iterado [15] (se sobreescribe)
}
async def cancel(update, context):
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Has cancelado la carga de slots")
return ConversationHandler.END
@admin_needed
async def define_slot_days(update, context):
# TODO: filtrar proyectos por pycamp activo.
if Slot.select().exists():
await context.bot.send_message(
chat_id=update.message.chat_id,
text="El cronograma ya existe."
)
return
if not Project.select().exists():
await context.bot.send_message(
chat_id=update.message.chat_id,
text="No hay proyectos que cronogramear."
)
return
if not Vote.select().exists():
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Todavia no se realizo la votacion."
)
return
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Cuantos dias tiene tu cronograma?"
)
return 1
async def define_slot_ammount(update, context):
global DAY_SLOT_TIME
text = update.message.text
if text not in ["1", "2", "3", "4", "5", "6", "7"]:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="mmm eso no parece un numero de dias razonable, de nuevo?"
)
return 1
DAY_SLOT_TIME['day'] =list(string.ascii_uppercase[0:int(text)])
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Cuantos slots tiene tu dia {}".format(DAY_SLOT_TIME['day'][0])
)
return 2
async def define_slot_times(update, context):
text = update.message.text
day = DAY_SLOT_TIME['day'][0]
await context.bot.send_message(
chat_id=update.message.chat_id,
text="A que hora empieza tu dia {}".format(day)
)
DAY_SLOT_TIME['slot'] = [text]
return 3
async def create_slot(update, context):
username = update.message.from_user.username
chat_id = update.message.chat_id
text = update.message.text
DAY_SLOT_TIME['time'] = [text]
slot_amount = DAY_SLOT_TIME['slot'][0]
times = list(range(int(slot_amount)+1))[1:]
starting_hour = int(text)
while len(times) > 0:
new_slot = Slot(code=str(DAY_SLOT_TIME['day'][0]+str(times[0])))
new_slot.start = starting_hour
pycampista = Pycampista.get_or_create(username=username, chat_id=chat_id)[0]
new_slot.current_wizard = pycampista
new_slot.save()
times.pop(0)
starting_hour += 1
DAY_SLOT_TIME['day'].pop(0)
if len(DAY_SLOT_TIME['day']) > 0:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Cuantos slots tiene tu dia {}".format(DAY_SLOT_TIME['day'][0])
)
return 2
else:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Genial! Slots Asignados"
)
make_schedule(update, context)
return ConversationHandler.END
async def make_schedule(update, context):
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Generando el Cronograma..."
)
data_json = export_db_2_json()
my_schedule = export_scheduled_result(data_json)
for relationship in my_schedule:
slot = Slot.get(Slot.code == relationship[1])
project = Project.get(Project.name == relationship[0])
project.slot = slot.id
project.save()
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Cronograma Generado!"
)
async def check_day_tab(slot, prev_slot, cronograma):
def append_day_name():
cronograma.append(f'*{get_slot_weekday_name(slot.code[0])}:*')
if prev_slot is None:
append_day_name()
elif slot.code[0] != prev_slot.code[0]:
cronograma.append('')
append_day_name()
async def show_schedule(update, context):
slots = Slot.select()
projects = Project.select()
cronograma = []
prev_slot = None
for i, slot in enumerate(slots):
await check_day_tab(slot, prev_slot, cronograma)
for project in projects:
if project.slot_id == slot.id:
cronograma.append(f'{slot.start}:00 *{escape_markdown(project.name)}*')
cronograma.append(f'Owner: @{escape_markdown(project.owner.username)}')
prev_slot = slot
await context.bot.send_message(
chat_id=update.message.chat_id,
text='\n'.join(cronograma),
parse_mode='MarkdownV2'
)
BORRAR_CRONO_PATTERN = "borrarcronograma"
@admin_needed
async def borrar_cronograma(update, context):
if not Slot.select().exists():
await context.bot.send_message(
chat_id=update.message.chat_id,
text="No hay cronograma para borrar."
)
return
keyboard = [
[
InlineKeyboardButton("Sí", callback_data=f"{BORRAR_CRONO_PATTERN}:si"),
InlineKeyboardButton("No", callback_data=f"{BORRAR_CRONO_PATTERN}:no"),
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(
chat_id=update.message.chat_id,
text="¿Borrar el cronograma? Se quitarán todos los slots y asignaciones.",
reply_markup=reply_markup,
)
async def borrar_cronograma_confirm(update, context):
callback_query = update.callback_query
await callback_query.answer()
chat_id = callback_query.message.chat_id
username = callback_query.from_user.username
if username not in get_admins_username():
await context.bot.send_message(
chat_id=chat_id,
text="No estas Autorizadx para hacer esta acción",
)
return
if callback_query.data.split(":")[1] == "no":
await context.bot.send_message(
chat_id=chat_id,
text="Operación cancelada.",
)
return
Project.update(slot=None).execute()
Slot.delete().execute()
await context.bot.send_message(
chat_id=chat_id,
text="Cronograma borrado. Podés volver a usar /cronogramear.",
)
@admin_needed
async def change_slot(update, context):
projects = Project.select()
slots = Slot.select()
text = update.message.text.split(' ')
if not len(text) >= 3:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="""El formato de este comando es:
/cambiar_slot NOMBRE_DEL_PROYECTO NUEVO_SLOT
ej: /cambiar_slot fades AB
"""
)
return
found = False
project_name = " ".join(text[1:-1])
for project in projects:
if project.name == project_name:
for slot in slots:
if slot.code == text[-1]:
found = True
project.slot = slot.id
project.save()
if found:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="Exito"
)
else:
await context.bot.send_message(
chat_id=update.message.chat_id,
text="O el slot o el nombre del proyecto no estan en la db"
)
load_schedule_handler = ConversationHandler(
entry_points=[CommandHandler('cronogramear', define_slot_days)],
states={
1: [MessageHandler(filters.TEXT, define_slot_ammount)],
2: [MessageHandler(filters.TEXT, define_slot_times)],
3: [MessageHandler(filters.TEXT, create_slot)]},
fallbacks=[CommandHandler('cancel', cancel)])
def set_handlers(application):
application.add_handler(CommandHandler('cronograma', show_schedule))
application.add_handler(CommandHandler('borrar_cronograma', borrar_cronograma))
application.add_handler(
CallbackQueryHandler(
borrar_cronograma_confirm,
pattern=f"{BORRAR_CRONO_PATTERN}:",
)
)
application.add_handler(CommandHandler('cambiar_slot', change_slot))
application.add_handler(load_schedule_handler)