forked from whittlem/pycryptobot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_bot.py
1143 lines (942 loc) · 42.2 KB
/
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bot to reply to Telegram messages.
Usage:
Press Ctrl-C on the command line or send a signal to the process to stop the bot.
"""
import argparse
import logging
import os
import json
import subprocess
import platform
import re
import urllib.request
from time import sleep
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup
from telegram.bot import Bot, BotCommand
from telegram.ext import (
Updater,
CommandHandler,
CallbackQueryHandler,
Filters,
ConversationHandler,
MessageHandler,
)
from telegram.replykeyboardremove import ReplyKeyboardRemove
# from telegram.utils.helpers import DEFAULT_20
from models.chat import Telegram
# Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
CHOOSING, TYPING_REPLY = range(2)
EXCHANGE, MARKET, ANYOVERRIDES, OVERRIDES, SAVE, START = range(6)
reply_keyboard = [["Coinbase Pro", "Binance", "Kucoin"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
class TelegramBotBase:
"""
base level for telegram bot
"""
userid = ""
datafolder = os.curdir
data = {}
def _read_data(self, name: str = "data.json") -> None:
with open(
os.path.join(self.datafolder, "telegram_data", name), "r", encoding="utf8"
) as json_file:
self.data = json.load(json_file)
def _write_data(self, name: str = "data.json") -> None:
try:
with open(
os.path.join(self.datafolder, "telegram_data", name),
"w",
encoding="utf8",
) as outfile:
json.dump(self.data, outfile, indent=4)
except:
with open(
os.path.join(self.datafolder, "telegram_data", name),
"w",
encoding="utf8",
) as outfile:
json.dump(self.data, outfile, indent=4)
def _getoptions(self, callbacktag, state):
buttons = []
keyboard = []
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
for file in jsonfiles:
if ".json" in file and not file == "data.json":
self._read_data(file)
if callbacktag == "sell":
if "margin" in self.data:
if not self.data["margin"] == " ":
buttons.append(
InlineKeyboardButton(
file.replace(".json", ""),
callback_data=callbacktag + "_" + file,
)
)
elif callbacktag == "buy":
if "margin" in self.data:
if self.data["margin"] == " ":
buttons.append(
InlineKeyboardButton(
file.replace(".json", ""),
callback_data=callbacktag + "_" + file,
)
)
else:
if "botcontrol" in self.data:
if self.data["botcontrol"]["status"] == state:
buttons.append(
InlineKeyboardButton(
file.replace(".json", ""),
callback_data=callbacktag + "_" + file,
)
)
if len(buttons) > 0:
if len(buttons) > 1:
keyboard = [
[InlineKeyboardButton("All", callback_data=callbacktag + "_all")]
]
i = 0
while i <= len(buttons) - 1:
if len(buttons) - 1 >= i + 2:
keyboard.append([buttons[i], buttons[i + 1], buttons[i + 2]])
elif len(buttons) - 1 >= i + 1:
keyboard.append([buttons[i], buttons[i + 1]])
else:
keyboard.append([buttons[i]])
i += 3
keyboard.append([InlineKeyboardButton("Cancel", callback_data="cancel")])
return keyboard
def _checkifallowed(self, userid, update) -> bool:
if str(userid) != self.userid:
update.message.reply_text("<b>Not authorised!</b>", parse_mode="HTML")
return False
return True
class TelegramBot(TelegramBotBase):
"""
main telegram bot class
"""
def __init__(self):
self.token = ""
self.config_file = ""
self.cl_args = ""
self.market = ""
self.exchange = ""
self.pair = ""
self.overrides = ""
parser = argparse.ArgumentParser(description="PyCryptoBot Telegram Bot")
parser.add_argument(
"--config",
type=str,
dest="config_file",
help="pycryptobot config file",
default="config.json",
)
parser.add_argument(
"--datafolder",
type=str,
help="Use the datafolder at the given location, useful for multi bots running in different folders",
default="",
)
args = parser.parse_args()
self.config_file = args.config_file
with open(os.path.join(self.config_file), "r", encoding="utf8") as json_file:
self.config = json.load(json_file)
self.token = self.config["telegram"]["token"]
self.userid = self.config["telegram"]["user_id"]
if "datafolder" in self.config["telegram"]:
self.datafolder = self.config["telegram"]["datafolder"]
if not args.datafolder == "":
self.datafolder = args.datafolder
if not os.path.exists(os.path.join(self.datafolder, "telegram_data")):
os.mkdir(os.path.join(self.datafolder, "telegram_data"))
if os.path.isfile(os.path.join(self.datafolder, "telegram_data", "data.json")):
self._read_data()
if not "markets" in self.data:
self.data.update({"markets": {}})
self._write_data()
else:
ds = {"trades": {}}
self.data = ds
self._write_data()
self.updater = Updater(
self.token,
use_context=True,
)
def responses(self, update, context):
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
if query.data == "orders" or query.data == "pairs" or query.data == "allactive":
self.marginresponse(update, context)
elif query.data in ("binance", "coinbasepro", "kucoin"):
self.showconfigresponse(update, context)
elif "pause_" in query.data:
self.pausebotresponse(update, context)
elif "restart_" in query.data:
self.restartbotresponse(update, context)
elif "sell_" in query.data:
self.sellresponse(update, context)
elif "buy_" in query.data:
self.buyresponse(update, context)
elif "stop_" in query.data:
self.stopbotresponse(update, context)
elif "start_" in query.data:
self.startallbotsresponse(update, context)
elif "delete_" in query.data:
self.deleteresponse(update, context)
elif query.data == "cancel":
query.edit_message_text("User Cancelled Request")
# Define a few command handlers. These usually take the two arguments update and context.
def setcommands(self, update, context) -> None:
command = [
BotCommand("help", "show help text"),
BotCommand("margins", "show margins for all open trades"),
BotCommand("trades", "show closed trades"),
BotCommand("stats", "show exchange stats for market/pair"),
BotCommand("showinfo", "show all running bots status"),
BotCommand("showconfig", "show config for selected exchange"),
BotCommand("addnew", "add and start a new bot"),
BotCommand("deletebot", "delete bot from startbot list"),
BotCommand("startbots", "start all or selected bot"),
BotCommand("stopbots", "stop all or the selected bot"),
BotCommand("pausebots", "pause all or selected bot"),
BotCommand("restartbots", "restart all or selected bot"),
BotCommand("buy", "Manual buy"),
BotCommand("sell", "Manual sell"),
]
ubot = Bot(self.token)
ubot.set_my_commands(command)
update.message.reply_text(
"<i>Bot Commands Created</i>",
parse_mode="HTML",
reply_markup=ReplyKeyboardRemove(),
)
def help(self, update, context):
"""Send a message when the command /help is issued."""
helptext = "<b>Information Command List</b>\n\n"
helptext += (
"<b>/setcommands</b> - <i>add all commands to bot for easy access</i>\n"
)
helptext += "<b>/margins</b> - <i>show margins for open trade</i>\n"
helptext += "<b>/trades</b> - <i>show closed trades</i>\n"
helptext += "<b>/stats</b> - <i>display stats for market</i>\n"
helptext += "<b>/showinfo</b> - <i>display bot(s) status</i>\n"
helptext += "<b>/showconfig</b> - <i>show config for exchange</i>\n\n"
helptext += "<b>Interactive Command List</b>\n\n"
helptext += "<b>/addnew</b> - <i>start the requested pair</i>\n"
helptext += "<b>/pausebots</b> - <i>pause all or the selected bot</i>\n"
helptext += "<b>/restartbots</b> - <i>restart all or the selected bot</i>\n"
helptext += "<b>/stopbots</b> - <i>stop all or the selected bots</i>\n"
helptext += "<b>/startbots</b> - <i>start all or the selected bots</i>\n"
helptext += "<b>/sell</b> - <i>sell market pair on next iteration</i>\n"
helptext += "<b>/buy</b> - <i>buy market pair on next iteration</i>\n"
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(helptext, parsemode="HTML")
def showbotinfo(self, update, context) -> None:
"""Show running bot status"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
output = ""
for file in jsonfiles:
if ".json" in file and not file == "data.json":
self._read_data(file)
output = output + f"<b>{file.replace('.json', '')}</b> - "
output = (
output
+ f"<i>Current Status: {self.data['botcontrol']['status']}</i>\n"
)
if output != "":
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(output, parsemode="HTML")
def trades(self, update, context):
"""List trades"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
self._read_data()
output = ""
for time in self.data["trades"]:
output = ""
output = output + f"<b>{self.data['trades'][time]['pair']}</b>\n{time}"
output = (
output
+ f"\n<i>Sold at: {self.data['trades'][time]['price']} Margin: {self.data['trades'][time]['margin']}</i>\n"
)
if output != "":
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(output, parsemode="HTML")
def marginrequest(self, update, context):
"""Ask what user wants to see active order/pairs or all"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
keyboard = [
[
InlineKeyboardButton("Active Orders", callback_data="orders"),
InlineKeyboardButton("Active Pairs", callback_data="pairs"),
InlineKeyboardButton("All", callback_data="allactive"),
],
[InlineKeyboardButton("Cancel", callback_data="cancel")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("Make your selection", reply_markup=reply_markup)
def marginresponse(self, update: Updater, context):
"""Show current active orders/pairs or all margins or latest messages"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
openoutput = ""
closeoutput = ""
for file in jsonfiles:
if ".json" in file and not file == "data.json":
self._read_data(file)
if "margin" in self.data:
if self.data["margin"] == " ":
closeoutput = (
closeoutput + f"<b>{str(file).replace('.json', '')}</b>"
)
closeoutput = closeoutput + f"\n<i>{self.data['message']}</i>\n"
elif len(self.data) > 2:
openoutput = (
openoutput + f"<b>{str(file).replace('.json', '')}</b>"
)
openoutput = (
openoutput
+ f"\n<i>Current Margin: {self.data['margin']} (P/L): {self.data['delta']}</i>\n"
)
query = update.callback_query
if query.data == "orders":
query.edit_message_text(openoutput, parse_mode="HTML")
elif query.data == "pairs":
query.edit_message_text(closeoutput, parse_mode="HTML")
elif query.data == "allactive":
query.edit_message_text(openoutput, parse_mode="HTML")
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(closeoutput, parsemode="HTML")
def statsrequest(self, update: Updater, context):
"""Ask which exchange stats are wanted for"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
update.message.reply_text("Select the exchange", reply_markup=markup)
return CHOOSING
def stats_exchange_received(self, update, context):
"""Ask which market stats are wanted for"""
if update.message.text.lower() == "done":
return None
if update.message.text.lower() == "cancel":
update.message.reply_text(
"Operation Cancelled", reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
if update.message.text in ("Coinbase Pro", "Kucoin", "Binance"):
self.exchange = update.message.text.lower()
if update.message.text == "Coinbase Pro":
self.exchange = "coinbasepro"
else:
if self.exchange == "":
update.message.reply_text("Invalid Exchange Entered!")
self.statsrequest(update, context)
return None
update.message.reply_text(
"Which market/pair do you want stats for?",
reply_markup=ReplyKeyboardRemove(),
)
return TYPING_REPLY
def stats_pair_received(self, update, context):
"""Show stats for selected exchange and market"""
if update.message.text.lower() == "done":
return None
if update.message.text.lower() == "cancel":
update.message.reply_text(
"Operation Cancelled", reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
if self.exchange == "coinbasepro" or self.exchange == "kucoin":
p = re.compile(r"^[1-9A-Z]{2,5}\-[1-9A-Z]{2,5}$")
if not p.match(update.message.text):
update.message.reply_text(
"Invalid market format", reply_markup=ReplyKeyboardRemove()
)
self.stats_exchange_received(update, context)
return None
elif self.exchange == "binance":
p = re.compile(r"^[A-Z0-9]{5,12}$")
if not p.match(update.message.text):
update.message.reply_text(
"Invalid market format.", reply_markup=ReplyKeyboardRemove()
)
self.stats_exchange_received(update, context)
return None
self.pair = update.message.text
update.message.reply_text(
"<i>Gathering Stats, please wait...</i>", parse_mode="HTML"
)
output = subprocess.getoutput(
f"python3 pycryptobot.py --stats --exchange {self.exchange} --market {self.pair} "
)
update.message.reply_text(output, parse_mode="HTML")
return ConversationHandler.END
def sellrequest(self, update, context):
"""Manual sell request (asks which coin to sell)"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = self._getoptions("sell", "")
if len(buttons) > 0:
reply_markup = InlineKeyboardMarkup(buttons)
update.message.reply_text(
"<b>What do you want to sell?</b>",
reply_markup=reply_markup,
parse_mode="HTML",
)
else:
update.message.reply_text("No active bots found.")
def sellresponse(self, update, context):
"""create the manual sell order"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
self._read_data(query.data.replace("sell_", ""))
if "botcontrol" in self.data:
self.data["botcontrol"]["manualsell"] = True
self._write_data(query.data.replace("sell_", ""))
query.edit_message_text(
f"Selling: {query.data.replace('sell_', '').replace('.json','')}\n<i>Please wait for sale notification...</i>",
parse_mode="HTML",
)
def buyrequest(self, update, context):
"""Manual buy request (asks which coin to buy)"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = self._getoptions("buy", "")
if len(buttons) > 0:
reply_markup = InlineKeyboardMarkup(buttons)
update.message.reply_text(
"<b>What do you want to buy?</b>",
reply_markup=reply_markup,
parse_mode="HTML",
)
else:
update.message.reply_text("No active bots found.")
def buyresponse(self, update, context):
"""create the manual sell order"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
self._read_data(query.data.replace("buy_", ""))
if "botcontrol" in self.data:
self.data["botcontrol"]["manualbuy"] = True
self._write_data(query.data.replace("buy_", ""))
query.edit_message_text(
f"Buying: {query.data.replace('buy_', '').replace('.json','')}\n<i>Please wait for buy notification...</i>",
parse_mode="HTML",
)
def showconfigrequest(self, update, context):
"""display config settings (ask which exchange)"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
keyboard = []
for exchange in self.config:
if not exchange == "telegram":
keyboard.append(
[InlineKeyboardButton(exchange, callback_data=exchange)]
)
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text("Select exchange", reply_markup=reply_markup)
def showconfigresponse(self, update, context):
"""display config settings based on exchanged selected"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
with open(os.path.join(self.config_file), "r", encoding="utf8") as json_file:
self.config = json.load(json_file)
query = update.callback_query
pbot = self.config[query.data]["config"]
query.edit_message_text(query.data + "\n" + json.dumps(pbot, indent=4))
def pausebotrequest(self, update, context) -> None:
"""Ask which bots to pause"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = self._getoptions("pause", "active")
if len(buttons) > 0:
reply_markup = InlineKeyboardMarkup(buttons)
update.message.reply_text(
"<i>What do you want to pause?</i>",
reply_markup=reply_markup,
parse_mode="HTML",
)
else:
update.message.reply_text("No active bots found.")
def pausebotresponse(self, update, context):
"""Pause all or selected bot"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
if query.data == "pause_all":
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
for file in jsonfiles:
if ".json" in file and not file == "data.json":
if self.updatebotcontrol(file, "pause"):
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(
f"<i>Pausing {file.replace('.json','')}</i>", parsemode="HTML"
)
else:
if self.updatebotcontrol(query.data.replace("pause_", ""), "pause"):
update.message.reply_text(
f"<i>Pausing {query.data.replace('pause_', '').replace('.json','')}</i>",
parse_mode="HTML",
)
def restartbotrequest(self, update, context) -> None:
"""Ask which bot to restart"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = self._getoptions("restart", "paused")
if len(buttons) > 0:
reply_markup = InlineKeyboardMarkup(buttons)
update.message.reply_text(
"<b>What do you want to restart?</b>",
reply_markup=reply_markup,
parse_mode="HTML",
)
else:
update.message.reply_text("No paused bots found.")
def restartbotresponse(self, update, context):
"""restart selected or all bots"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
if query.data == "restart_all":
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
query.edit_message_text(f"Restarting all bots", parse_mode="HTML")
for file in jsonfiles:
if ".json" in file and not file == "data.json":
if self.updatebotcontrol(file, "start"):
mbot = Telegram(self.token, str(context._chat_id_and_data[0]))
mbot.send(
f"<i>Restarting {file.replace('.json','')}</i>",
parsemode="HTML",
)
else:
if self.updatebotcontrol(query.data.replace("restart_", ""), "start"):
query.edit_message_text(
f"Restarting {query.data.replace('restart_', '').replace('.json','')}",
parse_mode="HTML",
)
def startallbotsrequest(self, update, context) -> None:
"""Ask which bot to start from start list (or all)"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = []
keyboard = []
self._read_data()
for market in self.data["markets"]:
if not os.path.isfile(
os.path.join(self.datafolder, "telegram_data", market + ".json")
):
buttons.append(
InlineKeyboardButton(market, callback_data="start_" + market)
)
if len(buttons) > 0:
if len(buttons) > 1:
keyboard = [
[InlineKeyboardButton("All", callback_data="start_" + "_all")]
]
i = 0
while i <= len(buttons) - 1:
if len(buttons) - 1 >= i + 2:
keyboard.append([buttons[i], buttons[i + 1], buttons[i + 2]])
elif len(buttons) - 1 >= i + 1:
keyboard.append([buttons[i], buttons[i + 1]])
else:
keyboard.append([buttons[i]])
i += 3
keyboard.append([InlineKeyboardButton("Cancel", callback_data="cancel")])
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
"<b>What crypto bots do you want to start?</b>",
reply_markup=reply_markup,
parse_mode="HTML",
)
def startallbotsresponse(self, update, context) -> None:
"""start selected or all bots"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
self._read_data()
query = update.callback_query
if "all" in query.data:
query.edit_message_text("Starting all bots")
for pair in self.data["markets"]:
if not os.path.isfile(
os.path.join(self.datafolder, "telegram_data", pair + ".json")
):
overrides = self.data["markets"][pair]["overrides"]
if platform.system() == "Windows":
os.system(
f"start powershell -Command $host.UI.RawUI.WindowTitle = '{pair}' ; python3 pycryptobot.py {overrides}"
)
else:
subprocess.Popen(
f"python3 pycryptobot.py {overrides}", shell=True
)
mBot = Telegram(self.token, str(context._chat_id_and_data[0]))
mBot.send(f"<i>Starting {pair} crypto bot</i>", parsemode="HTML")
sleep(10)
else:
overrides = self.data["markets"][str(query.data).replace("start_", "")][
"overrides"
]
if platform.system() == "Windows":
os.system(
f"start powershell -Command $host.UI.RawUI.WindowTitle = '{query.data.replace('start_', '')}' ; python3 pycryptobot.py {overrides}"
)
# os.system(f"start powershell -NoExit -Command $host.UI.RawUI.WindowTitle = '{query.data.replace('start_', '')}' ; python3 pycryptobot.py {overrides}")
else:
subprocess.Popen(f"python3 pycryptobot.py {overrides}", shell=True)
query.edit_message_text(
f"<i>Starting {str(query.data).replace('start_', '')} crypto bots</i>",
parse_mode="HTML",
)
def stopbotrequest(self, update, context) -> None:
"""ask which active bots to stop (or all)"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
buttons = self._getoptions("stop", "active")
if len(buttons) > 0:
reply_markup = InlineKeyboardMarkup(buttons)
update.message.reply_text(
"<b>What do you want to stop?</b>",
reply_markup=reply_markup,
parse_mode="HTML",
)
else:
update.message.reply_text("No active bots found.")
def stopbotresponse(self, update, context) -> None:
"""stop all or selected bot"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return
query = update.callback_query
self._read_data()
if "all" in query.data:
query.edit_message_text("Stopping all bots")
jsonfiles = os.listdir(os.path.join(self.datafolder, "telegram_data"))
for file in jsonfiles:
if ".json" in file and not file == "data.json":
if self.updatebotcontrol(file, "exit"):
mBot = Telegram(self.token, str(context._chat_id_and_data[0]))
mBot.send(f"Stopping {file.replace('.json', '')} crypto bot")
else:
if self.updatebotcontrol(str(query.data).replace("stop_", ""), "exit"):
query.edit_message_text(
f"Stopping {str(query.data).replace('stop_', '').replace('.json', '')} crypto bot"
)
def newbot_request(self, update: Updater, context):
"""start new bot ask which exchange"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
self.exchange = ""
self.market = ""
self.overrides = ""
update.message.reply_text("Select the exchange:", reply_markup=markup)
return EXCHANGE
def newbot_exchange(self, update, context):
"""start bot validate exchange and ask which market/pair"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
if update.message.text.lower() == "cancel":
update.message.reply_text(
"Operation Cancelled", reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
if (
update.message.text == "Coinbase Pro"
or update.message.text == "Kucoin"
or update.message.text == "Binance"
):
self.exchange = update.message.text.lower()
if update.message.text == "Coinbase Pro":
self.exchange = "coinbasepro"
else:
if self.exchange == "":
update.message.reply_text("Invalid Exchange Entered!")
self.newbot_request(update, context)
return None
update.message.reply_text(
"Which market/pair is this for?", reply_markup=ReplyKeyboardRemove()
)
return ANYOVERRIDES
def newbot_any_overrides(self, update, context) -> None:
"""start bot validate market and ask if overrides required"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
if update.message.text.lower() == "cancel":
update.message.reply_text(
"Operation Cancelled", reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
if self.exchange == "coinbasepro" or self.exchange == "kucoin":
p = re.compile(r"^[1-9A-Z]{2,5}\-[1-9A-Z]{2,5}$")
if not p.match(update.message.text):
update.message.reply_text(
"Invalid market format", reply_markup=ReplyKeyboardRemove()
)
self.newbot_exchange(update, context)
return None
elif self.exchange == "binance":
p = re.compile(r"^[A-Z0-9]{5,12}$")
if not p.match(update.message.text):
update.message.reply_text(
"Invalid market format.", reply_markup=ReplyKeyboardRemove()
)
self.newbot_exchange(update, context)
return None
self.pair = update.message.text
reply_keyboard = [["Yes", "No"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
update.message.reply_text(
"Do you want to use any commandline overrides?", reply_markup=markup
)
return MARKET
def newbot_market(self, update, context):
"""start bot - ask for overrides if none required ask to save bot"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
if update.message.text == "No":
reply_keyboard = [["Yes", "No"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
update.message.reply_text("Do you want to save this?", reply_markup=markup)
return SAVE
update.message.reply_text(
"Tell me any other commandline overrides to use?",
reply_markup=ReplyKeyboardRemove(),
)
return OVERRIDES
def newbot_overrides(self, update, context):
"""start bot - ask to save bot"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
# Telegram desktop client can auto replace -- with a single long dash
# this converts it back to --
self.overrides = update.message.text.replace(
b"\xe2\x80\x94".decode("utf-8"), "--"
)
reply_keyboard = [["Yes", "No"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
update.message.reply_text("Do you want to save this?", reply_markup=markup)
return SAVE
def newbot_save(self, update, context):
"""start bot - save if required ask if want to start"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
if update.message.text == "Yes":
self._read_data()
if "markets" in self.data:
if not self.pair in self.data["markets"]:
self.data["markets"].update(
{
self.pair: {
"overrides": f"--exchange {self.exchange} --market {self.pair} {self.overrides}"
}
}
)
self._write_data()
update.message.reply_text(f"{self.pair} saved")
else:
update.message.reply_text(
f"{self.pair} already setup, no changes made."
)
else:
self.data.update({"markets": {}})
self.data["markets"].update(
{
self.pair: {
"overrides": f"--exchange {self.exchange} --market {self.pair} {self.overrides}"
}
}
)
self._write_data()
update.message.reply_text(f"{self.pair} saved")
reply_keyboard = [["Yes", "No"]]
markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True)
update.message.reply_text("Do you want to start this bot?", reply_markup=markup)
return START
def newbot_start(self, update, context) -> None:
"""start bot - start bot if want"""
if not self._checkifallowed(context._user_id_and_data[0], update):
return None
if update.message.text == "Yes":
if os.path.isfile(
os.path.join(self.datafolder, "telegram_data", f"{self.pair}.json")
):
update.message.reply_text(
"Bot is already running, no action taken.",
reply_markup=ReplyKeyboardRemove(),
)
elif platform.system() == "Windows":
# subprocess.Popen(f"python3 pycryptobot.py {overrides}", creationflags=subprocess.CREATE_NEW_CONSOLE)
os.system(
f"start powershell -Command $host.UI.RawUI.WindowTitle = '{self.pair}' ; python3 pycryptobot.py --exchange {self.exchange} --market {self.pair} {self.overrides}"
)
update.message.reply_text(
f"{self.pair} crypto bot Starting",
reply_markup=ReplyKeyboardRemove(),
)
else:
subprocess.Popen(
f"python3 pycryptobot.py --exchange {self.exchange} --market {self.pair} {self.overrides}",
shell=True,
)
update.message.reply_text(
f"{self.pair} crypto bot Starting",
reply_markup=ReplyKeyboardRemove(),
)
update.message.reply_text(
"Command Complete, have a nice day.", reply_markup=ReplyKeyboardRemove()
)
return ConversationHandler.END
def updatebotcontrol(self, market, status) -> bool:
"""used to update bot json files for controlling state"""
self._read_data(market)
if "botcontrol" in self.data:
self.data["botcontrol"]["status"] = status
self._write_data(market)
return True
return False
def error(self, update, context):
"""Log Errors"""
if "message" in context.error:
if "HTTPError" in context.error.message:
while self.checkconnection() == False:
logger.warning("No internet connection found")
self.updater.start_polling(poll_interval=30)
sleep(30)
self.updater.start_polling()
else:
logger.warning('Update "%s" caused error "%s"', update, context.error)
def done(self, update, context):
"""added for conversations to end"""
return ConversationHandler.END
def deleterequest(self, update, context):
"""ask which bot to delete"""