-
Notifications
You must be signed in to change notification settings - Fork 0
/
tg_bot.py
859 lines (696 loc) · 39.8 KB
/
tg_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
import asyncio
import inspect
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.memory import MemoryStorage
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
import aiogram.utils.markdown as md
class Form(StatesGroup):
percent = State()
coin = State()
sub = State()
admin = State()
acc = State()
class TelegramBot:
def __init__(self, api_token: str, arbitoid, logger=None):
self.bot = Bot(token=api_token)
self.dp = Dispatcher(self.bot, storage=MemoryStorage())
self.logger = logger
self.arbitoid = arbitoid
self.handlers()
@classmethod
def keyboard(cls, commands: [list]) -> types.ReplyKeyboardMarkup:
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
for row in commands:
markup.row(
*list(map(types.KeyboardButton, row))
)
return markup
@classmethod
def main_menu(cls, user: dict = None) -> list:
menu = [
["🔍 ARBITRAGE"],
[
f"💸 {user['percent'] if user and user['percent'] else '3.5'}%",
f"💡 {'ON' if user and user['status'] else 'OFF'}"
],
["👤 ACC", "📎 HELP"]
]
return menu
@classmethod
def admin_panel(cls) -> list:
menu = [
["🏹 STATS"],
["🎫 SUB", "🏆 ADMIN", "👥 ACC"],
["⬅ MENU"]
]
return menu
def handlers(self):
@self.dp.message_handler(commands=['start'])
async def commands_start(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if self.arbitoid.input_user(message.from_user.id, message.from_user.username)['Response'] == 0:
for admin in self.arbitoid.get_admins['Response']:
await self.bot.send_message(admin['id'],
f"🔺 "
f"{md.hitalic('New user')} "
f"🔺\n\nStats:\n"
f"├{md.hbold('ID')}: {md.hcode(message.from_user.id)}\n"
f"├{md.hbold('Nick')}: @{message.from_user.username}\n"
f"├{md.hbold('Is_bot')}: {message.from_user.is_bot}\n"
f"\nTelegram bot: @Arbitroid_bot",
parse_mode='html')
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == int:
await self.bot.send_message(
message.from_user.id,
f"Welcome, @{message.from_user.username if message.from_user.username else 'user'}\n"
f"To gain access to the bot, write ---> @percoit 💬",
parse_mode='html'
)
else:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"Welcome back, @{message.from_user.username if message.from_user.username else 'user'}\n",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
'''
----------------------------------------------
Client logic
----------------------------------------------
'''
@self.dp.message_handler(commands=['account', 'acc', 'акк', 'аккаунт'])
@self.dp.message_handler(Text(equals=['👤 ACC'], ignore_case=True))
async def commands_account(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == str:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"\n📝 {md.hbold('Subscription expires on')}: "
f"{md.hitalic(user['sub'] if user['sub'] else 'XX-XX-XX')}(Y-M-D)\n"
f"\n👤My Profile:\n"
f"├Requests per minute: {md.hcode(str(user['req_num']) + '/5')}\n"
f"├Arbitrage % (min for alert): "
f"{md.hcode(str(user['percent']) + '%') if user['percent'] else md.hcode('3.5%')}\n"
f"\n🔔Alerts: {'on' if user['status'] == True else 'off'}",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['help', 'hlp', 'hp', 'поддержка'])
@self.dp.message_handler(Text(equals=['📎 HELP'], ignore_case=True))
async def commands_help(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == str:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"📎Details on each of the commands📎\n\n"
f"/acc {md.hitalic('- get your bot account details')}\n"
f"/pairs {md.hitalic('- get the most profitable arbitrage strategy on a coin')}\n"
f"/sw {md.hitalic('- to resume/break connection to the parser notification')}\n"
f"/prc {md.hitalic('- % of profit from which notifications will be sent (standard: 3.5)')}\n",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['status', 'st', 'switch', 'sw', 'change'])
@self.dp.message_handler(Text(contains=['💡'], ignore_case=True))
async def commands_status(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == str:
result = self.arbitoid.switch_status(message.from_user.id)['Response']
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
if result == 1:
await self.bot.send_message(
message.from_user.id,
f"Alerts {md.hbold('on')}...\n\n"
f"As soon as I find a good deal, I'll send a notification⏳"
f"To disable notifications, type 👉 /sw",
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id,
f"Alerts {md.hbold('off')}...\n\n"
f"To enable notifications, type 👉 /sw",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['percent', '%', 'prc', 'процент'])
@self.dp.message_handler(Text(contains=['💸'], ignore_case=True))
async def commands_prc(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == str:
markup = TelegramBot.keyboard(
[
['X']
]
)
await Form.percent.set()
await self.bot.send_message(
message.from_user.id,
"Enter % of which you'd like to receive arbitrage cases\n"
"To cancel, type the command 👉 /cancel",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state='*', commands='cancel')
@self.dp.message_handler(Text(equals=['cancel', 'отмена', '❌', 'X'], ignore_case=True), state='*')
async def cancel_handler(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
await message.delete()
current_state = await state.get_state()
if current_state is None:
return
if current_state.split(':')[1] in ['percent', 'coin']:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
else:
markup = TelegramBot.keyboard(self.admin_panel())
await self.bot.send_message(message.from_user.id, "Input stopped 📛", parse_mode='html',
reply_markup=markup)
await self.bot.delete_message(
message.from_user.id, message.message_id - 1
)
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state=Form.percent)
async def process_prc(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
async with state.proxy() as data:
data['percent'] = message.text
result = self.arbitoid.resize_percent(message.from_user.id, float(data['percent']))['Response']
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
if result == 0:
await self.bot.send_message(
message.from_user.id,
md.text(
md.text(
"Percent updated: " + md.hcode(data['percent'] + '%') + " 🔗"
),
sep='\n',
),
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id, "Incorrect input 📛 \n"
"Try again, type the command 👉 /prc", parse_mode='html',
reply_markup=markup
)
except Exception as error:
try:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id, "Unexpected error 📛 \n"
"Try again, type the command 👉 /prc", parse_mode='html',
reply_markup=markup
)
self.logger.warning(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['pairs', 'find_pairs', 'market', 'arbitro'])
@self.dp.message_handler(Text(equals=['🔍 ARBITRAGE'], ignore_case=True))
async def commands_pairs(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if type(self.arbitoid.check_sub(message.from_user.id)['Response']) == str:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
if user['req_num'] < 5:
markup = TelegramBot.keyboard([["X"]])
await Form.coin.set()
await self.bot.send_message(
message.from_user.id,
f"Enter the name of the cryptocurrency ({md.hitalic('bitcoin')})\n"
f"{md.hitalic('*check the correctness with the id on ')}"
f"{md.hlink('CoinGecko', 'https://www.coingecko.com/')}\n\n"
"To cancel, type the command 👉 /cancel",
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
else:
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"You have reached the request limit ({md.hcode(str(user['req_num']) + '/5')} per 1m)\n"
"Try again later type the command 👉 /pairs",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state=Form.coin)
async def process_pairs(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
async with state.proxy() as data:
data['coin'] = message.text.lower()
result = self.arbitoid.gecko_pairs(data['coin'])['Response']
self.arbitoid.add_req(message.from_user.id)
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
if result:
f = await self.bot.send_message(
message.from_user.id,
"Initialized the analysis of the selected coin... ⌛",
parse_mode='html'
)
market_buy, buy_price, link_buy = \
result[0]['market']['name'], result[0]['converted_last']['usd'], result[0]['trade_url']
market_sell, sell_price, link_sell = \
result[1]['market']['name'], result[1]['converted_last']['usd'], result[1]['trade_url']
network, market_fees = result[-1], result[2]
total_profit = self.arbitoid.profit_between_markets(
market_buy, self.arbitoid.reform_float(buy_price),
market_sell, self.arbitoid.reform_float(sell_price),
network[-1], market_fees
)
await asyncio.sleep(1)
await f.delete()
await self.bot.send_message(
message.from_user.id,
md.text(
md.hitalic("Link to check: ") +
f"https://www.coingecko.com/en/coins/{data['coin'].lower()}#markets" + ' ✅'
+ '\n\n' + "Parameters 📥/📤\n"
+ '├Market to buy: ' + md.hbold(market_buy)
+ '\n├Market link: \n'
+ link_buy[:link_buy.index('?') if '?' in link_buy else len(link_buy)]
+ "\n├Price to buy: " + md.hitalic(buy_price)
+ '\n├\n├Market to sell: ' + md.hbold(market_sell)
+ '\n├Market link: \n'
+ link_sell[:link_sell.index('?') if '?' in link_sell else len(link_sell)]
+ '\n├Price to sell: ' + md.hitalic(sell_price)
+ '\n\nTotal profit 💸' + "\n├Without fees: " + md.hcode(total_profit[0])
+ "\n├Minimal profit: " + md.hcode(total_profit[1])
+ "\n├Maximum profit: " + md.hcode(total_profit[-1])
+ "\nNetwork: " + md.hbold(network[0])
+ "\nFinal result might be lower according to network fees"
+ "\n\nData collected by " + "@Arbitroid_bot",
sep='\n',
),
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id, "Incorrect input 📛 \n"
"Try again, type the command 👉 /pairs", parse_mode='html',
reply_markup=markup
)
except Exception as error:
try:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id, "Unexpected error 📛 \n"
"Try again, type the command 👉 /pairs", parse_mode='html',
reply_markup=markup
)
self.logger.warning(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
'''
----------------------------------------------
Admin logic
----------------------------------------------
'''
@self.dp.message_handler(commands=['admin', 'promote'])
@self.dp.message_handler(Text(equals=['🏆 ADMIN'], ignore_case=True))
async def commands_admin(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
markup = TelegramBot.keyboard([["X"]])
await Form.admin.set()
await self.bot.send_message(
message.from_user.id,
f"Send the string in the following format: \n\n"
f"{md.hcode('user_id|status')}\n"
f"{md.hitalic('*0/1 - downgrade/upgrade to admin')}\n\n"
"To cancel, type the command 👉 /cancel",
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state=Form.admin)
async def process_admin(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
async with state.proxy() as data:
data['admin'] = message.text
tg_id, status = list(map(int, data['admin'].split('|')))
result = self.arbitoid.add_admin(tg_id, status)['Response']
user = self.arbitoid.get_user(tg_id)['Response']
markup = TelegramBot.keyboard(self.admin_panel())
if result == 0:
await self.bot.send_message(
message.from_user.id,
md.text(
f"{'🔥' if status == 1 else '💧'} "
f"User {('@' + user['username']) if user['username'] else md.hcode(user['id'])} "
f"{'promoted' if status == 1 else 'downgraded'} "
f"to {md.hbold('admin' if status == 1 else 'user')}",
sep='\n'
),
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id, "Incorrect input 📛 \n"
"Try again, type the command 👉 /admin", parse_mode='html',
reply_markup=markup
)
if status == 1:
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
response_markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
tg_id,
f"You've been promoted to admin ✔",
parse_mode='html',
reply_markup=response_markup
)
else:
response_markup = TelegramBot.keyboard(self.main_menu(user)) \
if type(self.arbitoid.check_sub(tg_id)['Response']) == str else types.ReplyKeyboardRemove()
await self.bot.send_message(
tg_id,
f"You've been downgraded to user ❌",
parse_mode='html',
reply_markup=response_markup
)
except Exception as error:
try:
await self.bot.send_message(
message.from_user.id, "Unexpected error 📛 \n"
"Try again, type the command 👉 /admin", parse_mode='html',
reply_markup=TelegramBot.keyboard(self.admin_panel())
)
self.logger.warning(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['stats', 'loc', 'акки', 'data'])
@self.dp.message_handler(Text(equals=['🏹 STATS'], ignore_case=True))
async def commands_stats(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
user_stats = self.arbitoid.get_stats['Response']
markup = TelegramBot.keyboard(self.admin_panel())
await self.bot.send_message(
message.from_user.id,
f"🌍 {md.hbold('USER STATS')} 🌍\n"
f"⸻⸻⸻⸻⸻⸻⸻\n\n"
f"👤 {md.hbold('ALL')}\n"
f"├Num: {md.hcode(len(user_stats['all']))}\n"
f"├Last Record: "
f"{md.hitalic(user_stats['all'][-1] if user_stats['all'] else 'отсутсвует')}\n\n"
f"🔖 {md.hbold('SUB')}\n"
f"├Num: {md.hcode(len(user_stats['with_sub']))}\n"
f"├Last Record: "
f"{md.hitalic(user_stats['with_sub'][-1] if user_stats['with_sub'] else 'отсутсвует')}\n\n"
f"Data collected by @Arbitroid_bot",
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['add_sub', 'adds'])
@self.dp.message_handler(Text(equals=['🎫 SUB'], ignore_case=True))
async def add_sub(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
markup = TelegramBot.keyboard([["X"]])
await Form.sub.set()
await self.bot.send_message(
message.from_user.id,
f"Send the string in the following format: \n\n"
f"{md.hcode('user_id|status')}\n"
f"{md.hitalic('*0/1 - take away/give a 2 month sub')}\n\n"
"To cancel, type the command 👉 /cancel",
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state=Form.sub)
async def process_sub(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
async with state.proxy() as data:
data['sub'] = message.text
tg_id, status = list(map(int, data['sub'].split('|')))
result = self.arbitoid.add_sub(tg_id, status)['Response']
user = self.arbitoid.get_user(tg_id)['Response']
markup = TelegramBot.keyboard(self.admin_panel())
if result == 0:
await self.bot.send_message(
message.from_user.id,
md.text(
f"{'✔' if status == 1 else '✖'} "
f"User {('@' + user['username']) if user['username'] else md.hcode(user['id'])} "
f"{'subscribed' if status == 1 else 'unsubscribed'} ",
sep='\n'
),
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id, "Incorrect input 📛 \n"
"Try again, type the command 👉 /add_sub", parse_mode='html',
reply_markup=markup
)
if user['is_admin'] is True:
await self.bot.send_message(
tg_id,
f"Subscription {'confirmed ✔' if status == 1 else 'declined ❌'}",
parse_mode='html',
)
else:
response_markup = TelegramBot.keyboard(self.main_menu(user)) \
if status == 1 else types.ReplyKeyboardRemove()
await self.bot.send_message(
tg_id,
f"Subscription {'confirmed ✔' if status == 1 else 'declined ❌'}",
parse_mode='html',
reply_markup=response_markup
)
except Exception as error:
try:
await self.bot.send_message(
message.from_user.id, "Unexpected error 📛 \n"
"Try again, type the command 👉 /add_sub", parse_mode='html',
reply_markup=TelegramBot.keyboard(self.admin_panel())
)
self.logger.warning(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(commands=['check_user', 'user'])
@self.dp.message_handler(Text(equals=['👥 ACC'], ignore_case=True))
async def check_user(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
markup = TelegramBot.keyboard([["X"]])
await Form.acc.set()
await self.bot.send_message(
message.from_user.id,
f"Send the string in the following format: \n\n"
f"{md.hcode('user_id')}\n\n"
"To cancel, type the command 👉 /cancel",
disable_web_page_preview=True,
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(state=Form.acc)
async def process_check_user(message: types.Message, state: FSMContext):
func_name = inspect.currentframe().f_code.co_name
try:
async with state.proxy() as data:
data['check_user'] = message.text
tg_id = data['check_user']
result = self.arbitoid.get_user(tg_id)['Response']
markup = TelegramBot.keyboard(self.admin_panel())
if type(result) == dict:
await self.bot.send_message(
message.from_user.id,
md.text(
f"👤 USER"
f"⸻⸻⸻⸻⸻⸻⸻\n\n"
f"├{md.hbold('ID')}: {md.hcode(result['id'])}\n"
f"├{md.hbold('Nick')}: @{result['username'] if result['username'] else 'none'}\n"
f"├{md.hbold('Is_admin')}: {result['is_admin']}\n"
f"├{md.hbold('Sub')}: {md.hitalic(result['sub'])}\n"
f"├{md.hbold('Req_per_1m')}: {md.hcode(str(result['req_num']) + '/5')}\n"
f"├{md.hbold('Alerts')}: {'on' if result['status'] == True else 'off'}\n"
f"├{md.hbold('Percent')}: {md.hcode(str(result['percent']))}\n"
f"├{md.hbold('Is_bot')}: {message.from_user.is_bot}\n",
sep='\n'
),
parse_mode='html',
reply_markup=markup
)
else:
await self.bot.send_message(
message.from_user.id, "Incorrect input 📛 \n"
"Try again, type the command 👉 /check_user", parse_mode='html',
reply_markup=markup
)
except Exception as error:
try:
await self.bot.send_message(
message.from_user.id, "Unexpected error 📛 \n"
"Try again, type the command 👉 /check_user", parse_mode='html',
reply_markup=TelegramBot.keyboard(self.admin_panel())
)
self.logger.warning(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
await state.finish()
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(Text(equals=['⬅ MENU'], ignore_case=True))
async def back_to_menu(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
user = self.arbitoid.get_user(message.from_user.id)['Response']
menu = self.main_menu(user)
menu.append(['➡ ADMIN_PANEL']) if user['is_admin'] else 0
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"Welcome back, @{message.from_user.username if message.from_user.username else 'user'}\n",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
@self.dp.message_handler(Text(equals=['➡ ADMIN_PANEL'], ignore_case=True))
async def enter_admin_panel(message: types.Message):
func_name = inspect.currentframe().f_code.co_name
try:
if message.from_user.id in [admin['id'] for admin in self.arbitoid.get_admins['Response']]:
menu = self.admin_panel()
markup = TelegramBot.keyboard(menu)
await self.bot.send_message(
message.from_user.id,
f"🔐 Welcome to {md.hbold('ARBITOID')} ADMIN PANEL, "
f"@{message.from_user.username if message.from_user.username else 'user'}\n",
parse_mode='html',
reply_markup=markup
)
await message.delete()
except Exception as error:
self.logger.error(f"{func_name}/{error.__class__}||{error.args[0]}") if self.logger else 0
finally:
self.logger.info(f"{func_name}/{message.from_user.id}") if self.logger else 0
def start(self, skip_updates: bool = True):
executor.start_polling(self.dp, skip_updates=skip_updates)