-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmytonctrl_bot.py
781 lines (677 loc) · 24 KB
/
mytonctrl_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
#!/usr/bin/env python3
# -*- coding: utf_8 -*-
import time
from os import listdir
from sys import getsizeof
from time import sleep
from mypylib.mypylib import (
MyPyClass,
Dict,
get_timestamp,
get_git_hash
)
# Telegram components
#pip3 install python-telegram-bot==13.7
from telegram import Bot, ParseMode, Update
from telegram.error import BadRequest, Unauthorized
from telegram.utils.helpers import escape_markdown
from telegram.ext import (
Updater,
CommandHandler,
MessageHandler,
Filters,
CallbackContext,
)
from utils import (
read_file,
get_config,
get_dict_from,
find_text_in_list,
get_item_from_list,
collect_template,
class_list2str_list
)
from user import (
User,
get_users,
get_active_users,
inform_admins, get_adnls, get_enabled_alerts
)
from user_alerts import (
ComplaintsAlert,
TelemetryAlert,
ComplaintsInformation,
ElectionsInformation
)
from toncenter import Toncenter
# Global vars
local = MyPyClass(__file__)
toncenter = Toncenter(local)
def init():
init_alerts()
init_buffer()
init_templates()
# Load translate table
# local.InitTranslator(local.buffer.get("myDir") + "translate.json")
# Set local config
local.db.config.isLocaldbSaving = True
local.db.config.logLevel = "debug"
local.run()
# Start threads
local.start_cycle(message_sender, sec=0.1)
local.start_cycle(scan_alerts, sec=60)
#end define
def init_alerts():
complaints_alerts = ComplaintsAlert(local, toncenter)
telemetry_alerts = TelemetryAlert(local, toncenter)
complaints_information = ComplaintsInformation(local, toncenter)
elections_information = ElectionsInformation(local, toncenter)
local.buffer.possible_alerts = [complaints_alerts, telemetry_alerts, complaints_information, elections_information]
local.buffer.possible_alerts_list = list()
for item in local.buffer.possible_alerts:
local.buffer.possible_alerts_list.append(type(item).__name__)
local.buffer.possible_alerts_text = ", ".join(local.buffer.possible_alerts_list)
#end define
def init_buffer():
config_path = local.buffer.my_dir + "settings.json"
data = get_config(config_path)
local.buffer.telegram_bot_token = data.telegram_bot_token
local.buffer.api_key = data.api_key
local.db.delay = data.delay if type(data.delay) == int else 60
local.buffer.admins = data.admins if type(data.admins) == list else list()
local.buffer.version = get_git_hash(local.buffer.my_dir, short=True)
#end define
def init_templates():
local.buffer.templates = Dict()
templates_dir = local.buffer.my_dir + "templates/"
for file_name in listdir(templates_dir):
template_name, file_type = file_name.split('.')
file_path = templates_dir + file_name
local.buffer.templates[template_name] = read_file(file_path)
#end define
def message_sender():
users = get_users(local)
for user in users:
user.send_messages(send_message)
#end define
def send_message(user, text):
# print(f"send_message user: {user.id}, text: {text}")
if len(text) == 0:
text = "No result"
if type(text) == str:
do_send_message(user, text)
elif type(text) == list:
for item in text:
do_send_message(user, item)
#end define
def do_send_message(user, text):
# print(f"do_send_message.text: `{text}`")
# context.bot.sendMessage(user.id=user.id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, disable_notification=True)
try:
local.buffer.updater.bot.sendMessage(chat_id=user.id, text=text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, disable_notification=True)
return True, None
except Exception as ex:
local.add_log(f"do_send_message error: {ex}", "error")
return False, ex
#end define
def init_bot():
# bot = Bot(token=telegram_bot_token)
# print(f"local.buffer: {local.buffer}")
telegram_bot_token = local.buffer.telegram_bot_token
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
local.buffer["updater"] = updater
# Create handlers
default_handler = MessageHandler(Filters.text & (~Filters.command), message_handler)
start_handler = CommandHandler("start", start_cmd)
help_handler = CommandHandler("help", help_cmd)
#status_handler = CommandHandler("status", status_cmd)
subscribe_node_handler = CommandHandler("subscribe_node", subscribe_node_cmd)
cancel_input_handler = CommandHandler("cancel", cancel_input_cmd)
#add_fullnode_adnl_handler = CommandHandler("add_fullnode_adnl", add_fullnode_adnl_cmd)
unsubscribe_node_handler = CommandHandler("unsubscribe_node", unsubscribe_node_cmd)
adnl_list_handler = CommandHandler("list_nodes", adnl_list_cmd)
enable_alert_handler = CommandHandler("enable_alert", enable_alert_cmd)
disable_alert_handler = CommandHandler("disable_alert", disable_alert_cmd)
alert_list_handler = CommandHandler("list_alerts", alerts_list_cmd)
me_handler = CommandHandler("me", me_cmd)
bot_handler = CommandHandler("bot", bot_cmd)
stats_handler = CommandHandler("stats", stats_cmd)
add_notification_handler = CommandHandler("add_notification", add_notification_cmd)
print_notification_handler = CommandHandler("print_notification", print_notification_cmd)
start_notification_handler = CommandHandler("start_notification", start_notification_cmd)
stop_notification_handler = CommandHandler("stop_notification", stop_notification_cmd)
test_print_handler = CommandHandler("test_print", test_print_cmd)
unknown_handler = MessageHandler(Filters.command, unknown_cmd)
# Add handlers
dispatcher.add_handler(default_handler)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(help_handler)
#dispatcher.add_handler(status_handler)
dispatcher.add_handler(subscribe_node_handler)
dispatcher.add_handler(cancel_input_handler)
#dispatcher.add_handler(add_fullnode_adnl_handler)
dispatcher.add_handler(unsubscribe_node_handler)
dispatcher.add_handler(adnl_list_handler)
dispatcher.add_handler(enable_alert_handler)
dispatcher.add_handler(disable_alert_handler)
dispatcher.add_handler(alert_list_handler)
dispatcher.add_handler(me_handler)
dispatcher.add_handler(bot_handler)
dispatcher.add_handler(stats_handler)
dispatcher.add_handler(add_notification_handler)
dispatcher.add_handler(print_notification_handler)
dispatcher.add_handler(start_notification_handler)
dispatcher.add_handler(stop_notification_handler)
dispatcher.add_handler(test_print_handler)
dispatcher.add_handler(unknown_handler)
return updater
#end define
def message_handler(update: Update, context: CallbackContext):
#input = update.message.text
#input = context.args
user = User(local, update.effective_user.id)
if user.get_state() == "subscribe_node":
adnl = update.message.text
label = None
if do_subscribe_node_cmd(user, adnl, label, '\nPlease try again or send /cancel to cancel:'):
user.set_state(None)
return
elif user.get_state() == "unsubscribe_node":
adnl = update.message.text
if do_unsubscribe_node_cmd(user, adnl, '\nPlease try again or send /cancel to cancel:'):
user.set_state(None)
return
output = "The command must start with a slash character (`/`)."
send_message(user, escape_markdown(output))
#end define
def unknown_cmd(update, context):
user = User(local, update.effective_user.id)
output = "Sorry, I didn't understand that command."
send_message(user, escape_markdown(output))
#end define
def start_cmd(update, context):
user = User(local, update.effective_user.id)
output = collect_template(local, "start")
send_message(user, output)
#end define
def help_cmd(update, context):
user = User(local, update.effective_user.id)
output = collect_template(local, "help")
send_message(user, output)
#end define
def me_cmd(update, context):
user = User(local, update.effective_user.id)
output = f"User: `{user.id}`" + '\n'
if user.is_admin() == True:
text = "Available admin commands: /add_notification, /print_notification, /start_notification, /stop_notification"
output += escape_markdown(text)
send_message(user, output)
#end define
def test_print_cmd(update, context):
user = User(local, update.effective_user.id)
if not user.is_admin():
unknown_cmd(update, context)
return
adnl = "CFB6E5AF514508527EDC8BD573B3EF9EEA09DD7227D9F3150D4E3B47DC87F19F"
telemetry_alerts = TelemetryAlert(local, toncenter)
complaints_alerts = ComplaintsAlert(local, toncenter)
elections_information = ElectionsInformation(local, toncenter)
complaints_information = ComplaintsInformation(local, toncenter)
value = 3600
upper_threshold = 40
lower_threshold = 20
telemetry_alerts.check_with_threshold(user, alert_name="Sync", adnl=adnl, value_for_comparison=value,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value)
value = 3
telemetry_alerts.check_with_threshold(user, alert_name="Sync", adnl=adnl, value_for_comparison=value,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value)
value = 15.13
max_value = 16
value_percent = round(value/max_value*100, 2)
upper_threshold = 90
lower_threshold = 80
telemetry_alerts.check_with_threshold(user, alert_name="CPU", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent, max_value=max_value)
value = 7.21
value_percent = round(value/max_value*100, 2)
telemetry_alerts.check_with_threshold(user, alert_name="CPU", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent, max_value=max_value)
value = 59.36
max_value = 64
value_percent = round(value/max_value*100, 2)
upper_threshold = 90
lower_threshold = 80
telemetry_alerts.check_with_threshold(user, alert_name="RAM", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent, max_value=max_value)
value = 31.08
value_percent = round(value/max_value*100, 2)
telemetry_alerts.check_with_threshold(user, alert_name="RAM", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent, max_value=max_value)
value = 580.81
upper_threshold = 500
lower_threshold = 450
telemetry_alerts.check_with_threshold(user, alert_name="Network", adnl=adnl, value_for_comparison=value,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value)
value = 420.23
telemetry_alerts.check_with_threshold(user, alert_name="Network", adnl=adnl, value_for_comparison=value,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value)
value = 46.31
value_percent = 92.46
upper_threshold = 90
lower_threshold = 80
telemetry_alerts.check_with_threshold(user, alert_name="Disk", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent)
value = 48.72
value_percent = 79.9
telemetry_alerts.check_with_threshold(user, alert_name="Disk", adnl=adnl, value_for_comparison=value_percent,
upper_threshold=upper_threshold, lower_threshold=lower_threshold, value=value, value_percent=value_percent)
election_id = get_timestamp()
complaints_alerts.warn(user, complaint=Dict(adnl_addr=adnl, election_id=election_id, suggested_fine=101*10**9))
complaints_information.inform(user, election_id=election_id, utime_until=election_id+60, complaints=[Dict(adnl_addr=adnl, election_id=election_id, suggested_fine=101*10**9), Dict(adnl_addr=adnl, election_id=election_id, suggested_fine=101*10**9)])
elections_information.inform_before_start(user, election_id, participant=Dict(adnl_addr=adnl, stake=701000*10**9))
elections_information.inform_after_start(user, election_id, problem_adnl_list=[adnl])
#end define
def bot_cmd(update, context):
user = User(local, update.effective_user.id)
if user.is_admin() == False:
unknown_cmd(update, context)
return
#end if
active_users = get_active_users(local)
db_size = round(getsizeof(local.db)/10**6, 2)
buffer_size = round(getsizeof(local.buffer)/10**6, 2)
output = f"version: `{local.buffer.version}`" + '\n'
output += f"users: `{len(active_users)}/{len(local.db.users)}`" + '\n'
output += f"db size: `{db_size} Mb`" + '\n'
output += f"buffer size: `{buffer_size} Mb`" + '\n'
send_message(user, output)
#end define
def stats_cmd(update, context):
user = User(local, update.effective_user.id)
if not user.is_admin():
unknown_cmd(update, context)
return
#end if
s = time.time()
active_users = get_active_users(local)
adnls = get_adnls(local)
enabled_alerts = get_enabled_alerts(local)
output = ''
output += f"total users: *{len(local.db.users)}*\n"
output += f"active users: *{len(active_users)}*\n"
output += f'total adnls: *{len(adnls)}*\n'
output += f"unique adnls: *{len(set(adnls))}*\n"
output += f"enabled alerts: \n"
for alert_name, count in enabled_alerts.items():
output += f" `{alert_name}`: *{count}*\n"
output += f"stats fetched in *{round(time.time() - s, 3)} sec*"
send_message(user, output)
#end define
def add_notification_cmd(update, context):
user = User(local, update.effective_user.id)
if user.is_admin() == False:
unknown_cmd(update, context)
return
#end if
text = update.message.text_markdown
if '\n' in text:
notification = text[text.find('\n') + 1:]
elif ' ' in text:
notification = text[text.find(' ') + 1:]
else:
notification = None
#end if
if notification and len(notification) > 0:
local.db.notification = notification
output = "Notification added"
else:
output = "Empty notification"
send_message(user, output)
#end define
def print_notification_cmd(update, context):
user = User(local, update.effective_user.id)
if user.is_admin() == False:
unknown_cmd(update, context)
return
#end if
if local.db.notification == None or len(local.db.notification) == 0:
output = "Empty notification"
send_message(user, output)
return
#end if
send_message(user, local.db.notification)
#end define
def start_notification_cmd(update, context):
username = escape_markdown('@' + update.effective_user.username)
user = User(local, update.effective_user.id)
if user.is_admin() == False:
unknown_cmd(update, context)
return
#end if
if local.db.notification == None or len(local.db.notification) == 0:
output = "Empty notification"
send_message(user, output)
return
#end if
if local.buffer.notification_sending == True:
output = "Already started"
send_message(user, output)
return
#end if
local.start_thread(do_notification_sending)
local.buffer.notification_sending = True
output = f"Start notification sending by {username} in {local.db.delay} seconds"
inform_admins(local, output)
#end define
def do_notification_sending():
sleep(local.db.delay)
if local.db.notification == None or len(local.db.notification) == 0:
return
#end if
sent, not_sent, blocked = 0, 0, 0
active_users = get_active_users(local)
for user_id, user in active_users.items():
# user.add_message(local.db.notification)
status, ex = do_send_message(user, local.db.notification)
if status:
sent += 1
continue
not_sent += 1
if isinstance(ex, Unauthorized):
if ex.message == "Forbidden: bot was blocked by the user":
blocked += 1
local.db.notification = None
local.buffer.notification_sending = None
text = f"Notification sent to {sent} users, not sent: {not_sent}, blocked: {blocked}"
inform_admins(local, text)
#end define
def stop_notification_cmd(update, context):
username = escape_markdown('@' + update.effective_user.username)
user = User(local, update.effective_user.id)
if user.is_admin() == False:
unknown_cmd(update, context)
return
#end if
local.db.notification = None
output = f"Stop notification sending by {username}"
inform_admins(local, output)
#end define
def cancel_input_cmd(update: Update, context: CallbackContext):
user = User(local, update.effective_user.id)
user.set_state(None)
output = "Canceled"
send_message(user, output)
#end define
def subscribe_node_cmd(update: Update, context: CallbackContext):
user = User(local, update.effective_user.id)
try:
adnl = context.args[0]
label = get_item_from_list(context.args, 1)
except:
msg = "Send Node ADNL Address or send /cancel to cancel:"
user.set_state("subscribe_node")
send_message(user, msg)
return
do_subscribe_node_cmd(user, adnl, label)
#end define
def do_subscribe_node_cmd(user, adnl, label, suffix: str = ''):
try:
int(adnl, 16)
is_hex = True
except:
is_hex = False
if not is_hex or len(adnl) != 64:
output = "The input doesn't seem to be a valid ADNL address."
send_message(user, output + suffix)
return False
validators_list = toncenter.get_validators_list()
nodes_list = toncenter.get_nodes_list()
adnl_list = validators_list + nodes_list
if adnl in adnl_list:
output = user.add_adnl(adnl)
user.add_label(adnl, label)
if adnl not in nodes_list:
output = f"Warning: Node doesn't send telemetry. Some functionality is unavailable. \n" + output
else:
output = f"ADNL `{adnl}` not found."
send_message(user, output + suffix)
return False
send_message(user, output)
return True
#end define
def unsubscribe_node_cmd(update, context):
user = User(local, update.effective_user.id)
#user_adnl_list_text = ", ".join(user_adnl_list)
try:
adnl = context.args[0]
except:
msg = "Send Node ADNL Address or send /cancel to cancel:"
user.set_state("unsubscribe_node")
send_message(user, msg)
return
#end try
do_unsubscribe_node_cmd(user, adnl)
#end define
def do_unsubscribe_node_cmd(user, adnl, suffix: str = ''):
user_adnl_list = user.get_adnl_list()
if adnl in user_adnl_list:
user_adnl_list.remove(adnl)
output = f"`{adnl}` is deleted."
res = True
else:
output = f"`{adnl}` not found." + suffix
res = False
#output += f"User adnl list: _{user_adnl_list_text}_"
send_message(user, output)
return res
def adnl_list_cmd(update, context):
user = User(local, update.effective_user.id)
user_adnl_list = user.get_adnl_list()
user_labels = user.get_labels()
output = ""
for adnl in user_adnl_list:
label = user_labels.get(adnl, "")
output += f"`{adnl} {label}`" + '\n'
# output = json.dumps(user_adnl_list, indent=2)
# output = f"`{output}`"
send_message(user, output)
#end define
def add_fullnode_adnl_cmd(update, context):
user = User(local, update.effective_user.id)
try:
fullnode_adnl = context.args[0]
except:
error = "Bad args. Usage: `add_fullnode_adnl <fullnode_adnl>`"
send_message(user, error)
return
output = user.add_fullnode_adnl(fullnode_adnl)
send_message(user, output)
#end define
def enable_alert_cmd(update, context):
user = User(local, update.effective_user.id)
try:
alert_type = context.args[0]
except:
error = "Bad args. Usage: `/enable_alert <alert_type>`" + '\n'
error += f"Possible alerts: _{local.buffer.possible_alerts_text}_"
send_message(user, error)
return
output = user.enable_alert(alert_type)
send_message(user, output)
#end define
def disable_alert_cmd(update, context):
user = User(local, update.effective_user.id)
try:
alert_type = context.args[0]
except:
error = "Bad args. Usage: `/disable_alert <alert_type>`" + '\n'
send_message(user, error)
return
#end try
output = user.disable_alert(alert_type)
send_message(user, output)
#end define
def alerts_list_cmd(update, context):
user = User(local, update.effective_user.id)
user_alerts_list = user.get_alerts_list()
user_alerts_text = ", ".join(class_list2str_list(user_alerts_list))
output = f"User alerts: _{user_alerts_text}_" + '\n'
#output += f"Possible alerts: _{local.buffer.possible_alerts_text}_"
send_message(user, output)
#end define
def status_cmd(update, context):
user = User(local, update.effective_user.id)
data = get_my_status(user)
output = Status2TextWithFraction(data)
send_message(user, output)
#end define
def get_my_status(user):
'''Отобразить статусы своих валидаторов'''
user_labels = user.get_labels()
user_adnl_list = user.get_adnl_list()
result = list()
for adnl_addr in user_adnl_list:
data = get_validator_status(user, adnl_addr)
data["label"] = user_labels.get(adnl_addr)
result.append(data)
return result
#end define
def Status2TextWithFraction(data):
result = list()
buff = list_fraction(data, 16)
# print("Status2TextWithFraction.data:", json.dumps(data))
# print("Status2TextWithFraction.buff:", json.dumps(buff))
for item in buff:
text = StatusList2Text(item)
result.append(text)
# print("Status2TextWithFraction.result:", json.dumps(result))
return result
#end define
def StatusList2Text(data):
output = ""
for item in data:
output += Status2Text(item)
return output
#end define
def Status2Text(item):
output = ""
if item.label:
output += f"Label: {item.label}" + '\n'
output += f"ADNL: {item.adnl_short}... `{item.status_icon}`" + '\n'
output += f"Validator: {item.is_validator}" + '\n'
output += f"Send telemetry: {item.is_send_telemetry}" + '\n'
if item.is_validator:
output += f"Working: {item.isWorking}" + '\n'
if item.telemetry_availability:
output += f"Out of sync: {item.outOfSync}" + '\n'
output += f"Cpu load: {item.cpuLoad}" + '\n'
output += f"Net load: {item.netLoad}" + '\n'
#if item.telemetry_availability == False and item.is_send_telemetry == True:
# output += "Warning: Telemetry is only available to validator owners. "
# output += "Confirm node ownership with command /add_fullnode_adnl" + '\n'
output += '\n'
output = f"`{output}`"
return output
#end define
def get_validator_status(user, adnl_addr):
data = Dict()
data.adnl_addr = adnl_addr
data.adnl_short = adnl_addr[0:7]
data.is_validator = False
data.is_send_telemetry = False
data.telemetry_availability = False
# get data
validators = toncenter.get_validators()
user_fullnode_adnl_list = user.get_fullnode_adnl_list()
# Get validator info
for validator in validators:
itemAdnlAddr = validator.get("adnl_addr")
if adnl_addr == itemAdnlAddr:
# print("get_validator_status.validator:", json.dumps(validator))
data.is_validator = True
#data.adnl_addr = adnl_addr
#data.adnl_ending = adnl_addr[58:65]
data.pubkey = validator.get("pubkey")
data.weight = validator.get("weight")
#end for
# Get node info
node = toncenter.get_telemetry(user, adnl_addr)
data.is_send_telemetry = toncenter.is_send_telemetry(adnl_addr)
if node:
data.telemetry_availability = True
data.cpuLoad = node.data.cpuLoad
data.netLoad = node.data.netLoad
buff_status = node.data.validatorStatus
if buff_status:
data.isWorking = buff_status.get("isWorking")
data.unixtime = buff_status.get("unixtime")
data.masterchainblocktime = buff_status.get("masterchainblocktime")
data.outOfSync = buff_status.get("outOfSync")
#end if
#end if
# Set status
isWorking = data.get("isWorking")
outOfSync = data.get("outOfSync")
is_validator = data.get("is_validator")
status = None
# Если нода отправляет телеметрию
if outOfSync != None:
# Если рассинхронизация > 300, или нода не работает
if outOfSync > 300 or isWorking == False:
status = False
else:
status = True
#end if
# Set status icon
if status == True and is_validator == True:
status_icon = "✅"
elif status == True and is_validator == False:
status_icon = "☑️"
elif status == False:
status_icon = "❌"
else:
status_icon = ""
data["status_icon"] = status_icon
data["status"] = status
return data
#end define
def list_fraction(input_list, max_len):
buff = list()
result = list()
for item in input_list:
if len(buff) == max_len:
result.append(buff)
buff = list()
buff.append(item)
if len(buff) > 0:
result.append(buff)
return result
#end define
def scan_alerts():
users = get_users(local)
for user in users:
try_scan_user_alerts(user)
#end define
def try_scan_user_alerts(user):
try:
scan_user_alerts(user)
except Exception as er:
local.add_log(f"scan_user_alerts {user.id} error: {er}", "error")
#end define
def scan_user_alerts(user):
user_alerts_list = user.get_alerts_list()
#for alert in local.buffer.possible_alerts:
#if type(alert).__name__ in user_alerts_list:
# alert.check(user)
for alert in user_alerts_list:
alert.check(user)
#end define
###
### Start of the program
###
if __name__ == "__main__":
init()
updater = init_bot()
updater.start_polling()
#end if