-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtelepostgre.py
More file actions
1857 lines (1627 loc) · 91.3 KB
/
telepostgre.py
File metadata and controls
1857 lines (1627 loc) · 91.3 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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
print('running telepostgre')
import teleadmin
import psycopg2
import logging
import datetime
import sqlite3
from time import sleep
import re
import schedule
import requests
##from dbcontrol import estab_conn
from telegram import Update, InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery
from telegram.ext import filters, MessageHandler, ApplicationBuilder, ContextTypes, CommandHandler, CallbackQueryHandler, CallbackContext, ConversationHandler
from tpfpostgre import *
print('running2')
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
print(f'tele.py running started at time: {datetime.datetime.now()}')
application = ApplicationBuilder().token("5948121349:AAG3k_7Wv-aCxyQlJzCtR0U4vcN8-onmUqI").build()
def send_to_admin(message='hello'):
TOKEN = "5811073358:AAGgEtuRoV4T1f4zKjukgu3-gTJpAqogru0"
chatid = '298000154'
url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chatid}&text={message}"
requests.get(url).json()
def execute_pgsql(sql: str, values=[], fetchall=False, fetchone=False, fetchmany=False):
#SETUP
#SET TOKEN AS MFPNEWBOT TOKEN
API_TOKEN = "5948121349:AAF_BtTRt0ckuYnZbDO81pv7aOVpZAT4aVs""5948121349:AAF_BtTRt0ckuYnZbDO81pv7aOVpZAT4aVs"
#SET DB URL FROM RAILWAY
DB_URL = "postgresql://postgres:[email protected]:7864/railway"
conn = psycopg2.connect(DB_URL, sslmode='require')
cur = conn.cursor()
result = False
#TRY BLOCK
try:
if fetchall:
if len(values)==0:
print('fetchall, lv=0')
cur.execute(sql)
try:
result = cur.fetchall()
except:
pass
else:
print('fetchall, lv=+')
resultpre = cur.execute(sql, values)
try:
result = cur.fetchall()
except:
pass
elif fetchone:
if len(values)==0:
print('fetchone, lv=0')
resultpre = cur.execute(sql)
try:
result = cur.fetchone()
except:
pass
else:
print('fetchone, lv=+')
resultpre = cur.execute(sql, values)
try:
result = cur.fetchone()
except:
pass
elif fetchmany:
if len(values)==0:
print('fetchmany, lv=0')
resultpre = cur.execute(sql)
try:
result = cur.fetchmany()
except:
pass
else:
print('fetchmany, lv=+')
resultpre = cur.execute(sql, values)
try:
result = cur.fetchmany()
except:
pass
else:
if len(values)==0:
print('nofetchall, lv=0')
result = cur.execute(sql)
else:
print('nofetchall, lv=+')
result = cur.execute(sql, values)
conn.commit()
print(f'successful execution of pgsql: result: {result}, sql: \'{sql}\'')
except Exception as e:
print(f'pgsql fail with exception {e}, sql: {sql}')
result = e
cur.close()
conn.close()
return result
#verify if account created -- called by all functions except start and username -- returns username if userid exists and False if not
#by default sends msg to user if account does not exist, but prin False prevents the send
def verify_if_account_exists(userid, context, prin = True, update=''):
'''checks if userid is in database, if not ask to create username'''
if not userid_exists(userid):
return False
else:
return userid_exists(userid)
#start function -- called by /start - welcomes user to bot and requests them to type username to create account - might need to have login function
async def start(update: Update, context):
user = update.message.from_user
print('user {}, user ID: {}, called /start'.format(user['username'], user['id']))
if userid_exists(user['id']): #if id exists in userdatadb already, welcome back
await context.bot.send_message(chat_id=update.effective_chat.id, text='welcome back, {}! \n\ntype /help to view available commands and options'.format(userid_exists(user['id'])))
else: #if id exists in userdatadb already, welcome and direct to account creation (username)
await context.bot.send_message(chat_id=update.effective_chat.id, text="welcome to mfp_bot!")
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /username <your username> to create an account \n\nlike this: /username user1.')
#help function -- called at anytime - prints list of functions and commands
async def telehelp(update: Update, context):
await context.bot.send_message(chat_id=update.effective_chat.id, text='''here is what you can do in mfpbot
\U0001F4CB /viewlog: your daily activity log
\U0001F4CA /viewmacros: your daily macro info
\U0001F3CB /viewgym: your gym PBs
\U0001F371 /newactivity: add activities to daily log \n'''+
u'\u2696' + ''' /updateweight update your weight
\U0001F4B8 /viewmoney: your food expenditure
\U0001F4D2 /customentry: add custom entries to personal database''')
#username function -- called by /username - if input is formatted correctly, verify username is unique, create user table in userdata.db, inform user
async def username(update: Update, context, tele_call=True):
user = update.message.from_user
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /username <your username> to create a username. \n\nlike this: /username user1.')
else:
print('user ID: {}, called /username'.format(user['id']))
usernameinput = context.args[0].lower()
if username_validation(usernameinput, user['id']):
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'user {usernameinput} created. \n\ntype /setmacros to set your macro targets or /changeusername to change your username')
send_to_admin(f'user {usernameinput} created')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'username {usernameinput} is already taken. \n\ntype /username <your username> to create another username \n\nlike this: /username user1')
#can be called by all users, introduces setbcg to new users and prints menu for existing users
async def setmacros(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setmacros'.format(user['id']))
if verify_if_account_exists(user['id'], context):
keyboard = [[InlineKeyboardButton("macro calculator", url = 'https://www.fatcalc.com/bwp'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
if usermacros_created(user['id']):
# await context.bot.send_message(chat_id=update.effective_chat.id, text='find out more about your daily macro targets at: \n\nhttps://www.fatcalc.com/bwp \n', disable_web_page_preview=True)
await context.bot.send_message(chat_id=update.effective_chat.id, text='''which targets would you like to set? \n
bcg - /setbcg <your bcg>
protein - /setp <your protein target>
carbs - /setc <your carb target>
fat - /setf <your fat target>
weight - /setw <your weight goal>
current weight - /updateweight <your current weight>
or type /help to view available commands and options''', reply_markup=reply_markup)
else:
await update.message.reply_text(text='calculate your daily macro targets', reply_markup=reply_markup)
# await context.bot.send_message(chat_id=update.effective_chat.id, text='find out more about your daily macro targets at: \n\nhttps://www.fatcalc.com/bwp \n', disable_web_page_preview=True)
await context.bot.send_message(chat_id=update.effective_chat.id, text=
'''let's start with your base calorie goal.
base calorie goal (bcg) - a specific amount of calories that you aim to consume on a daily basis in order to reach your weight goal.
type /setbcg <your bcg> to set bcg.
like this: /setbcg 2000''')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
#can be called by any user, when called (verifies input is integer then updates default in database) (introduce setp function to set protein goal)
async def setbcg(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setbcg'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /setbcg <your bcg> to set bcg. \n\nlike this: /setbcg 2000')
try:
value = int(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your bcg> must be a number')
else:
if verify_if_account_exists(user['id'], context):
set_macro = sql_set_defaultmacro('calout', value, user['id'])
if set_macro == 'true': #successful set of default macro - tell user success and redirect to other functions
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your daily bcg has been set to {value} calories')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /setmacros to set your other macro targets or /setbcg <new bcg> to change your bcg' )
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /setbcg again or contact bot admin at @xxx')
send_to_admin(f'set bcg fail for user {username} with exception {set_macro[1]}')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def setp(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setp'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /setp <your protein target> to set your protein target in grams. \n\nlike this: /setp 120')
try:
value = int(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your protein target> must be a number')
else:
if verify_if_account_exists(user['id'], context):
set_macro = sql_set_defaultmacro('prottarget', value, user['id'])
if set_macro == 'true': #successful set of default macro - tell user success and redirect to other functions
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your daily protein target has been set to {value}g')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /setmacros to set your other macro targets or /setp <new protein target> to change your protein target')
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /setp again or contact bot admin at @xxx')
send_to_admin(f'set p fail for user {username} with exception {set_macro[1]}')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def setc(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setc'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /setc <your carb target> to set your carb target in grams. \n\nlike this: /setp 200')
try:
value = int(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your carb target> must be a number')
else:
if verify_if_account_exists(user['id'], context):
set_macro = sql_set_defaultmacro('carbtarget', value, user['id'])
if set_macro == 'true': #successful set of default macro - tell user success and redirect to other functions
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your daily carb target has been set to {value}g')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /setmacros to set your other macro targets or /setc <new carb target> to change your carb target' )
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /setc again or contact bot admin at @xxx')
send_to_admin(f'set c fail for user {username} with exception {set_macro[1]}')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def setf(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setf'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /setf <your fat target> to set your fat target in grams. \n\nlike this: /setf 60')
try:
value = int(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your fat target> must be a number')
else:
if verify_if_account_exists(user['id'], context):
set_macro = sql_set_defaultmacro('fattarget', value, user['id'])
if set_macro == 'true': #successful set of default macro - tell user success and redirect to other functions
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your daily fat target has been set to {value}g')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /setmacros to set your other macro targets or /setf <new fat target> to change your fat target' )
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /setf again or contact bot admin at @xxx')
send_to_admin(f'set f fail for user {username} with exception {set_macro[1]}')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def setw(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /setw'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /setw <your weight goal> to set your weight goal in kg. \n\nlike this: /setw 60')
try:
value = float(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your weight goal> must be a number (can be a decimal)')
else:
if verify_if_account_exists(user['id'], context):
set_macro = sql_set_defaultmacro('fattarget', value, user['id'])
if set_macro == 'true': #successful set of default macro - tell user success and redirect to other functions
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your weight goal has been set to {value}kg')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /updateweight <your current weight> to set your current weight or type /setmacros to set your other macro targets' )
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /setw again or contact bot admin at @xxx')
send_to_admin(f'set w fail for user {username} with exception {set_macro[1]}')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def updateweight(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /updateweight'.format(user['id']))
if len(context.args) == 0:
await context.bot.send_message(chat_id=update.effective_chat.id, text='type /updateweight <your current weight> to update your current weight in kg. \n\nlike this: /updateweight 60')
try:
value = float(context.args[0])
except:
await context.bot.send_message(chat_id=update.effective_chat.id, text='<your weight> must be a number (can be a decimal)')
else:
username = verify_if_account_exists(user['id'], context)
if username:
datetoday = datetime.datetime.now().strftime("%d-%m-%Y")
print(datetoday)
presql = f'DELETE FROM tracking_{username} where date LIKE \'%{datetoday}%\''
x= False
try:
execute_pgsql(presql) #IF WEIGHT FOR TODAY INPUTTED BEFORE THEN DELETE
execute_pgsql(f'INSERT INTO tracking_{username}(date,weight) VALUES(%s,%s)', (datetoday, value))
x = True
except Exception as e:
print(e)
send_to_admin(f'updateweight fail for user {username} with exception {e}')
if x: #successful set of weight
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'your weight has been updated to {value}kg')
await context.bot.send_message(chat_id=update.effective_chat.id, text ='type /help to view other functions' )
else: #unsuccessful set of default macro -- tell user got issue and tell admin got issue
await context.bot.send_message(chat_id=update.effective_chat.id, text=f'there was an issue setting this value\ntry using /updateweight again or contact bot admin at @xxx')
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def viewlog(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /viewlog'.format(user['id']))
username = verify_if_account_exists(user['id'], context)
if not username: #if username does not exist, v_i_a_e will tell user they have nt created account and return False
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
return False #end viewlog function
else:
pass #continue viewlog function
printstring = display_activity_log(username, True) #return a formatted activity log print string
printstring += '\n\ntype /newentry to add a new activity'
if printstring != 'no activities today :/':
printstring += '\ntype /viewmacros to view today\'s macros'
await context.bot.send_message(chat_id=update.effective_chat.id, text=printstring)
async def viewmacros(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /viewmacros'.format(user['id']))
username = verify_if_account_exists(user['id'], context, update=update)
if not username: #if username does not exist, v_i_a_e will tell user they have nt created account and return False
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
return False #end viewmacros function
else:
pass #continue viewmacros function
try:
printstring = display_macros(username)
except Exception as e:
send_to_admin(f'display_macros called by {username} and failed with exception {e}')
else:
printstring += '\n\ntype /newentry to add a new activity'
printstring += '\ntype /setmacros to change your macro goals'
await context.bot.send_message(chat_id=update.effective_chat.id, text=printstring)
print(f'display_macros called by {username} and returned the formatted printstring correctly')
async def viewgympri(update: Update, context):
user = update.message.from_user
print('user ID: {}, called /viewgym'.format(user['id']))
username = verify_if_account_exists(user['id'], context, update=update)
if not username: #if username does not exist, v_i_a_e will tell user they have nt created account and return False
return False #end viewgym function
else:
pass #continue viewgym function
buttons = [[
InlineKeyboardButton(text="biceps", callback_data='biceps'),
InlineKeyboardButton(text="triceps", callback_data='triceps'),
InlineKeyboardButton(text="shoulders", callback_data='shoulders')],
[
InlineKeyboardButton(text="back", callback_data='back'),
InlineKeyboardButton(text="chest", callback_data='chest'),
InlineKeyboardButton(text="abs", callback_data='abs'),
InlineKeyboardButton(text="legs", callback_data='legs')]
]
keyboard = InlineKeyboardMarkup(buttons)
await update.message.reply_text('select muscle group:', reply_markup=keyboard)
async def viewgymhandle(update: Update, context):
user = update.callback_query.from_user
username = verify_if_account_exists(user['id'], context)
query = update.callback_query
group = query.data
print(group)
await query.answer()
#get all gym records for specified group - search for entries with names that contain <group> AND lift (incase like meals got core inside also)
names = execute_pgsql(f'SELECT * FROM uniquedata_{username} WHERE name ILIKE \'%lift%\' AND name ILIKE \'%{group}%\'',fetchall=True)
lifts_string = f'''current PBs for {group}
------------------------\n'''
print('here')
for i in names: #compile print string for display to user
lift, groupname, exname = i[1].split(", ")
sets = int(i[2])
weight = float(i[3])
reps = int(i[4])
if sets == 0 and weight == 0 and reps == 0:
pass
else:
lifts_string += f'{groupname}, {exname}: {str(sets)}x{str(reps)} {weight} kg\n'
if lifts_string == f'''current PBs for {group}\n------------------------\n''':
lifts_string = f'no current PBs for {group}'
lifts_string += '\ntype /viewgym again to view PBs for another muscle group'
await context.bot.send_message(chat_id=update.effective_chat.id, text=lifts_string)
print('here3')
print(f'viewgym called by {username} and returned the formatted lifts_string correctly')
####TEST THIS FUNCTION TO SEE IF BUTTONS REMAIN AFTER SELECTION IF SO THEN DONT NEED TO REDIRECT TO VIEWGYM AGAIN
async def unknown(update: Update, context):
await context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.")
async def testfunction(update, context):
keyboard = [[InlineKeyboardButton("toxic", callback_data='toxicabc123'), InlineKeyboardButton("nottoxic", callback_data='nottoxicabc123') ]]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(chat_id = update.effective_chat.id, text='dog', reply_markup=reply_markup)
async def testhandlerfunction(update, context: CallbackContext):
query = update.callback_query
# print(query.data)
#echo function -- no use yet
async def echo(update: Update, context):
await context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
####################################CONV HANDLER############################################
# State definitions for states (initial states before split for gym
SELECTING_SUBTYPE, TYPING_STRING, SEARCH_NEW_NAME, SELECTING_OPTION, SELECT_DIFF_OPTION, TYPING_QU4NTITY, CHANGE_QUANTITY = map(chr, range(7))
# State definitions for states (states for gym numbers)
SELECTING_REPLACE, TYPING_SETS, TYPING_WEIGHT, CHANGE_WEIGHT, TYPING_REPS, CHANGE_REPS = map(chr,range(7, 13))
# State definitions for states (datetime)
SELECTING_DATE, CHANGE_DATE, TYPING_TIME, CHANGE_TIME = map(chr,range(13, 17))
# State definitions for states (completing entries)
COST_YESNO, TYPING_COST, CHANGE_COST, VERIFYING_RESTART, CONFIRMING_RESTART, NEWORADD, CONFIRMING_REPS, CONFIRMING_WEIGHT = map(chr,range(17, 25))
SINGLE_ENTRY, GYM_ADDORSAVE, TYPING_TYTLE, FOOD_ADDORSAVE, INVALID_SEARCH, INVALID_OPTION, CONFIRMING_TIME = map(chr,range(25, 32))
END = ConversationHandler.END
print('XXXXXXX', TYPING_TYTLE == TYPING_STRING)
print(type(SELECTING_SUBTYPE), type(TYPING_STRING), type(SELECTING_OPTION), type(END), sep='\n')
async def newactivity(update: Update, context):
try:
query = update.callback_query #check for callback query
data = query.data
print('ne have cbquery')
if data == 'reselect_subtype': #if there is callbackquery data, it means its a backwards call, so just display the buttons again for user to click
user = update.callback_query.from_user
print('user ID: {}, called /newactivity'.format(user['username']))
title = context.user_data['activitytitle']
print('hertry3')
buttons = [
[
InlineKeyboardButton(text="breakfast", callback_data='breakfast'),
InlineKeyboardButton(text="snack", callback_data='snack'),
],
[
InlineKeyboardButton(text="lunch", callback_data='lunch'),
InlineKeyboardButton(text="dinner", callback_data='dinner'),
],
[
InlineKeyboardButton(text="cardio", callback_data='cardio'),
InlineKeyboardButton(text="sport", callback_data='sport'),
InlineKeyboardButton(text="gym", callback_data='gym'),
],
]
keyboard = InlineKeyboardMarkup(buttons)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text='select activity type', reply_markup=keyboard) #ask user to click button to select activity type
return SELECTING_SUBTYPE
except: #normal call and not reverse callback from reverse
print('ne fwd call')
user = update.message.from_user
print('user ID: {}, called /newentry'.format(user['username']))
if verify_if_account_exists(user['id'], context):
# if title == 'x': #if activitytitle provided with command is x, save title as empty string
# context.user_data['activitytitle'] = ''
# else:
# context.user_data['activitytitle'] = title #save title as title provided
buttons = [
[
InlineKeyboardButton(text="breakfast", callback_data='breakfast'),
InlineKeyboardButton(text="snack", callback_data='snack'),
],
[
InlineKeyboardButton(text="lunch", callback_data='lunch'),
InlineKeyboardButton(text="dinner", callback_data='dinner'),
],
[
InlineKeyboardButton(text="cardio", callback_data='cardio'),
InlineKeyboardButton(text="sport", callback_data='sport'),
InlineKeyboardButton(text="gym", callback_data='gym'),
],
]
keyboard = InlineKeyboardMarkup(buttons)
await update.message.reply_text(text='select activity type ', reply_markup=keyboard) #ask user to click button to select activity type
return SELECTING_SUBTYPE
else:
await context.bot.send_message(chat_id=update.effective_chat.id, text='you have not created an account yet \n\n type /username <your username> to create an account \n\nlike this: /username user1.')
async def req_for_title(update: Update, context):
print(conv_handler.check_update(update))
subtype = update.callback_query.data
if subtype in ['breakfast', 'lunch', 'dinner', 'snack']:
maintype = 'food'
else:
maintype = 'workout'
context.user_data['maintype'] = maintype #save type in user data
context.user_data['subtype'] = subtype #save subtype in user data
subtype_string = subtype if maintype == 'food' else str(subtype + ' activity')
message = f'enter a title for your {subtype_string}\n\nor click \U0001F447 to skip title'
keyboard = [[InlineKeyboardButton("skip title", callback_data='skip_title'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=message, reply_markup=reply_markup)
print('returning typing_tYtle')
return TYPING_TYTLE
async def req_for_search(update: Update, context):
print('in rfs')
subtype = context.user_data['subtype']
maintype = context.user_data['maintype']
try:
title = update.message.text #forward call with title text
context.user_data['activitytitle'] = title
except:
# print(update.callback_query.data)
if update.callback_query.data == 'skip_title': #forward call with skip title
# print('true')
context.user_data['activitytitle'] = subtype
else: #reverse call
# print('frue')
title = context.user_data['activitytitle']
if maintype == 'food' or subtype == 'gym':
try:
print(context.user_data['tempdict'])
if len(context.user_data['tempdict']) < 1:
context.user_data['tempdict'] = [] #if no entries in dictionary, reinitialise jic
except:
context.user_data['tempdict'] = [] #initialise if tempdict does not exist
a = 'food' if maintype == 'food' else 'lift' if subtype == 'gym' else subtype
message = f'type to search for a {a} \nor click \U0001F447 to select a different activity type'
keyboard = [[InlineKeyboardButton("select different activity type", callback_data='reselect_subtype'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=message, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=message, reply_markup=reply_markup)
print('returning typing_string')
return TYPING_STRING
async def select_option(update: Update, context):
print('s_o')
maintype = context.user_data['maintype']
subtype = context.user_data['subtype']
title = context.user_data['activitytitle']
try:
searchname = update.message.text
context.user_data['searchname'] = searchname
#if update.message text exists, select_option call is from message handler (forward call from r_f_s), save searchname as update.message.text
except Exception:
print('here4')
searchname = context.user_data['searchname']
#if update.message.text does not exists, s_o call is from cqh (reverse call from r_f_q), retrieve originally searched searchname
try:
user = update.message.from_user
except:
user = update.callback_query.from_user
userid = user['id'] #get username from userid
username = verify_if_account_exists(userid, context, prin=False) #get username from viae and prevents message send
a = 'food' if maintype == 'food' else 'lift' if subtype == 'gym' else subtype
message = f'searching {a} database for: {searchname}...'
try:
await update.message.reply_text(message)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(message)
print(f'searchname: {searchname}')
splitsearchname = searchname.split(' ')
sql1 = ''
if len(splitsearchname) == 1:
sql1 = f'SELECT * FROM uniquedata_{username} WHERE name LIKE \'%{a}%\' AND name ILIKE \'%{searchname}%\''
elif len(splitsearchname) == 2:
sql1 = f'SELECT * FROM uniquedata_{username} WHERE name LIKE \'%{a}%\' AND name ILIKE \'%{splitsearchname[0]}%\' AND name ILIKE \'%{splitsearchname[1]}%\''
elif len(splitsearchname) == 3:
sql1 = f'SELECT * FROM uniquedata_{username} WHERE name LIKE \'%{a}%\' AND name ILIKE \'%{splitsearchname[0]}%\' AND name ILIKE \'%{splitsearchname[1]}%\' AND name ILIKE \'%{splitsearchname[2]}%\''
elif len(splitsearchname) > 3:
x = ' '.join(splitsearchname[2:])
sql1 = f'SELECT * FROM uniquedata_{username} WHERE name LIKE \'%{a}%\' AND name ILIKE \'%{splitsearchname[0]}%\' AND name ILIKE \'%{splitsearchname[1]}%\' AND name ILIKE \'%{x}%\''
print(sql1)
try:
results = execute_pgsql(sql1,fetchall=True)
if len(results) < 1:
message2 = f'no {a} found containing {searchname}\n\nclick \U0001F447 to search for another {a}\n\nor type /exit then /customentry to create a new {a}'
keyboard = [[InlineKeyboardButton(f"search for another {a}", callback_data=subtype),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=message2, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=message2, reply_markup=reply_markup)
return SELECTING_OPTION
else:
internaldict = {}
message2 = f'search results for {searchname}: \n'
for searchid in range(1, len(results)+1):
internaldict[searchid] = results[searchid-1] #tag each result with a search id
for searchid, val in internaldict.items():
itemname = ', '.join(val[1].split(', ')[1:])
msgpart = f'{searchid}: {itemname}\n' #print search id: item name
message2 += msgpart
context.user_data['resultsdict'] = internaldict #save internaldict to userdata for next function to access
print(internaldict, 'so')
message2 += f'\ntype the number of the {a} you would like to add to the actvity \n\nor click \U0001F447 to search for another {a}'
except:
message2 = f'no {a} found containing {searchname}\n\nclick \U0001F447 to search for another {a}'
keyboard = [[InlineKeyboardButton(f"search for another {a}", callback_data=subtype),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=message2, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=message2, reply_markup=reply_markup)
return SELECTING_OPTION
async def req_for_quantity(update: Update, context):
print('rfq')
maintype = context.user_data['maintype']
subtype = context.user_data['subtype']
title = context.user_data['activitytitle']
resultsdict = context.user_data['resultsdict']
print(resultsdict, 'rfq')
try:
#if update.message.text is available, means forward call and save the selectedoption
selectedoption = int(update.message.text)
searchid = str(resultsdict[selectedoption][0]) # get the database id of selected entry from user
context.user_data['selectedoption'] = selectedoption
context.user_data['searchid'] = searchid # save the database id of selected entry to user_data
print('successful option select')
except ValueError:
print(e)
keyboard = [[InlineKeyboardButton(text="select different option", callback_data='sdo'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid option\n\nclick \U0001F447 to re-select option', reply_markup=reply_markup)
return INVALID_OPTION #if invalid input and cannot find in resultsdict, revert by using INVALID_OPTION state to handle callbackquery sdo
except:
#if update.message.text is unavailable, means either backward or invalid call
try:
#if context.user_data['selectoption' is available, it means its a callback where so and si have been saved before
selectedoption = context.user_data['selectedoption']
searchid = context.user_data['searchid']
print('successful reverse to selectoption')
except:
#handles case where selected option is not inside resultsdict or if selected option is invalid
keyboard = [[InlineKeyboardButton(text="select different option", callback_data='sdo'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid option\n\nclick \U0001F447 to re-select option', reply_markup=reply_markup)
return INVALID_OPTION #if invalid input and cannot find in resultsdict, revert by using INVALID_OPTION state to handle callbackquery sdo
print(resultsdict[selectedoption])
a = 'food' if maintype == 'food' else 'lift' if subtype == 'gym' else subtype
itemname = ', '.join(resultsdict[selectedoption][1].split(', ')[1:]) #split name string by entry and remove the type from name to recreate string without type
context.user_data['itemname'] = itemname
if a == 'food':
def get_mac_from_desc(description):
print(f'getting mac from {description}')
def get_p_from_desc(description):
p_pattern = 'P:.+g, F'
p_pattern2 = 'P:.+g,'
p_pattern3 = '\d.+\d'
match = re.search(p_pattern, description).group()
match2 = re.search(p_pattern2, match).group()
match3 = re.search(p_pattern3, match2).group()
return float(match3)
def get_c_from_desc(description):
c_pattern = 'C:.+g, P'
c_pattern2 = '\d.+\d'
match = re.search(c_pattern, description).group()
match2 = re.search(c_pattern2, match).group()
# print(match2)
return float(match2)
def get_f_from_desc(description):
f_pattern = 'F:.+g'
f_pattern2 = '\d.+\d'
match = re.search(f_pattern, description).group()
match2 = re.search(f_pattern2, match).group()
# print(match2)
return float(match2)
p = get_p_from_desc(description)
c = get_c_from_desc(description)
f = get_f_from_desc(description)
return c, p, f
servingsize = str(float(resultsdict[selectedoption][2]))
servingsizeunit = str(resultsdict[selectedoption][3])
context.user_data['ssvalue'] = servingsize
context.user_data['ssunit'] = servingsizeunit
cal = str(int(resultsdict[selectedoption][4]))
c, p, f = tuple([str(x) for x in get_mac_from_desc(resultsdict[selectedoption][5])])
context.user_data['cal'] = cal
context.user_data['cpf'] = ', '.join([c, p, f])
selected_message = f'you have selected {itemname}\n1 serving: {servingsize} {servingsizeunit}\n{cal} cal, c: {c}g, p: {p}g, f: {f}g'
rfq_message = f'enter servings \nor click \U0001F447 to select another option'
elif a == 'cardio' or a == 'sport':
mets = float(resultsdict[selectedoption][4])
user = update.message.from_user
username = verify_if_account_exists(user['id'], context, prin=False) #get username from viae and prevents message send
sql2 = f'SELECT date FROM tracking_{username}'
dates = [x[0] for x in execute_pgsql(sql2, fetchall=True)]
try:
dates.remove('default')
except:
pass
#find latest date
datetimes = []
for dead in dates:
dt = datetime.datetime.strptime(dead_string, "%d-%m-%Y")
datetimes.append(dt)
latestdateobject = max(datetimes)
latestdatestring = latestdateobject.strftime("%d-%m-%Y")
sql3 = f"SELECT weight from tracking_{username} WHERE date = '{latestdatestring}'"
weightpre = execute_pgsql(sql3, fetchone=True)
weight = float(weightpre[0]) if len(weightpre)==0 else 60.0
calsperhr = round(mets * float(weight) * 3.5 * 60 / 200)
selected_message = f'you have selected {itemname}\n60 mins, {calsperhr} cal'
context.user_data['cph'] = calsperhr
rfq_message = f'enter minutes of activity \nor click \U0001F447 to select another option'
elif a == 'lift':
sets = int(resultsdict[selectedoption][2])
if sets == 0.0: #check if sets have been set before (if not, it is untouched from basedata, if is, pb has been set before)
req_for_sets = f'enter the number of sets for {itemname} \n\nor click \U0001F447 to select another lift'
context.user_data['pb'] = 'false'
keyboard = [[InlineKeyboardButton(text="select different lift", callback_data='sdo'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=req_for_sets, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=req_for_sets, reply_markup=reply_markup)
return TYPING_SETS
else:
weight = str(float(resultsdict[selectedoption][3]))
reps = str(int(resultsdict[selectedoption][4]))
pb_string = f'you have set a pb for {itemname} before: \nsets: {sets}, weight: {weight}kg, reps: {reps}'
context.user_data['pb'] = 'true'
rfr_message = f'would you like to set a new pb?'
buttons = [
[
InlineKeyboardButton(text="yes", callback_data='yes'),
InlineKeyboardButton(text="no", callback_data='no'),
],
[
InlineKeyboardButton(text="select different lift", callback_data='sdo'),
],
]
keyboard = InlineKeyboardMarkup(buttons)
try:
await update.message.reply_text(text=pb_string)
await update.message.reply_text(text=rfr_message, reply_markup=keyboard)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=pb_string)
await context.bot.send_message(chat_id=update.effective_chat.id, text=rfr_message, reply_markup=keyboard)
return SELECTING_REPLACE
keyboard = [[InlineKeyboardButton(f"select another option", callback_data='sdo'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(selected_message)
await update.message.reply_text(rfq_message, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=selected_message)
await context.bot.send_message(chat_id=update.effective_chat.id, text=rfq_message, reply_markup=keyboard)
x = TYPING_QU4NTITY
print(f'returning {x}')
return x
async def temp_yesno_replace(update: Update, context):
print(update.callback_query.data)
itemname = context.user_data['itemname']
if update.callback_query.data == 'yes':
context.user_data['replace'] = 'true'
notstr = ' '
else:
notstr = ' not '
context.user_data['replace'] = 'false'
await update.callback_query.answer()
await update.callback_query.edit_message_text(f'you have selected{notstr}to replace pb for {itemname}')
req_for_sets = f'enter the number of sets for {itemname}\n\nor click \U0001F447 to select another lift'
keyboard = [[InlineKeyboardButton(text="select different lift", callback_data='sdo'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(chat_id=update.effective_chat.id,text=req_for_sets, reply_markup=reply_markup)
return TYPING_SETS
async def req_for_reps(update: Update, context):
try:
sets = int(update.message.text) #try to get sets input (text)
except:
try:
sets = context.user_data['sets'] #if sets has been set before i.e. backwards call from rfr:
except:
keyboard = [[InlineKeyboardButton(text="change sets", callback_data='cq'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid input\n\nclick \U0001F447 to re-enter sets', reply_markup=reply_markup)
return CHANGE_QUANTITY #if invalid input and cannot find sets, revert
context.user_data['sets'] = sets #save sets for future reference
itemname = context.user_data['itemname']
req_for_reps = f'enter reps per set for {itemname}, {sets} sets\n\nor click \U0001F447 to re-enter sets'
keyboard = [[InlineKeyboardButton(text="change sets", callback_data='cq'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=req_for_reps, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=req_for_reps, reply_markup=reply_markup)
return TYPING_REPS
async def req_for_weight(update: Update, context):
print(update.message.text)
try:
reps = int(update.message.text) #try to get reps input (from text message)
except:
try:
reps = context.user_data['reps'] #if reps have been set before i.e. backwards call from verify_weight:
except:
keyboard = [[InlineKeyboardButton(text="change reps", callback_data='cr'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid input\n\nclick \U0001F447 to re-enter sets', reply_markup=reply_markup)
return TYPING_WEIGHT #if invalid input and cannot find reps, revert
context.user_data['reps'] = reps #save reps for future reference
itemname = context.user_data['itemname']
sets = context.user_data['sets']
req_for_reps = f'enter weight (kg) for\n{itemname}, {sets} sets x {reps} reps\n\nor click \U0001F447 to re-enter sets'
keyboard = [[InlineKeyboardButton(text="change reps", callback_data='cr'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=req_for_reps, reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=req_for_weight, reply_markup=reply_markup)
return TYPING_WEIGHT
async def verify_weight(update: Update, context):
print('verify_weight', update.message.text)
try:
weight = float(update.message.text) #try to get weight input (from text message)
except:
keyboard = [[InlineKeyboardButton(text="change weight", callback_data='cw'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid input\n\nclick \U0001F447 to re-enter weight', reply_markup=reply_markup)
return CONFIRMING_WEIGHT #if invalid input and cannot find weight, revert to rfw
context.user_data['weight'] = weight #save weight for future reference
# itemname = context.user_data['itemname']
# sets = context.user_data['sets']
# weight = context.user_data['weight']
# liftstring = f'lift: {itemname}, {weight} kg x {sets} sets\n\n\nor click \U0001F447 to re-enter sets'
# req_for_date = f'enter reps for\n{itemname}, {weight} kg x {sets} sets\n\n\nor click \U0001F447 to re-enter sets'
keyboard = [[InlineKeyboardButton(text="confirm", callback_data='yes'), InlineKeyboardButton(text="change weight", callback_data='cw'), ]]
reply_markup = InlineKeyboardMarkup(keyboard)
try:
await update.message.reply_text(text=f'confirm weight: {weight} kg', reply_markup=reply_markup)
except:
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=f'confirm weight: {weight} kg', reply_markup=reply_markup)
return CONFIRMING_WEIGHT
async def process_lift(update:Update, context):
print('process_lift')
itemname = context.user_data['itemname']
searchid = context.user_data['searchid']
sets = context.user_data['sets']
weight = context.user_data['weight']
reps = context.user_data['reps']
title = context.user_data['activitytitle'] #persist
tempdict = context.user_data['tempdict'] #persist
pb = context.user_data['pb']
try:
replace = context.user_data['replace']
except:
replace = 'false'
print(itemname, sets, weight, reps, title, tempdict)
appendstring = '|'.join((str(searchid),str(itemname),str(sets),str(reps),str(weight),str(pb),str(replace))) #format a string to append to temp dict
print(appendstring)
tempdict.append(appendstring)
context.user_data['tempdict'] = tempdict #rewrite temp dict
shorteneditemname = ', '.join(itemname.split(', ')[:-1])
printstring = f'''{shorteneditemname}: {str(sets)}x{str(reps)} {weight} kg
{shorteneditemname} added to {title}'''
req_for_save = f'would you like to add another lift to {title}?'
keyboard = [[InlineKeyboardButton(text="add another lift", callback_data='gym'),],
[InlineKeyboardButton(text=f"done, save workout to activity log", callback_data='save'), ],]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.callback_query.answer()
await update.callback_query.edit_message_text(text=printstring)
await context.bot.send_message(chat_id=update.effective_chat.id, text=req_for_save, reply_markup=reply_markup)
return GYM_ADDORSAVE
async def process_quantity(update:Update, context):
try:
quantity = float(update.message.text)
context.user_data['quantity'] = quantity
except:
keyboard = [[InlineKeyboardButton(text="change quantity", callback_data='cq'),]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(text='invalid input\n\nclick \U0001F447 to re-enter quantity', reply_markup=reply_markup)
return SINGLE_ENTRY #if invalid input and cannot find weight, revert to rfq
maintype = context.user_data['maintype']
subtype = context.user_data['subtype']
itemname = context.user_data['itemname']
print(maintype)
if maintype == 'food':
try:
ssunit = context.user_data['ssunit']
ssvalue = context.user_data['ssvalue']
except Exception as e:
print(e)
await update.message.reply_text(text='error')
return END
ssvalue = float(context.user_data['ssvalue'])
calsperserving = float(context.user_data['cal'])
cps, pps, fps = [float(x) for x in context.user_data['cpf'].split(', ')]
cals = round(calsperserving * quantity)
c = round(cps * quantity)
p = round(pps * quantity)
f = round(fps * quantity)
#save calculated cals, cpf, for given quantity
context.user_data['calquan'] = cals
context.user_data['cpfquan'] = '|'.join([str(c), str(p), str(f)])
keyboard = [[InlineKeyboardButton(text="yes", callback_data='yes'), InlineKeyboardButton(text="no", callback_data='no'), ],
[InlineKeyboardButton(text="enter different quantity", callback_data='cq'),],]
reply_markup = InlineKeyboardMarkup(keyboard)