forked from deepakm78/kourage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embed.py
514 lines (444 loc) · 20.6 KB
/
embed.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
import asyncio
import platform
import time
import itertools
import discord
import sqlite3
import datetime
import discord
from discord.ext import commands
from datetime import date, timedelta
from discord import client
import datetime
from urllib import parse, request
import sqlite3
from matplotlib import pyplot as plt
import numpy as np
import asyncio
from uuid import uuid4
import datetime
from urllib import parse, request
from sqlite3.dbapi2 import Cursor
import sqlite3
from colorama import init
from termcolor import colored
machine = platform.node()
init()
class Logger:
def __init__(self, app):
self.app = app
def info(self, message):
print(colored(f'[{time.asctime(time.localtime())}] [{machine}] [{self.app}] {message}', 'yellow'))
def warning(self, message):
print(colored(f'[{time.asctime(time.localtime())}] [{machine}] [{self.app}] {message}', 'green'))
def error(self, message):
print(colored(f'[{time.asctime(time.localtime())}] [{machine}] [{self.app}] {message}', 'red'))
def color(self, message, color):
print(colored(f'[{time.asctime(time.localtime())}] [{machine}] [{self.app}] {message}', color))
logger = Logger("kourage-Attendance")
def attendance(opening_time, closing_time):
embed = discord.Embed(title="Attendance System",
description="Please react before closing time else the message will disappear ",
color=0x11806a)
embed.set_author(name="Mark you attendance by reacting ⬆️ emoji")
embed.set_thumbnail(
url="https://media.discordapp.net/attachments/700257704723087360/819643015470514236/SYM_TEAL.png?width=455"
"&height=447")
embed.add_field(name="Opening Time", value=opening_time, inline=False)
embed.add_field(name="Closing Time", value=closing_time, inline=False)
embed.set_footer(text="Made with ❤️️ by Koders")
return embed
def simple_embed(title, description):
embed = discord.Embed(
title = title,
description = description,
colour=0x11806a
)
embed.set_thumbnail(url="https://media.discordapp.net/attachments/700257704723087360/819643015470514236/SYM_TEAL.png?width=455&height=447")
embed.set_footer(text="Made with ❤️️ by Koders")
embed.timestamp = datetime.datetime.utcnow()
return embed
def attendance_dm(date, time, day):
embed = discord.Embed(title="Thank you for marking your attendance!", color=0x11806a)
embed.set_author(name="Attendance")
embed.set_thumbnail(
url="https://media.discordapp.net/attachments/700257704723087360/819643015470514236/SYM_TEAL.png?width=455"
"&height=447")
embed.add_field(name="Date", value=date, inline=True)
embed.add_field(name="Time", value=time, inline=True)
embed.add_field(name="Day", value=day, inline=True)
return embed
def attendance_missed_dm(date, time, day):
embed = discord.Embed(title="Yo have not marked your attendance yet. Only 5 minutes remaining", color=0x11806a)
embed.set_author(name="Attendance")
embed.set_thumbnail(
url="https://media.discordapp.net/attachments/700257704723087360/819643015470514236/SYM_TEAL.png?width=455"
"&height=447")
embed.add_field(name="Date", value=date, inline=True)
embed.add_field(name="Time", value=time, inline=True)
embed.add_field(name="Day", value=day, inline=True)
return embed
async def leave_and_attendance(ctx, bot, start_date, end_date, users, mode):
"""
This module shows attendance and leaves
:params: start_date(str), end_date(str), user_id(int), username(str)
:return: None
:mode: 1 - for attendance, 2 - leaves
"""
logger.info("Show attendance called")
conn = sqlite3.connect('db/ATTENDANCE.sqlite')
cur = conn.cursor()
if mode == 1:
cur.execute('''SELECT DATE, SHIFT, ABSENTEES FROM Attendance_table WHERE DATE BETWEEN ? AND ?''',(start_date, end_date))
if mode == 2:
cur.execute('''SELECT DATE, SHIFT, PRESENTEES FROM Attendance_table WHERE DATE BETWEEN ? AND ?''', (start_date,end_date))
data = cur.fetchall()
if not data: # TODO Check if this is working
no_data_embed=discord.Embed(title="No attendance data found between " + str(start_date) + ' ' + str(end_date),description="",colour=0x11806a)
await ctx.send(embed=no_data_embed,delete_after=60)
logger.warning("No attendance data found between those dates")
return None
else:
morning_only, evening_only, full_day = {}, {}, {}
selected_dates = []
for each in data:
if each[1] == "M":
morning_only[each[0]] = set(each[2].strip('"{}').split(', ')) # Adding members
elif each[1] == "E":
evening_only[each[0]] = set(each[2].strip('"{}').split(', ')) # Adding members
selected_dates.append(each[0])
# Calculating all possible dates and adding members accordingly
selected_dates = set(selected_dates) # For finding unique dates
for each_date in selected_dates:
full_day[each_date]=set()
if not morning_only:
logger.warning("no morning data")
break
if not evening_only:
logger.warning("no evening data")
break
for each_person in morning_only[each_date]:
try:
if each_person in evening_only[each_date]:
full_day[each_date].add(each_person)
except Exception as err:
logger.error("Something went wrong while fetching the full day attendance")
# if full day is found. removing from morning and evening
for each_person in full_day[each_date]:
morning_only[each_date].remove(each_person)
evening_only[each_date].remove(each_person)
if users:
if mode == 1:
status = "Absent"
elif mode == 2:
status = "Present"
print(type(users))
for user in users:
print(await bot.fetch_user(int(user)))
day_full=0
morning=0
evening=0
dates=0
message=""
not_there=set()
if not morning_only:
not_there=set(itertools.chain(full_day[each_date],evening_only[each_date]))
elif not evening_only:
not_there=set(itertools.chain(full_day[each_date],morning_only[each_date]))
elif not full_day:
not_there=set(itertools.chain(morning_only[each_date],evening_only[each_date]))
else:
not_there=set(itertools.chain(full_day[each_date],morning_only[each_date],evening_only[each_date]))
for each_date in selected_dates:
dates=dates+1
if str(user) in not_there:
try:
if str(user) in full_day[each_date]:
message += each_date + ": " + status + " full day \n"
day_full=day_full+1
except Exception as e:
pass
try:
if str(user) in morning_only[each_date]:
message += each_date + ": " + status + " in morning only \n"
morning=morning+1
except Exception as e:
pass
try:
if str(user) in evening_only[each_date]:
message += each_date + ": " + status + " in evening only \n"
evening=evening+1
except Exception as e:
pass
else:
message += each_date +": Not "+status+"\n"
#graph
def addlabels(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = 'center',
Bbox = dict(facecolor = 'grey', alpha =.8))
value = [dates,morning,evening,day_full]
data = ('Total\nDates', 'Morning','Evening','Full')
x_pos = np.arange(len(data))
save_filename='test.png'
plt.bar(x_pos, value, color = ['darkcyan'])
addlabels(data, value)
plt.title(status+' Graph for @'+str(await bot.fetch_user(int(user))))
plt.ylabel('values')
plt.xticks(x_pos, data)
plt.savefig(save_filename,dpi=100)
plt.close()
embed=simple_embed(title="Result for: "+str(await bot.fetch_user(int(user)))+"\n",description="")
embed.add_field(name='Here are the details', value=message, inline=False)
await ctx.send(embed=embed,file=discord.File(save_filename), delete_after = 20)
async def export_csv(ctx,start_date,end_date):
logger.info("export csv called")
conn = sqlite3.connect('db/ATTENDANCE.sqlite')
cur = conn.cursor()
cur.execute('''SELECT DATE, SHIFT, ABSENTEES FROM Attendance_table WHERE DATE BETWEEN ? AND ?''',(start_date, end_date))
data = cur.fetchall()
if not data: # TODO Check if this is working
no_data_embed=discord.Embed(title="No attendance data found between "+str(start_date)+" and "+str(end_date),description="",colour=0x11806a)
await ctx.send(embed=no_data_embed,delete_after=60)
logger.warning("No attendance data found between those dates")
return None
else:
try:
fields = ['Date', 'Shift', 'Absentees']
absentees_file = 'Absentees.csv'
embed=simple_embed(title="Absentees CSV FILE ",description="of dates("+str(start_date)+" "+str(end_date)+")")
with open(absentees_file, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(data)
logger.info("CSV write done")
logger.info(data)
await ctx.send(embed=embed,file=discord.File(absentees_file), delete_after = 60)
logger.info("Absentees("+str(start_date)+" "+str(end_date)+") CSV sent")
except Exception as e:
logger.error("Error sending csv")
def leave_and_attendance(ctx, bot, start_date, end_date, users, mode):
"""
This module shows attendance and leaves
:params: start_date(str), end_date(str), user_id(int), username(str)
:return: None
:mode: 1 - for attendance, 2 - leaves
"""
logger.info("Show attendance called")
conn = sqlite3.connect('db/ATTENDANCE.sqlite')
cur = conn.cursor()
if mode == 1:
cur.execute('''SELECT DATE, SHIFT, PRESENTEES FROM ATTENDANCE WHERE DATE BETWEEN ? AND ?''', str(start_date), str(end_date))
if mode == 2:
cur.execute('''SELECT DATE, SHIFT, ABSENTEES FROM ATTENDANCE WHERE DATE BETWEEN ? AND ?''', str(start_date), str(end_date))
data = cur.fetchone()
if not data: # TODO Check if this is working
logger.warning("No attendance data found between those dates")
return None
else:
# TODO - try with string strips
morning_only, evening_data, full_day = {}, {}, {}
for each in data:
selected_dates = []
if each[1] == "M":
morning_only[each[0]] = set(each[2].strip('"{}').split(', ')) # Adding members
elif each[1] == "E":
evening_only[each[0]] = set(each[2].strip('"{}').split(', ')) # Adding members
selected_dates.append(each[0])
# Calculating all possible dates and adding members accordingly
selected_dates = set(selected_dates) # For finding unique dates
for each_date in selected_dates:
for each_person in morning_only[each_date]:
try:
if each_person in evening_only[each_date]:
full_day[each_date].append(each_person)
# if full day is found. removing from morning and evening
morning_only.remove(each_person)
evening_only.remove(each_person)
except Exception as err:
logger.error("Something went wrong while fetching the full day attendance")
if users:
if mode == 1:
status = "Present"
elif mode == 2:
status = "Absent"
for user in users:
message=""
for each_date in selected_dates:
try:
if user in full_day[each_date]:
message += each_date + ": " + status + " in full day \n"
elif user in morning_only[each_date]:
message += each_date + ": " + status + " in morning only \n"
elif user in evening[each_date]:
message += each_date + ": " + status + " in evening only \n"
except Exception as e:
pass # handling KeyError in dict
embed=simple_embed(title="Result for: "+str(bot.get_user(user)+"\n",description="")
embed.add_field(name='Here are the details', value=message, inline=False)
await ctx.send(embed=embed, delete_after=60)
async def data_input(ctx, bot):
start_date_embed=discord.Embed(title="Enter start date",description="Please enter in this format only 'yyyy-mm-dd'",colour=0x11806a)
start=await ctx.send(embed=start_date_embed,delete_after=60)
start_date1 = await ctx_input(ctx, bot, start)
if not start_date1:
return
end_date_embed=discord.Embed(title="Enter end date",description="Please enter in this format only 'yyyy-mm-dd'",colour=0x11806a)
end=await ctx.send(embed=end_date_embed,delete_after=60)
end_date1 = await ctx_input(ctx, bot, end)
if not end_date1:
return
start_date = datetime.datetime.strptime(start_date1, '%Y-%m-%d')
end_date = datetime.datetime.strptime(end_date1, '%Y-%m-%d')
return start_date, end_date;
attendance_embed=simple_embed(title="Leaves for : "+str(username)+"\n",description="")
attendance_embed.add_field(name='Leaves List', value = attendance_list, inline=False)
return attendance_embed
def attendance(ctx, bot, start_date, end_date, user_id, mode, flag):
"""
This module shows attendance and leaves
:params: start_date(str), end_date(str), user_id(int), username(str)
:return: None
"""
logger.info("Attendance function called")
attendance_list=""
attendance_list=attendance_list+"\n𝗗𝗔𝗧𝗘: "+dates+"\n"
conn = sqlite3.connect('db/ATTENDANCE.sqlite')
cur = conn.cursor()
# TODO
# Fix sql query
if flag == 1:
cur.execute('''SELECT DATE, SHIFT, PRESENTEES FROM ATTENDANCE WHERE ''')
elif flag == 2:
cur.execute('''SELECT DATE, SHIFT, ABSENTEES FROM ATTENDANCE WHERE ''')
data = cur.fetchone()
if not data: # TODO Check if this is working
logger.warning("No attendance data found between those dates")
return None
else:
morning_only, evening_data, full_day = {}, {}, {}
for each in data:
selected_dates = []
# TODO
# Check strip
if each[1] == "M":
morning_only[each[0]] = set(each[2].strip("'{}'").split(', ')) # Adding members
elif each[1] == "E":
evening_only[each[0]] = set(each[2].strip("'{}'").split(', ')) # Adding members
selected_dates.append(each[0])
selected_dates = set(selected_dates) # Unique dates
for each_date in selected_dates:
for each_person in morning_only[each_date]:
try:
if each_person in evening_only[each_date]:
full_day[each_date].append(each_person) # this should be in try and catch
# if full day is found. removing from morning and evening
morning_only.remove(each_person)
evening_only.remove(each_person)
except Exception as err:
logger.error("Something went wrong while fetching the full day attendance")
return morning_only, evening_only, full_day
morning_only[dates] = set of presntees
if((present_morning==True) and (present_evening==True)):
attendance_list=attendance_list+"Present full day\n"
elif((present_morning==False) and (present_evening==True)):
attendance_list=attendance_list+"Absent in morning\n"
elif((present_morning==True) and (present_evening==False)):
attendance_list=attendance_list+"Absent in evening\n"
elif((absent_morning==True) and (absent_evening==True)):
attendance_list=attendance_list+"Absent full day\n"
attendance_embed=simple_embed(title="Leaves for : "+str(username)+"\n",description="")
attendance_embed.add_field(name='Leaves List', value = attendance_list, inline=False)
return attendance_embed
#graph
def addlabels(x,y):
for i in range(len(x)):
plt.text(i, y[i], y[i], ha = 'center',
Bbox = dict(facecolor = 'grey', alpha =.8))
value = [attendance_dates,full_present,morning_present,evening_present,absent]
data = ('Total\nDates', 'Full Day\nPresent', 'Morning\nPresent','Evening\nPresent','Absent')
x_pos = np.arange(len(data))
save_filename='test.png'
plt.bar(x_pos, value, color = ['darkcyan'])
addlabels(data, value)
plt.title('Attendance Graph for @'+str(username))
plt.ylabel('values')
plt.xticks(x_pos, data)
plt.savefig(save_filename,dpi=100)
plt.close()
return attendence_embed,save_filename;
async def ctx_input(ctx, bot, embed, timeout = 60.0):
try:
msg = await bot.wait_for(
"message",
timeout=timeout,
check=lambda message: message.author == ctx.author
)
if msg:
await embed.delete()
_id = msg.content
await msg.delete()
return _id
except asyncio.TimeoutError as err:
await embed.delete()
await ctx.send('Cancelling due to timeout.', delete_after = timeout)
return None
async def data_input(ctx, bot):
start_date_embed=discord.Embed(title="Enter start date",description="Please enter in this format only 'yyyy-mm-dd'",colour=0x11806a)
start=await ctx.send(embed=start_date_embed,delete_after=60)
start_date = await ctx_input(ctx, bot, start)
if not start_date:
return
end_date_embed=discord.Embed(title="Enter end date",description="Please enter in this format only 'yyyy-mm-dd'",colour=0x11806a)
end=await ctx.send(embed=end_date_embed,delete_after=60)
end_date = await ctx_input(ctx, bot, end)
if not end_date:
return
return start_date, end_date;
def simple_embed(title, description):
embed = discord.Embed(
title = title,
description = description,
colour=0x11806a
)
embed.set_thumbnail(url="https://media.discordapp.net/attachments/700257704723087360/819643015470514236/SYM_TEAL.png?width=455&height=447")
embed.set_footer(text="Made with ❤️️ by Koders")
embed.timestamp = datetime.datetime.utcnow()
return embed
_rxn_no = {'1️⃣':1, '2️⃣':2, '3️⃣':3,'4️⃣':4}
async def take_reaction_no(ctx, rxn_amnt, _embed, bot, timeout=300.0):
rxn = dict()
_i = 1
for i in _rxn_no:
if _i > rxn_amnt:
break
rxn[i] = _i
_i += 1
for i in rxn:
await _embed.add_reaction(i)
def check(reaction, user):
_c1 = user.bot is not True and user == ctx.author
return _c1 and str(reaction.emoji) in rxn
try:
result = await bot.wait_for('reaction_add', check=check, timeout=timeout)
reaction, user = result
ret = (None, rxn[str(reaction)]) [ str(reaction) in rxn ]
return ret, _embed
except asyncio.TimeoutError:
await ctx.delete()
async def ctx_input(ctx, bot, embed, timeout = 60.0):
try:
msg = await bot.wait_for(
"message",
timeout=timeout,
check=lambda message: message.author == ctx.author
)
if msg:
await embed.delete()
_id = msg.content
await msg.delete()
return _id
except asyncio.TimeoutError as err:
await embed.delete()
await ctx.send('Cancelling due to timeout.', delete_after = timeout)
return None