-
Notifications
You must be signed in to change notification settings - Fork 2
/
bot.py
1421 lines (1186 loc) · 55.7 KB
/
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
import sys
import traceback
import asyncio
from threading import Thread
import json
import decimal
import math
import time
from decimal import Decimal
import logging
import requests
import telebot
from sqlalchemy import exc
from telebot import types
import database
from cfg import *
import cr_utils
class Callback:
callback_funcs = {}
inline_messages = {}
sti = {}
def __init__(self):
pass
def register_callback(self, message, func, *args):
self.delete_old_inline(message.chat.id)
key = str(message.chat.id) + str(message.id)
self.callback_funcs[key] = [func, args]
self.inline_messages[message.chat.id] = message.id
def run_callback(self, call, data):
bot.answer_callback_query(call.id)
bot.delete_message(call.message.chat.id, call.message.id)
key = str(call.message.chat.id) + str(call.message.id)
try:
func, args = self.callback_funcs[key]
except KeyError:
return
func(call, data, *args)
def delete_old_inline(self, uid):
if uid in self.inline_messages:
if self.inline_messages[uid]:
try:
bot.delete_message(uid, self.inline_messages[uid])
except:
pass
self.inline_messages[uid] = None
def delete_sti(self, uid):
if uid in list(self.sti.keys()):
if self.sti[uid]:
try:
bot.delete_message(uid, self.sti[uid])
except:
self.sti[uid] = None
def send_sti(self, uid, path):
self.sti[uid] = bot.send_sticker(uid, open(path, "rb")).id
db = database.Handler()
cb = Callback()
bot = telebot.TeleBot(BOT_TOKEN)
cr_utils.save_escrow_chats()
logging.basicConfig(format='%(asctime)s --- %(message)s \n', level=logging.WARNING, filename='log.txt')
# admin commands
@bot.message_handler(commands=["id"])
def check_id(message):
bot.reply_to(message, message.chat.id)
@bot.message_handler(commands=["rate"])
def rate(message):
if not (message.from_user.username in ADMINS and message.chat.id == RATE_CHANGE_CHAT_ID):
return
try:
_, fiat_name, buy_rate, sell_rate = message.text.split(" ")
except ValueError:
bot.reply_to(message, "Ошибка форматирования")
return
cr_utils.update_fiat_rates(fiat_name, buy_rate, sell_rate)
bot.reply_to(message, "Курс обновлен")
@bot.message_handler(commands=["balance"])
def balance_admin(message=None):
if message:
if message.chat.id != WALLET_CHAT_ID:
return
sys_bal = db.count_system_balances()
bin_bal = cr_utils.get_bin_balance()
msg = "Общий баланс пользователей:\n"
for val, bal in zip(sys_bal.keys(), sys_bal.values()):
msg += f"{bal} {val}; "
msg += "\nБаланс binance:\n"
for val, bal in zip(bin_bal.keys(), bin_bal.values()):
msg += f"{bal} {val}; "
bot.send_message(WALLET_CHAT_ID, msg)
@bot.message_handler(commands=["users"])
def users_admin(message):
if message.chat.id != WALLET_CHAT_ID:
return
users = db.get_users()
msg = ""
for user in users:
balances = user.balance
msg += f"{user.first_name} - {('@' + user.username) if user.username else ''} ({user.id}): {'; '.join([str(bal.amount) + ' ' + bal.currency for bal in balances])}\n"
bot.send_message(WALLET_CHAT_ID, msg)
@bot.message_handler(commands=["user"])
def user_admin(message):
if message.chat.id != WALLET_CHAT_ID:
return
user_id = message.text.split(" ")[-1]
try:
if "@" in user_id:
user = db.get_user(username=user_id.replace("@", ""))
else:
user = db.get_user(tg_id=int(user_id))
except exc.NoResultFound:
msg = "Пользователь не найден"
except ValueError:
msg = "Ошибка форматирования"
else:
msg = f"{user.first_name} - {('@' + user.username) if user.username else ''} ({user.id}): {'; '.join([str(bal.amount) + ' ' + bal.currency for bal in user.balance])}"
rate_ = (user.sum_rate / user.exchanges if user.exchanges else 0)
msg += f"\n{user.exchanges} завершенных обменов, средний рейтинг - {rate_:.1f}\n"
msg += f"Язык - {user.lang}"
bot.send_message(WALLET_CHAT_ID, msg)
@bot.message_handler(commands=["add_escrow_chat"])
def add_escrow(message):
chat = bot.get_chat(message.chat.id)
admins = bot.get_chat_administrators(message.chat.id)
admins = [admin.user.id for admin in admins]
bot_id = bot.send_message(chat.id, "Проверка...").from_user.id
if bot_id in admins:
bot.send_message(chat.id, "Чат успешно добавлен")
cr_utils.save_escrow_chats(chat.id)
else:
bot.reply_to(message, f"Бот не является админом в {chat.first_name}, добавте и повторите.")
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
data = json.loads(call.data)
if "placeholder" in data:
return
cb.delete_sti(call.from_user.id)
cb.run_callback(call, data)
# start, menu and some starting funcs
@bot.message_handler(commands=["start"])
def start(message):
try:
db.create_user(message.from_user.id, message.from_user.username, DEFAULT_LANGUAGE, message.from_user.first_name)
except exc.IntegrityError:
main_menu(db.get_user(message.from_user.id))
else:
user = db.get_user(message.from_user.id)
select_language1(user, select_fiat1)
log(f"{user.username} впервые воспользовался ботом")
def select_language1(user, next_func):
message = bot.send_message(user.id, MSGS[user.lang]["ChooseLang"],
reply_markup=select_language_keyboard())
cb.register_callback(message, select_language2, next_func)
def select_language_keyboard():
k = types.InlineKeyboardMarkup()
langs = list(MSGS.keys())
icons = [lang["Icon"] for lang in list(MSGS.values())]
for lang, icon in zip(langs, icons):
k.add(types.InlineKeyboardButton(text=icon, callback_data=json.dumps({"lang": lang})))
return k
def select_language2(call, data, next_func):
lang = data["lang"]
user = db.get_user(call.from_user.id)
db.update_user(user.id, lang=lang)
bot.send_message(user.id, MSGS[user.lang]["LangUpdated"].format(lang))
user = db.get_user(call.from_user.id)
if next_func:
next_func(user)
def select_fiat1(user):
message = bot.send_message(user.id, MSGS[user.lang]["ChooseFiat"],
reply_markup=currencies_keyboard(FIAT_CURRENCIES))
cb.register_callback(message, select_fiat2)
def select_fiat2(call, data):
user = db.get_user(call.from_user.id)
fiat = data["currency"]
db.update_user(user.id, fiat=fiat)
bot.send_message(user.id, MSGS[user.lang]["FiatUpdated"].format(fiat))
main_menu(user)
def currencies_keyboard(currencies):
k = types.InlineKeyboardMarkup()
for currency in currencies:
k.add(types.InlineKeyboardButton(text=currency, callback_data=json.dumps({"currency": currency})))
return k
last_sti = {}
def main_menu(user):
cb.delete_old_inline(user.id)
cb.send_sti(user.id, "stickers/welcome.tgs")
bot.send_message(user.id, MSGS[user.lang]["MainMenu"].format(user.first_name), reply_markup=menu_keyboard(user),
parse_mode="HTML")
def menu_keyboard(user):
k = types.ReplyKeyboardMarkup(resize_keyboard=True)
k.row(MSGS[user.lang]["Operations"], MSGS[user.lang]["Wallet"])
k.row(MSGS[user.lang]["Settings"], MSGS[user.lang]["Support"])
return k
@bot.message_handler()
def menu_handler(message):
try:
user = db.get_user(message.from_user.id)
except exc.NoResultFound:
start(message)
return
cb.delete_old_inline(user.id)
cb.delete_sti(user.id)
if message.text == MSGS[user.lang]["Operations"]:
operations_menu(user)
elif message.text == MSGS[user.lang]["Wallet"]:
wallet_menu(user)
elif message.text == MSGS[user.lang]["Settings"]:
settings_menu(user)
elif message.text == MSGS[user.lang]["Support"]:
support_menu(user)
elif message.text == MSGS[user.lang]["Back"]:
main_menu(user)
# operations menu
def operations_menu(user):
cb.send_sti(user.id, "stickers/exchange.tgs")
message = bot.send_message(user.id, MSGS[user.lang]["OperationsMenu"], reply_markup=operations_menu_keyboard(user),
parse_mode="HTML")
cb.register_callback(message, operations_menu2)
def operations_menu2(call, data):
user = db.get_user(call.from_user.id)
if "FastExchange" in data:
fast_exchange(user)
elif "EscrowExchange" in data:
escrow_exchange_start(user)
elif "P2P" in data:
p2p_exchange(user)
def p2p_exchange(user):
if not user.balance:
bot.send_message(user.id, MSGS[user.lang]["NoBalance"])
return
currencies = [user.fiat] + CRYPTO_CURRENCIES
message = bot.send_message(user.id, MSGS[user.lang]["SelectOrderSellCur"],
reply_markup=currencies_keyboard(currencies))
cb.register_callback(message, p2p_exchange2)
def p2p_exchange2(call, data):
sell_cur = data["currency"]
user = db.get_user(call.from_user.id)
if sell_cur in FIAT_CURRENCIES:
currencies = list(CRYPTO_CURRENCIES)
else:
currencies = [user.fiat] + CRYPTO_CURRENCIES
if sell_cur in currencies:
currencies.pop(currencies.index(sell_cur))
bot.send_message(user.id, MSGS[user.lang]["CurrencyChosen"].format(sell_cur))
message = bot.send_message(user.id, MSGS[user.lang]["SelectOrderBuyCur"],
reply_markup=currencies_keyboard(currencies))
cb.register_callback(message, p2p_exchange3, sell_cur)
def p2p_exchange3(call, data, sell_cur):
user = db.get_user(call.from_user.id)
buy_cur = data["currency"]
bot.send_message(user.id, MSGS[user.lang]["CurrencyChosen"].format(buy_cur))
user = db.get_user(call.from_user.id)
p2p_exchange4(user, sell_cur, buy_cur)
def p2p_exchange4(user, sell_cur, buy_cur):
message = bot.send_message(user.id, MSGS[user.lang]["P2PMenu"], reply_markup=p2p_exchange_keyboard(user))
cb.register_callback(message, p2p_exchange5, sell_cur, buy_cur)
def p2p_exchange5(call, data, sell_cur, buy_cur):
user = db.get_user(call.from_user.id)
if "SeeOrders" in data:
orders_paginator(user, sell_cur, buy_cur)
return
elif "CreateOrder" in data:
create_order(user, sell_cur, buy_cur)
elif "SeeOwnOrders" in data:
my_orders_paginator(user, sell_cur, buy_cur)
def my_orders_paginator(user, sell_cur, buy_cur, start=0, end=9):
orders = db.get_orders(sell_cur, buy_cur, user.id, self_=True)
if not orders:
bot.send_message(user.id, MSGS[user.lang]["NoOrders"])
p2p_exchange4(user, sell_cur, buy_cur)
return
pages = math.ceil(len(orders) / 9)
page = int(start / 9) + 1
message = bot.send_message(user.id, MSGS[user.lang]["OrdersView"].format(page, pages),
reply_markup=paginator_keyboard(user.lang, orders[start:end], page != 1, page != pages))
cb.register_callback(message, my_orders_paginator2, sell_cur, buy_cur, start, end)
def my_orders_paginator2(call, data, sell_cur, buy_cur, start, end):
user = db.get_user(call.from_user.id)
if "back" in data:
p2p_exchange4(user, sell_cur, buy_cur)
return
if "prev" in data or "next" in data:
if "prev" in data:
end = start
start = start - 9
else:
start = end
end = end + 9
orders_paginator(user, sell_cur, buy_cur, start, end)
return
else:
order_id = data["order_id"]
order = db.get_order(order_id)
message = bot.send_message(user.id,
MSGS[user.lang]["DeleteOrder"].format(order.format(user.lang, status=False)),
reply_markup=get_confirm_keyboard(user))
cb.register_callback(message, remove_order1, order_id)
def remove_order1(call, data, order_id):
user = db.get_user(call.from_user.id)
order = db.get_order(order_id)
if data["confirm"]:
db.freeze_order(order_id, False)
db.delete_order(order_id)
bot.send_message(user.id, MSGS[user.lang]["OrderDeleted"])
p2p_exchange4(user, order.sell_currency, order.buy_currency)
def create_order(user, sell_cur, buy_cur):
msg = MSGS[user.lang]["CurrentBalance"].format(user.balance_in(sell_cur), sell_cur)
msg += "\n" + MSGS[user.lang]["EnterSellSum"]
message = bot.send_message(user.id, msg, reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, create_order2, sell_cur, buy_cur)
def create_order2(message, sell_cur, but_cur):
user = db.get_user(message.from_user.id)
amount = message.text
if amount == MSGS[user.lang]["Back"]:
p2p_exchange4(user, sell_cur, but_cur)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, create_order2, sell_cur, but_cur)
return
if amount > user.balance_in(sell_cur):
bot.send_message(user.id, MSGS[user.lang]["NotEnough"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, create_order2, sell_cur, but_cur)
return
bot.send_message(user.id, MSGS[user.lang]["MinTradeAmount"])
bot.register_next_step_handler(message, create_order3, sell_cur, but_cur, amount)
def create_order3(message, sell_cur, buy_cur, sell_amount):
user = db.get_user(message.from_user.id)
amount = message.text
if amount == MSGS[user.lang]["Back"]:
p2p_exchange4(user, sell_cur, buy_cur)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, create_order3, sell_cur, buy_cur, sell_amount)
return
min_trade_amount = amount
rate_ = str(cr_utils.rate(sell_cur, buy_cur, True))
bot.send_message(user.id, MSGS[user.lang]["YourRate"].format(sell_cur, buy_cur, rate_))
bot.register_next_step_handler(message, create_order4, sell_cur, buy_cur, sell_amount, min_trade_amount)
def create_order4(message, sell_cur, buy_cur, sell_amount, min_trade_amount):
user = db.get_user(message.from_user.id)
amount = message.text
if amount == MSGS[user.lang]["Back"]:
p2p_exchange4(user, sell_cur, buy_cur)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, create_order4, sell_cur, buy_cur, sell_amount, min_trade_amount)
return
rate = amount
db.create_order(user.id, sell_cur, buy_cur, min_trade_amount, sell_amount, rate)
bot.send_message(user.id, MSGS[user.lang]["OrderCreated"])
p2p_exchange4(user, sell_cur, buy_cur)
def orders_paginator(user, sell_cur, buy_cur, start=0, end=9):
orders = db.get_orders(sell_cur, buy_cur, user.id)
if not orders:
bot.send_message(user.id, MSGS[user.lang]["NoOrders"])
p2p_exchange4(user, sell_cur, buy_cur)
return
pages = math.ceil(len(orders) / 9)
page = int(start / 9) + 1
message = bot.send_message(user.id, MSGS[user.lang]["OrdersView"].format(page, pages),
reply_markup=paginator_keyboard(user.lang, orders[start:end], page != 1, page != pages))
cb.register_callback(message, orders_paginator2, sell_cur, buy_cur, start, end)
def orders_paginator2(call, data, sell_cur, buy_cur, start, end):
user = db.get_user(call.from_user.id)
if "back" in data:
p2p_exchange4(user, sell_cur, buy_cur)
return
if "prev" in data or "next" in data:
if "prev" in data:
end = start
start = start - 9
else:
start = end
end = end + 9
orders_paginator(user, sell_cur, buy_cur, start, end)
return
else:
order_id = data["order_id"]
order = db.get_order(order_id)
msg = MSGS[user.lang]["OfferForOrder"].format(f"{order.min_trade_amount:.{SYMBOLS[order.sell_currency]}f}",
f"{order.sell_amount:.{SYMBOLS[order.sell_currency]}f}",
order.sell_currency)
message = bot.send_message(user.id, msg,
reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, p2p_exchange6, order_id)
def p2p_exchange6(message, order_id):
user = db.get_user(message.from_user.id)
amount = message.text
order = db.get_order(order_id)
if amount == MSGS[user.lang]["Back"]:
p2p_exchange4(user, order.sell_currency, order.buy_currency)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, p2p_exchange6, order_id)
return
if amount < order.min_trade_amount:
bot.send_message(user.id, MSGS[user.lang]["ToSmallAmount"].format(order.min_trade_amount, order.buy_currency),
reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, p2p_exchange6, order_id)
return
if amount > order.sell_amount:
bot.send_message(user.id, MSGS[user.lang]["ToBigAmount"].format(order.sell_amount, order.buy_currency),
reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, p2p_exchange6, order_id)
return
if amount * order.rate > db.get_user(user.id).balance_in(order.buy_currency):
bot.send_message(user.id, MSGS[user.lang]["NotEnough"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, p2p_exchange6, order_id)
return
f_user = db.get_user(order.user_id)
message = bot.send_message(user.id,
order.format(user.lang, user=f_user) + "\n" + MSGS[user.lang][
"YourOffer"].format(amount,
order.sell_currency),
reply_markup=get_confirm_keyboard(user))
cb.register_callback(message, p2p_exchange7, order_id, amount)
def p2p_exchange7(call, data, order_id, amount):
user = db.get_user(call.from_user.id)
if not data["confirm"]:
order = db.get_order(order_id)
sell_cur = order.sell_currency
buy_cur = order.buy_currency
p2p_exchange4(user, sell_cur, buy_cur)
return
order = db.get_order(order_id)
bot.send_message(user.id, MSGS[user.lang]["CPNotified"], reply_markup=menu_keyboard(user))
message = bot.send_message(order.user_id,
MSGS[order.user.lang]["CPNotificationOrder"].format(
order.format(order.user.lang, status=False, to_me=True),
user.username, amount,
order.buy_currency),
reply_markup=get_confirm_keyboard(order.user))
cb.register_callback(message, p2p_exchange8, order_id, user.id, amount)
def p2p_exchange8(call, data, order_id, user_id, sell_amount):
c_user = db.get_user(call.from_user.id)
if not data["confirm"]:
return
order = db.get_order(order_id)
buy_amount = sell_amount * order.rate
user = db.get_user(user_id)
if buy_amount > user.balance_in(order.buy_currency):
bot.send_message(c_user.id, MSGS[c_user.lang]["CounterpartyNotEnough"].format(user.username))
return
op = db.create_linked_operations("EscrowExchange", order.user_id, user_id, order.sell_currency, sell_amount,
order.buy_currency, buy_amount)
db.freeze_order(order_id, False)
db.update_order(order_id, sell_amount=order.sell_amount - sell_amount)
db.freeze_order(order_id, True)
db.freeze_operation(op.id)
db.freeze_operation(op.linked_operation_id)
op = db.get_operation(op.id)
log("Завершена операция\n" + op.format(counterparty=True, lang="en", op_name="P2P Exchange"))
close_escrow(op.id, None, True, False)
def paginator_keyboard(lang, orders, prev, next):
k = types.InlineKeyboardMarkup()
for order in orders:
k.row(
types.InlineKeyboardButton(text=order.format(lang=lang, status=False),
callback_data=json.dumps({"order_id": order.id}))
)
btns = []
if prev:
btns.append(types.InlineKeyboardButton(text="⬅️", callback_data=json.dumps({"prev": ""})))
else:
btns.append(types.InlineKeyboardButton(text=" ", callback_data=json.dumps({"placeholder": ""})))
btns.append(types.InlineKeyboardButton(text=MSGS[lang]["Back"], callback_data=json.dumps({"back": ""})))
if next:
btns.append(types.InlineKeyboardButton(text="➡️", callback_data=json.dumps({"next": ""})))
else:
btns.append(types.InlineKeyboardButton(text=" ", callback_data=json.dumps({"placeholder": ""})))
k.row(*btns)
return k
def p2p_exchange_keyboard(user):
k = types.InlineKeyboardMarkup()
k.row(
types.InlineKeyboardButton(text=MSGS[user.lang]["SeeOrders"], callback_data=json.dumps({"SeeOrders": ""})),
types.InlineKeyboardButton(text=MSGS[user.lang]["CreateOrder"], callback_data=json.dumps({"CreateOrder": ""})),
)
k.row(
types.InlineKeyboardButton(text=MSGS[user.lang]["SeeOwnOrders"], callback_data=json.dumps({"SeeOwnOrders": ""}))
)
return k
def escrow_exchange_start(user):
message = bot.send_message(user.id, MSGS[user.lang]["EscrowExplanation"], reply_markup=escrow_types_keyboard(user))
cb.register_callback(message, escrow_exchange)
def escrow_types_keyboard(user):
k = types.InlineKeyboardMarkup()
k.row(
types.InlineKeyboardButton(text=MSGS[user.lang]["ChatEscrow"], callback_data=json.dumps({"_": "chat_escrow"})),
types.InlineKeyboardButton(text=MSGS[user.lang]["NoChatEscrow"],
callback_data=json.dumps({"_": "no_chat_escrow"}))
)
k.row(
types.InlineKeyboardButton(text=MSGS[user.lang]["DeleteEscrow"],
callback_data=json.dumps({"delete_escrow": ""}))
)
return k
def escrow_exchange(call, data):
user = db.get_user(call.from_user.id)
if "delete_escrow" in data:
delete_escrow_paginator(user)
return
type_ = data["_"]
if type_ == "no_chat_escrow" and not user.balance:
bot.send_message(user.id, MSGS[user.lang]["NoBalance"])
return
message = bot.send_message(user.id, MSGS[user.lang]["EnterUsername"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange1, type_)
def delete_escrow_paginator(user, start=0, end=9):
operations = db.get_escrows(user.id)
if not operations:
bot.send_message(user.id, MSGS[user.lang]["NoOffers"])
escrow_exchange_start(user)
return
pages = math.ceil(len(operations) / 9)
page = int(start / 9) + 1
message = bot.send_message(user.id, MSGS[user.lang]["OrdersView"].format(page, pages),
reply_markup=paginator_keyboard(user.lang, operations[start:end], page != 1,
page != pages))
cb.register_callback(message, delete_escrow_paginator2, start, end)
def delete_escrow_paginator2(call, data, start, end):
user = db.get_user(call.from_user.id)
if "back" in data:
escrow_exchange_start(user)
return
if "prev" in data or "next" in data:
if "prev" in data:
end = start
start = start - 9
else:
start = end
end = end + 9
delete_escrow_paginator(user, start, end)
return
op_id = data["order_id"]
operation = db.get_operation(op_id)
message = bot.send_message(user.id,
MSGS[user.lang]["DeleteOrder"].format(operation.format()),
reply_markup=get_confirm_keyboard(user))
cb.register_callback(message, remove_operation, op_id)
def remove_operation(call, data, op_id):
user = db.get_user(call.from_user.id)
if not data["confirm"]:
escrow_exchange_start(user)
return
op = db.get_operation(op_id)
if op.frozen:
db.freeze_operation(op_id, False)
if op.notification_id:
bot.delete_message(op.linked_operation.user_id, op.notification_id)
db.delete_operation(op_id)
bot.send_message(user.id, MSGS[user.lang]["OrderDeleted"])
escrow_exchange_start(user)
def escrow_exchange1(message, type_):
user = db.get_user(message.from_user.id)
username = message.text.replace("@", "").lower()
if message.text == MSGS[user.lang]["Back"]:
main_menu(user)
return
try:
contr_user = db.get_user(username=username)
if username == message.from_user.username:
raise exc.NoResultFound
except exc.NoResultFound:
bot.send_message(user.id, MSGS[user.lang]["NoSuchUser"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange1, type_)
return
user = db.get_user(message.from_user.id)
currencies = [balance_obj.currency for balance_obj in user.balance]
message = select_currency(user, currencies, "Sell")
cb.register_callback(message, escrow_exchange2, username, type_)
def escrow_exchange2(call, data, username, type_):
sell_cur = data["currency"]
user = db.get_user(call.from_user.id)
bot.send_message(user.id, MSGS[user.lang]["CurrencyChosen"].format(sell_cur))
if type_ == "no_chat_escrow" or sell_cur in CRYPTO_CURRENCIES:
msg = MSGS[user.lang]["CurrentBalance"].format(user.balance_in(sell_cur), sell_cur)
else:
msg = ""
msg += "\n" + MSGS[user.lang]["EnterSellSum"]
message = bot.send_message(user.id, msg, reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange3, sell_cur, username, type_)
def escrow_exchange3(message, sell_cur, username, type_):
user = db.get_user(message.from_user.id)
amount = message.text
if amount == MSGS[user.lang]["Back"]:
main_menu(user)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange3, sell_cur, username, type_)
return
if amount > user.balance_in(sell_cur) and (type_ == "no_chat_escrow" or sell_cur in CRYPTO_CURRENCIES):
bot.send_message(user.id, MSGS[user.lang]["NotEnough"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange3, sell_cur, username, type_)
return
sell_amount = amount
currencies = list(CRYPTO_CURRENCIES)
if sell_cur not in FIAT_CURRENCIES:
currencies.append(user.fiat)
message = select_currency(user, currencies, "Buy")
cb.register_callback(message, escrow_exchange4, username, sell_cur, sell_amount, type_)
def escrow_exchange4(call, data, username, sell_cur, sell_amount, type_):
buy_cur = data["currency"]
user = db.get_user(call.from_user.id)
bot.send_message(user.id, MSGS[user.lang]["CurrencyChosen"].format(buy_cur))
msg = MSGS[user.lang]["OperationAmount"].format(MSGS[user.lang]["Buy"])
message = bot.send_message(user.id, msg, reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange5, username, sell_cur, sell_amount, buy_cur, type_)
def escrow_exchange5(message, username, sell_cur, sell_amount, buy_cur, type_):
user = db.get_user(message.from_user.id)
amount = message.text
if amount == MSGS[user.lang]["Back"]:
main_menu(user)
return
try:
amount = Decimal(amount.replace(",", "."))
if amount <= 0:
raise decimal.InvalidOperation
except decimal.InvalidOperation:
bot.send_message(user.id, MSGS[user.lang]["FormatError"], reply_markup=back_keyboard(user))
bot.register_next_step_handler(message, escrow_exchange5, sell_cur, sell_amount, buy_cur, type_)
return
buy_amount = amount
countr_user = db.get_user(username=username)
operation = db.create_linked_operations("EscrowExchange", user.id, countr_user.id, sell_cur, sell_amount, buy_cur,
buy_amount)
if sell_cur not in FIAT_CURRENCIES or type_ == "no_chat_escrow":
db.freeze_operation(operation.id)
operation = db.get_operation(operation.id)
message = bot.send_message(user.id, operation.format(counterparty=True), reply_markup=get_confirm_keyboard(user))
cb.register_callback(message, escrow_exchange6, operation.id, countr_user, type_)
def escrow_exchange6(call, data, operation_id, countr_user, type_):
user = db.get_user(call.from_user.id)
if not data["confirm"]:
db.freeze_operation(operation_id, False)
bot.send_message(user.id, MSGS[user.lang]["OperationCancelled"])
main_menu(user)
return
bot.send_message(user.id, MSGS[user.lang]["CPNotified"], reply_markup=menu_keyboard(user))
operation = db.get_operation(operation_id)
if type_ == "chat_escrow":
msg = MSGS[user.lang]["CPNotificationChat"].format(user.username,
MSGS[user.lang]["EscrowDescription"].format(user.username,
operation.format(
user=countr_user,
rate=True)))
else:
msg = MSGS[user.lang]["CPNotificationNoChat"].format(user.username,
MSGS[user.lang]["EscrowDescription"].format(user.username,
operation.format(
user=countr_user,
rate=True)))
message = bot.send_message(countr_user.id, msg, operation,
reply_markup=countr_user_notification_keygboard(user))
db.update_operation(operation.id, notification_id=message.id)
cb.register_callback(message, escrow_exchange7, operation.id, user.id, type_)
def escrow_exchange7(call, data, operation_id, user_id, type_):
countr_user = db.get_user(call.from_user.id)
if not data["Accept"]:
bot.send_message(countr_user.id, MSGS[countr_user.lang]["OperationCancelled"])
bot.send_message(user_id,
MSGS[db.get_user(user_id).lang]["OperationRejected"].format(db.get_operation(operation_id)))
db.freeze_operation(operation_id, False)
db.delete_operation(operation_id)
return
op = db.get_operation(operation_id)
if type_ == "no_chat_escrow":
if op.linked_operation.amount > db.get_user(call.from_user.id).balance_in(op.linked_operation.currency):
bot.send_message(countr_user.id, MSGS[countr_user.lang]["NotEnough"])
return
db.freeze_operation(db.get_operation(operation_id).linked_operation_id)
log("Завершена операция\n" + op.format(counterparty=True, lang="en", op_name="Escrow Exchange (without chat)"))
close_escrow(operation_id, None, True)
else:
if op.currency in FIAT_CURRENCIES:
db.freeze_operation(op.linked_operation.id)
chat = cr_utils.get_chat()
if not chat:
message = bot.send_message(WALLET_CHAT_ID,
"Закончились свободные чаты для ескроу, просьба создать новый, сделать бота админом и прислать"
" id сюда.")
bot.register_next_step_handler(message, get_new_escrow_chat, operation_id, message.from_user.id)
return
escrow_exchange8(operation_id, chat)
chats = {}
def escrow_exchange8(operation_id, chat_id):
operation = db.get_operation(operation_id)
user = operation.user
link = bot.create_chat_invite_link(chat_id).invite_link
bot.send_message(user.id,
MSGS[user.lang]["Accepted"].format(operation.format(counterparty=True)) + "\n" + MSGS[user.lang][
"Invite"].format(link))
c_user = operation.linked_operation.user
bot.send_message(c_user.id, MSGS[c_user.lang][
"Invite"].format(link))
msg = MSGS[user.lang]["EscrowDescription"].format(user.username, operation.format(user=user))
if operation.currency in CRYPTO_CURRENCIES:
seller = user
buyer = c_user
else:
seller = c_user
buyer = user
msg += "\n" + MSGS[user.lang]["EscrowInstructions"].format(seller.username, buyer.username)
notify_admin_escrow(link, operation_id)
message = bot.send_message(chat_id, msg)
self_id = message.from_user.id
bot.register_next_step_handler(message, escrow_wait_for_commands, operation_id, chat_id, seller.id, self_id)
target = lambda: scan_for_noobs(chat_id, msg)
t = Thread(target=target)
t.start()
def scan_for_noobs(chat_id, msg):
c = bot.get_chat_members_count(chat_id)
while True:
time.sleep(15)
nc = bot.get_chat_members_count(chat_id)
if nc > c:
c = nc
bot.send_message(chat_id, msg)
if c >= 4:
return
def notify_admin_escrow(link, operation_id):
operation = db.get_operation(operation_id)
user = operation.user
c_user = operation.linked_operation.user
msg = f"Escrow exchange: @{user.username} | @{c_user.username}\n" \
f"{operation.format(lang='en', counterparty=True)}\nЧат с сторонами - {link}"
bot.send_message(WALLET_CHAT_ID, msg)
def escrow_wait_for_commands(message, operation_id, chat_id, seller_id, self_id):
if message.from_user.id == self_id:
bot.register_next_step_handler(message, escrow_wait_for_commands, operation_id, chat_id, seller_id, self_id)
if not message.text:
bot.register_next_step_handler(message, escrow_wait_for_commands, operation_id, chat_id, seller_id, self_id)
return
if "/cancel" in message.text:
close_escrow(operation_id, chat_id, False, chat=True)
return
elif "/confirm" in message.text and message.from_user.id == seller_id:
log("Завершена операция\n" + db.get_operation(operation_id).format(counterparty=True, lang="en",
op_name="Escrow Exchange"))
close_escrow(operation_id, chat_id, chat=True)
else:
bot.register_next_step_handler(message, escrow_wait_for_commands, operation_id, chat_id, seller_id, self_id)
def rate_user(user, c_user):
message = bot.send_message(user.id, MSGS[user.lang]["EscrowFinished"].format(c_user.username),
reply_markup=rate_keyboard())
cb.register_callback(message, register_rate, c_user)
def register_rate(call, data, c_user):
rate_ = data["rate"]
user = db.get_user(call.from_user.id)
bot.send_message(user.id, MSGS[user.lang]["Thanks"], reply_markup=menu_keyboard(user))
db.update_user(user.id, exchanges=user.exchanges + 1, sum_rate=user.sum_rate + rate_)
def rate_keyboard():
k = types.InlineKeyboardMarkup()
k.row(*[types.InlineKeyboardButton(text=i, callback_data=json.dumps({"rate": i})) for i in range(1, 6)])
k.row(*[types.InlineKeyboardButton(text=i, callback_data=json.dumps({"rate": i})) for i in range(6, 11)])
return k
def close_escrow(operation_id, chat_id=None, confirm=True, chat=False):
op = db.get_operation(operation_id)
user = op.user
c_user = op.linked_operation.user
if chat:
bot.kick_chat_member(chat_id, user.id)
bot.kick_chat_member(chat_id, c_user.id)
cr_utils.mark_as_free(chat_id)
if confirm:
if chat: # опция обмена с чатом, подтверждаем первую не фиатную операцию
if op.currency not in FIAT_CURRENCIES:
db.update_operation(op.id, confirm=True)
else:
db.update_operation(op.linked_operation_id, confirm=True)
else: # опция обмена без чата, подтверждаем обе операции
db.update_operation(op.id, confirm=True)
db.update_operation(op.linked_operation_id, confirm=True)
rate_user(user, c_user)
rate_user(c_user, user)
else:
if chat: # опция обмена с чатом, размораживаем первую не фиатную операцию
if op.currency not in FIAT_CURRENCIES:
db.freeze_operation(op.id, False)
else:
db.freeze_operation(op.linked_operation_id, False)
else: # опция обмена без чата, размораживаем обе операции
db.freeze_operation(op.id, False)
db.freeze_operation(op.linked_operation_id, False)
db.delete_operation(operation_id)
def get_new_escrow_chat(message, operation_id, self_id):
try:
chat_id = int(message.text)
except ValueError:
bot.reply_to(message, "Ошибка форматирования, повторите")
bot.register_next_step_handler(message, get_new_escrow_chat, operation_id)
else:
chat = bot.get_chat(chat_id)
admins = bot.get_chat_administrators(chat_id)
admins = [admin.user.id for admin in admins]
if self_id in admins:
bot.reply_to(message, "Успешно.")
cr_utils.save_escrow_chats(chat_id)
escrow_exchange8(operation_id, chat_id)
else:
bot.reply_to(message, f"Бот не является админом в {chat.first_name}, добавте и повторите.")
bot.register_next_step_handler(message, get_new_escrow_chat, operation_id)
return
def countr_user_notification_keygboard(user):
k = types.InlineKeyboardMarkup()
k.row(
types.InlineKeyboardButton(text=MSGS[user.lang]["Accept"], callback_data=json.dumps({"Accept": True})),
types.InlineKeyboardButton(text=MSGS[user.lang]["Deny"], callback_data=json.dumps({"Accept": False})),
)
return k
def fast_exchange(user):
if not user.balance:
bot.send_message(user.id, MSGS[user.lang]["NoBalance"])
return
currencies = [balance_obj.currency for balance_obj in user.balance]
message = select_currency(user, currencies, "Sell")
cb.register_callback(message, fast_exchange2)