-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtrade_telegram_bot.py
1641 lines (1314 loc) · 63.3 KB
/
trade_telegram_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
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
# ################################################################
from datetime import datetime, timedelta
from telegram import LabeledPrice, ShippingOption
from backend.operations.binance import getAllOpenOrderSymbol, getAllOpenOrders, getAllOpenPositions
from backend.operations.bot import sendAdminMessages
from backend.operations.db import checkSubscriptionStatus, dbupdate
from backend.utils.binance.client import Client as BinanceSpotClient
from backend.utils import security
from backend.models import BotConfigsModel
from config import Config
from db import db
from app import app
import json
###################################################################
import logging
from multiprocessing import Process, Pipe
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, Update
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
ConversationHandler,
CallbackQueryHandler,
CallbackContext,
PreCheckoutQueryHandler
)
########################################################################
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
# State definitions for top level conversation
SELECTING_ACTION, ADDING_MEMBER, ADDING_SELF, DESCRIBING_SELF = map(chr, range(4))
# State definitions for second level conversation
SELECTING_LEVEL, SELECTING_GENDER, SELECTING_TRADE = map(chr, range(4, 7))
# State definitions for descriptions conversation
SELECTING_FEATURE, SELECTING_FEATURE1, SELECTING_FEATURE2, SELECTING_FEATURE3,SELECTING_FEATURE4, TYPING, TYPING1, TYPING2, TYPING3 = map(chr, range(7, 16))
# Meta states
STOPPING, SHOWING = map(chr, range(16, 18))
# Shortcut for ConversationHandler.END
END = ConversationHandler.END
# own settings
ENDMANUAL = map(chr, range(18, 19))
# Different constants for this example
(
PARENTS,
CHILDREN,
NEIGHBORS,
FOREIGNERS,
SELF,
GENDER,
MALE,
FEMALE,
AUTOMATED,
COPYTRADE,
SETTINGS,
SHOW_SETTINGS,
WEBHOOK,
WEBHOOKR,
AGE,
NAME,
SUBSCRIPTIONS,
BUYETH,
BUYEOS,
BUYXRP,
SELLETH,
SELLEOS,
SELLXRP,
LEVERAGE,
CLOSE,
POSITION,
START_OVER,
FEATURES,
CURRENT_FEATURE,
CURRENT_LEVEL,
TAKEPROFIT,
STOPLOSS,
AMOUNTSETTING,
TRAILINGSTOP,
NEWTRAILINGACTIVE,
LEVERAGESETTING,
CSUBSCRIPTION,
CONNECT,
DISCONNECT
) = map(chr, range(19, 58))
global telegram_id
global first_name
global second_name
telegram_id = ''
first_name = ''
second_name = ''
bot_token =Config.BOT_TOKEN
update1 = {}
print("------------UPDATE 1- INIT----------------", update1)
callback1 = {}
print("------------CALLBACK 1---INIT--------------", callback1)
# return all the user details to avoid crushes in multisking
def getUserDetails(update: Update, context: CallbackContext) -> None:
if update.callback_query == None:
user = update.message.from_user
print(user)
global telegram_id, first_name
telegram_id = user.id
first_name = user.first_name
second_name = user.last_name
if update.callback_query != None:
print("update---------------------------------------", update)
user = update.callback_query.message.chat
print('-------------------------------', user)
telegram_id = user.id
first_name = user.first_name
second_name = user.last_name
print('first name...............',first_name)
if first_name == 'None' or first_name == None:
first_name = ''
if second_name == 'None' or second_name == None:
second_name = ''
return user, telegram_id, first_name, second_name
# Top level contversation callbacks
def start(update: Update, context: CallbackContext) -> None:
global update1
global callback1
update1 = update
callback1 = CallbackContext
print('update1',update1)
print('callback1', callback1)
adm_message="Started the bot"
user, telegram_id, first_name, second_name = getUserDetails(update, context)
# sending starting bot message
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
logger.info("User %s started the conversation.", first_name)
print('telegram id------ ', telegram_id)
"""Select an action: Adding parent/child or show data."""
text = (
'Ensure you have been validated using your Binance API Key and Secret'
)
buttons = [
[
InlineKeyboardButton(text='Select Exchange', callback_data=str(ADDING_MEMBER)),
# InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Done', callback_data=str(END))
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we're starting over we don't need do send a new message
if context.user_data.get(START_OVER):
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# update1.message.reply_text(text=text, reply_markup=keyboard)
else:
update.message.reply_text(
'Hello, Welcome to Binance premium trading bot. If you do not have a binance account use the the link below to open account with binance\n'
'https://accounts.binance.me/en/register?ref=29337156\n\n'
'After opening an account with binance use the link below to create your api key and secret \n'
'https://www.binance.com/en/my/settings/api-management\n\n'
'On the same window where there is Api key and secret are generated, look for Edit button and click it,then look for an option✅ to enable futures option and click it by ticking the box on top and click SAVE.\n\n'
'If you do not save you wont be able to trade\n\n'
'REMEMBER TO TRANFER YOUR DEPOSIT FROM EITHER FUNDING OR SPOT ACCOUNT TO FUTURE ACCOUNT\n\n'
'After copying the API key and secret click select Exchange, Binance Futures then APi Data buttons, capture the keys on the Api key and Api secret buttons on the bot then click Done\n\n'
'Click Trading Signals, subscriptions select free plan and the proceed to set Amount and Leverage\n\n'
'WAIT FOR PROFITABLE SIGNALS TO DO THE MAGIC\n\n'
'TO CONNECT OR DISCONNECT THE BOT FROM EXECUTING THE ORDERS, Navigate through the trading signals button to access the connect and disconnect buttons'
)
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_ACTION
def adding_self(update: Update, context: CallbackContext) -> None:
context.user_data[CURRENT_LEVEL] = SELF
text = 'By verifying your API keys you accept you are using this bot at your own risk!'
button = InlineKeyboardButton(text='API DATA', callback_data=str(MALE))
keyboard = InlineKeyboardMarkup.from_button(button)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return DESCRIBING_SELF
def verifyApiData(update: Update, context: CallbackContext, level, user_data):
key = ''
text = 'Null'
text_except = ''
text_if1 = ''
text_if2 = ''
buy = ''
sell = ''
secret = ''
bot_token =Config.BOT_TOKEN
user, telegram_id, first_name, second_name = getUserDetails(update, context)
vvery12 = telegram_id
for person in user_data[level]:
# people = user_data.get(level)
#the below code doesn't execute settings, just bad naming. It executes BTC Orders
if person[GENDER] == MALE: #Executes Binance Trading. I suppose this has changed to TRADE BTC
# gender = female
text += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
api_key =f"{person.get(NAME, '-')}"
api_secret = f"{person.get(AGE, '-')}"
bsclient = BinanceSpotClient(api_key=api_key, api_secret=api_secret)
try:
account_balance = bsclient.get_asset_balance("BTC")
print("account balance", account_balance)
with app.app_context():
print("here-------------------------------------------------------")
exists = bool(db.session.query(BotConfigsModel).filter_by(telegram_id = str(telegram_id)).first())
print("existance", exists)
if exists:
db.session.query(BotConfigsModel).filter_by(telegram_id=str(telegram_id)).update({"key":api_key, "secret":api_secret})
db.session.commit()
print('Telegram Data Updated')
text1 =' Your New Data has been updated \n '
text2 = ' Your Binance data has been Verified too. You can proceed and start trading \n'
text3 ='Binance ID is valid \n \n'
'You can proceed to swap trading'
# update.callback_query.edit_message_text(text=(text1 + text2 + text3))
# update.callback_query.edit_message_text(text='Type /stop to restart bot and start Trading')
textp = text1 + text2 + text3
vvery12 = telegram_id
bot_message = 'Telegram ID ' ''+ str(vvery12) +'' ' \n \n '
' Name ' + first_name + ' ' + second_name + '\n \n'
'Sir Name ' ''+ second_name +'' ' \n \n '
' *User has updated their API key and Secret* ' '\n \n'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + '1093054762' + '&parse_mode=Markdown&text=' + bot_message
#https://api.telegram.org/botAAEXuaj6a029wmrNBnOCSFpPadIWga7KOBk/sendMessage?chat_id=1093054762&parse_mode=Markdown&text=atomatedtradingview
# response = requests.get(send_text)
adm_message = "Updated their API key and Secret successfully"
user, telegram_id, first_name, second_name = getUserDetails(update, context)
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
# send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + str(telegram_id) + '&parse_mode=Markdown&text=' + bot_message
# response = requests.get(send_text)
# select_level(update, context)
# text_if1 = text1 + text2 + text3
else:
print("am executing the false function @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
todo = BotConfigsModel.create(telegram_id=telegram_id,key=api_key,secret=api_secret)
db.session.commit()
print('Telegram Table Create Result')
print(todo)
print('__________________________________________________________')
text1 = 'Your data has been captured \n'
text2 = 'Your Binance data has been Verified. You can proceed and start trading \n'
text3 = 'Binance ID is valid, you can proceed to trading \n'
# update.callback_query.edit_message_text(text=(text1 + text2 + text3))
# update.callback_query.edit_message_text(text='Type /stop to restart bot and Verify your keys afresh')
textp = text1 + text2 + text3
bot_message = 'Telegram ID ' ''+ str(vvery12) +'' ' \n \n '
' Name ' + first_name + ' ' + second_name + '\n \n'
'Sir Name ' ''+ second_name +'' ' \n \n '
' *User has Captured and Validated their API key and Secret for the first time* ' '\n \n'
send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + '1093054762' + '&parse_mode=Markdown&text=' + bot_message
#https://api.telegram.org/botAAEXuaj6a029wmrNBnOCSFpPadIWga7KOBk/sendMessage?chat_id=1093054762&parse_mode=Markdown&text=atomatedtradingview
# response = requests.get(send_text)
adm_message = "*User has Captured and Validated their API key and Secret for the first time*"
user, telegram_id, first_name, second_name = getUserDetails(update, context)
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
except:
text1 = ' Your Binance API Data is incorrect. Confirm they are correct. \n'
text2 = 'Visit https://www.binance.com/en/my/settings/api-management to get keys \n'
text3 = 'please verify your Binance keys before proceeding to trade.\n'
textp = text1 + text2 + text3
adm_message = "Added incorrect keys"
user, telegram_id, first_name, second_name = getUserDetails(update, context)
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
return textp
def swapTrade(update: Update, context: CallbackContext, level, user_data):
key = ''
text = 'Null'
text_except = ''
text_if1 = ''
text_if2 = ''
buy = ''
sell = ''
secret = ''
bot_token =Config.BOT_TOKEN
user, telegram_id, first_name, second_name = getUserDetails(update, context)
vvery12 = telegram_id
for person in user_data[level]:
# people = user_data.get(level)
#the below code doesn't execute settings, just bad naming. It executes BTC Orders
if person[GENDER] == FEMALE: #Executes Binance Trading. I suppose this has changed to TRADE BTC
# gender = female
swap_payload =f"{person.get(NAME, '-')}"
print(swap_payload)
if swap_payload == "":
textp = "Invalid message"
else:
try:
json.loads(swap_payload)
with app.app_context():
bclient = dbOperations.getBinaceClient(str(telegram_id))
textp = binaceSwapOperations.performSwap(bclient, json.loads(swap_payload))
except:
textp = "Invalid Swap message format"
return textp
def handleTradingSignals(user_data, level):
people = user_data.get(level)
text=''
if not people:
return '\nNo information yet.'
if level == SELF:
for person in user_data[level]:
text += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
if level == CHILDREN:
for person in user_data[level]:
if person[GENDER] == COPYTRADE:
person.get(NAME, None),
person.get(AGE, None)
return text
def show_data(update: Update, context: CallbackContext) -> str:
"""Pretty print gathered data."""
"""Pretty print gathered data."""
print("The execution is still on show data")
textp = "djhsofddu"
bot_token =Config.BOT_TOKEN
user, telegram_id, first_name, second_name = getUserDetails(update, context)
user_data = context.user_data
bot_chatID = str(telegram_id)
user_data = context.user_data
print(user_data, "USER DATA")
#text = 'Yourself:' + prettyprint(user_data, SELF)
# print(' prettyprint(user_data, PARENTS)' ,prettyprint(user_data, PARENTS))
print('PARENTS DATA')
print('parents data here')
print(PARENTS)
level = context.user_data[CURRENT_LEVEL]
print("the level", level)
if level == SELF:
textp = verifyApiData(update, context, level, user_data)
user_data.clear()
user_data[START_OVER] = True
print("------------CALLBACK 1---END START--------------", callback1)
print("------------UPDATE 1- END START----------------", update1)
buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=textp, reply_markup=keyboard)
return SHOWING
if level==CHILDREN:
people = user_data.get(level)
for person in user_data[level]:
if person[GENDER] == MALE:
textp = verifyApiData(update, context, level, user_data)
user_data.clear()
user_data[START_OVER] = True
print("------------CALLBACK 1---END START--------------", callback1)
print("------------UPDATE 1- END START----------------", update1)
# buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]]
# keyboard = InlineKeyboardMarkup(buttons)
# update.callback_query.answer()
# update.callback_query.edit_message_text(text=textp, reply_markup=keyboard)
if person[GENDER]==COPYTRADE:
amount = person.get(AGE, None)
leverage =person.get(LEVERAGE, None)
with app.app_context():
status, subscription_type =checkSubscriptionStatus(telegram_id)
if status==False:
textp = "Update declined, You have no active subscription"
else:
textp=''
if amount is not None:
try:
float(amount)
dbupdate(telegram_id,{'amount':amount})
textp+="Amount updated successifully\n"
except Exception as e:
textp += "Invalid amount, try again\n"
if leverage is not None:
try:
int(leverage)
dbupdate(telegram_id,{'leverage':leverage})
textp+="Leverage updated successifully\n"
except Exception as e:
textp += "Invalid leverage, try again\n"
if textp=='':
textp="No Entry provided"
adm_message = textp
user, telegram_id, first_name, second_name = getUserDetails(update, context)
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
buttons = [[InlineKeyboardButton(text='Back', callback_data=str(END))]]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=textp, reply_markup=keyboard)
textp=''
return SHOWING
else:
print("The level", level)
select_level(update, context)
def stop(update: Update, context: CallbackContext) -> None:
"""End Conversation by command."""
update.message.reply_text('Okay, bye.')
update.message.reply_text('Type, /start to restart bot.')
adm_message = "Stopped the bot"
user, telegram_id, first_name, second_name = getUserDetails(update, context)
sendAdminMessages(first_name, second_name,telegram_id,adm_message)
context.user_data[START_OVER] = False
return END
def end(update: Update, context: CallbackContext) -> None:
"""End conversation from InlineKeyboardButton."""
update.callback_query.answer()
text = 'See you around!'
update.callback_query.edit_message_text(text=text)
update.callback_query.edit_message_text(text = 'Type, /start to restart bot.')
# update.message.reply_text('Type, /start to restart bot.')
return END
# def select_gender(update: Update, context: CallbackContext) -> None:
# update1 = update
# callback1 = CallbackContext
# """Choose to add mother or father."""
# level = update.callback_query.data
# context.user_data[CURRENT_LEVEL] = level
# text = 'Please select a option to continue'
# if level == PARENTS or level == CHILDREN or level == SELF or level == NEIGHBORS or level == FOREIGNERS:
# buttons = [
# # [
# # InlineKeyboardButton(text= male, callback_data=str(MALE)),
# # ],
# [
# InlineKeyboardButton(text= female, callback_data=str(FEMALE)),
# InlineKeyboardButton(text= automated, callback_data=str(AUTOMATED)),
# ],
# [
# InlineKeyboardButton(text= settings, callback_data=str(SETTINGS)),
# # InlineKeyboardButton(text= show_settings, callback_data=str(SHOW_SETTINGS)),
# ],
# [
# # InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
# InlineKeyboardButton(text='Back', callback_data=str(END)),
# ],
# ]
# keyboard = InlineKeyboardMarkup(buttons)
# update.callback_query.answer()
# update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# return SELECTING_GENDER
def _name_switcher(level):
if level == PARENTS:
return 'API DATA', 'Manual Trading', 'Automated Trading','Trading Signals'
if level == CHILDREN:
return 'API DATA', 'Manual Trading', 'Automated Trading', 'Trading Signals'
def select_gender(update: Update, context: CallbackContext) -> None:
"""Choose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please select a option to continue'
male, female, automated, copy_trade = _name_switcher(level)
buttons = [
[
InlineKeyboardButton(text= male, callback_data=str(MALE)),
],
# [
# InlineKeyboardButton(text= female, callback_data=str(FEMALE)),
# InlineKeyboardButton(text= automated, callback_data=str(AUTOMATED)),
# ],
[
InlineKeyboardButton(text= copy_trade, callback_data=str(COPYTRADE)),
],
[
InlineKeyboardButton(text='Back', callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_GENDER
# Second level conversation callbacks
# Second level conversation callbacks
def select_level(update: Update, context: CallbackContext) -> None:
"""Choose to add a parent or a child."""
text = 'You can perform sell, buy operations or automated trades. To proceed select an option'
buttons = [
[
# InlineKeyboardButton(text='Binance Spot', callback_data=str(PARENTS)),
InlineKeyboardButton(text='Binance Futures', callback_data=str(CHILDREN)),
],
[
InlineKeyboardButton(text='Back', callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_LEVEL
def get_all_swaps(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Cselect_genderhoose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please select a option to continue'
# all the swap operations here
user, telegram_id, first_name, second_name = getUserDetails(update, context)
# with app.app_context():
# bcient =dbOperations.getBinaceClient(str(telegram_id))
# all_swaps = binaceSwapOperations.getAllSWaps(bcient)
# print(all_swaps)
# text = all_swaps[:10]
# text = json.dumps(text, indent=2)
buttons = [
# [
# InlineKeyboardButton(text= male, callback_data=str(MALE)),
# ],
[
InlineKeyboardButton(text= " Manual Swap", callback_data=str(FEMALE)),
InlineKeyboardButton(text= "Automated Swaps", callback_data=str(AUTOMATED))
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
return SELECTING_GENDER
def request_swap(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Cselect_genderhoose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please select a option to continue'
# all the swap operations here
buttons = [
[
# InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Back', callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text="request swap", reply_markup=keyboard)
return SELECTING_GENDER
def perform_swap(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Cselect_genderhoose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please select a option to continue'
# perform swap operations here
buttons = [
[
# InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Back', callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text="perform swap", reply_markup=keyboard)
return SELECTING_GENDER
def get_swap_history(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Cselect_genderhoose to add mother or father."""
level = update.callback_query.data
context.user_data[CURRENT_LEVEL] = level
text = 'Please select a option to continue'
# all the swap history operations here
user, telegram_id, first_name, second_name = getUserDetails(update, context)
with app.app_context():
user = db.session.query(Telegram).filter_by(telegramid=str(telegram_id)).first()
if user == None or user.verified !="Yes":
res = "Your api data are not authentic, verify your Binance keys to continue using this bot."
else:
with app.app_context():
bsclient= dbOperations.getBinaceClient(str(telegram_id))
res = binaceSwapOperations.getSwapHistory(bsclient)
buttons = [
[
# InlineKeyboardButton(text='Show data', callback_data=str(SHOWING)),
InlineKeyboardButton(text='Back', callback_data=str(END)),
],
]
keyboard = InlineKeyboardMarkup(buttons)
update.callback_query.answer()
update.callback_query.edit_message_text(text=res, reply_markup=keyboard)
return SELECTING_GENDER
def end_second_level(update: Update, context: CallbackContext) -> None:
"""Return to top level conversation."""
context.user_data[START_OVER] = True
print('update1',update1)
print('callback1', callback1)
start(update, context)
return END
# Third level callbacks
def select_feature(update: Update, context: CallbackContext) -> None:
"""Select a feature to update for the person."""
update1 = update
callback1 = CallbackContext
buttons = [
[
InlineKeyboardButton(text='Api Key', callback_data=str(NAME)),
InlineKeyboardButton(text='Api Secret', callback_data=str(AGE)),
InlineKeyboardButton(text='Done', callback_data=str(END)),
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'Please select a feature to update.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a feature to update.'
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE
# def select_feature1(update: Update, context: CallbackContext) -> None:
# """Select a feature to update for the person."""
# update1 = update
# callback1 = CallbackContext
# buttons = [
# [
# InlineKeyboardButton(text='Continue', callback_data=str(NAME)),
# ]
# ]
# keyboard = InlineKeyboardMarkup(buttons)
# # If we collect features for a new person, clear the cache and save the gender
# if not context.user_data.get(START_OVER):
# context.user_data[FEATURES] = {GENDER: update.callback_query.data}
# text = 'To perform swap trade\n 1. Copy and paste the swap trade message \n 2. Edit the message to your preferred the your quoteAsset,baseAsset and Quantity\n 3. click continue to perform swap trade'
# update.callback_query.answer()
# update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# # But after we do that, we need to send a new message
# else:
# text = 'Got it! Please select a feature to update.'
# update.message.reply_text(text=text, reply_markup=keyboard)
# context.user_data[START_OVER] = False
# return SELECTING_FEATURE1
# Third level callbacks
def select_feature1(update: Update, context: CallbackContext) -> None:
"""Select a feature to update for the person."""
buttons = [
[
InlineKeyboardButton(text='Buy', callback_data=str(NAME)),
InlineKeyboardButton(text='Sell', callback_data=str(AGE)),
],
[
InlineKeyboardButton(text='Leverage', callback_data=str(LEVERAGE)),
InlineKeyboardButton(text='Close', callback_data=str(CLOSE)),
],
[
InlineKeyboardButton(text='Position', callback_data=str(POSITION)),
InlineKeyboardButton(text='Done', callback_data=str(END)),
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'Please select a operation to perform.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a operation to perform.'
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE1
def select_feature2(update: Update, context: CallbackContext) -> None:
"""Select a feature to update for the person."""
update1 = update
callback1 = CallbackContext
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'select operation'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a feature to update.'
update.message.reply_text(text=text)
context.user_data[START_OVER] = False
return SELECTING_FEATURE2
def select_feature3(update: Update, context: CallbackContext) -> None:
"""Select a feature to update for the person."""
buttons = [
[
InlineKeyboardButton(text='Subscriptions', callback_data=str(SUBSCRIPTIONS)),
],
[
InlineKeyboardButton(text='Connect', callback_data=str(CONNECT)),
InlineKeyboardButton(text='Disconnect', callback_data=str(DISCONNECT)),
],
[
InlineKeyboardButton(text='set amount', callback_data=str(AGE)),
InlineKeyboardButton(text='set Leverage', callback_data=str(LEVERAGE))
],
[
InlineKeyboardButton(text='check Positions', callback_data=str(POSITION)),
InlineKeyboardButton(text='check Orders', callback_data=str(NAME)),
],
[
InlineKeyboardButton(text='Close', callback_data=str(CLOSE)),
],
[
InlineKeyboardButton(text='Done', callback_data=str(END)),
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'Please select a operation to perform.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a operation to perform.'
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE3
def ask_for_input(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Prompt user to input data for selected feature."""
context.user_data[CURRENT_FEATURE] = update.callback_query.data
text = 'Okay, tell me.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text)
return TYPING
def ask_for_input1(update: Update, context: CallbackContext) -> None:
update1 = update
callback1 = CallbackContext
"""Prompt user to input data for selected feature."""
context.user_data[CURRENT_FEATURE] = update.callback_query.data
text = 'update feature'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text)
return TYPING1
def select_feature_sub3(update: Update, context: CallbackContext):
"""Select a feature to update for the person."""
update1 = update
callback1 = CallbackContext
buttons = [
[
# InlineKeyboardButton(text='Check subscription', callback_data=str(CSUBSCRIPTION)),
InlineKeyboardButton(text='Plans', callback_data=str(NAME))
],
[
InlineKeyboardButton(text='Free Trial', callback_data=str(AGE))
],
# [
# # InlineKeyboardButton(text='Link bot', callback_data=str(CSUBSCRIPTION)),
# # InlineKeyboardButton(text='Unlink bot', callback_data=str(NAME))
# ]
[
InlineKeyboardButton(text='Back', callback_data=str(END)),
]
]
keyboard = InlineKeyboardMarkup(buttons)
# If we collect features for a new person, clear the cache and save the gender
if not context.user_data.get(START_OVER):
context.user_data[FEATURES] = {GENDER: update.callback_query.data}
text = 'Please select a feature to update.'
update.callback_query.answer()
update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
# But after we do that, we need to send a new message
else:
text = 'Got it! Please select a feature to update.'
update.message.reply_text(text=text, reply_markup=keyboard)
context.user_data[START_OVER] = False
return SELECTING_FEATURE4
def start_without_shipping_callback(update: Update, context: CallbackContext) -> None:
"""Sends an invoice without shipping-payment."""
user, telegram_id, first_name, second_name = getUserDetails(update, context)
chat_id = telegram_id
title = "Trading Signal"
description = "Payment for Binance automated trading signals"
# select a payload just for you to recognize its the donation from your bot
payload = "Custom-Payload"
# In order to get a provider_token see https://core.telegram.org/bots/payments#getting-a-token
provider_token = "284685063:TEST:YjBiNjE5YTQ0YWZm"
currency = "USD"
# price in dollars
price = 15
# price * 100 so as to include 2 decimal points
prices = [LabeledPrice("Starter", price * 100)]
# optionally pass need_name=True, need_phone_number=True,
# need_email=True, need_shipping_address=True, is_flexible=True
context.bot.send_invoice(
chat_id, title, description, payload, provider_token, currency, prices
)
# after (optional) shipping, it's the pre-checkout
def precheckout_callback(update: Update, context: CallbackContext) -> None:
"""Answers the PreQecheckoutQuery"""
query = update.pre_checkout_query
# check the payload, is this from your bot?
if query.invoice_payload != 'Custom-Payload':
# answer False pre_checkout_query
query.answer(ok=False, error_message="Something went wrong...")
else:
query.answer(ok=True)