-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathokerr-telebot.py
executable file
·577 lines (458 loc) · 16.7 KB
/
okerr-telebot.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
#!/usr/bin/env python
# coding=utf-8
# from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
# from telegram import InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup
# from telegram.error import (TelegramError, Unauthorized, BadRequest,
# TimedOut, ChatMigrated, NetworkError)
# import telegram
import telebot
import argparse
import logging
import json
import time
import signal
import sys, os
import socket
import datetime
import django
#from django.core.urlresolvers import reverse
from django.urls import reverse
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "okerr.settings")
django.setup()
from django.db import connection
from requests.exceptions import RequestException
from okerrui.models import Profile, Project
from okerrui.cluster import myci, RemoteServer
from okerrui.impex import Impex
from okerrupdate import OkerrProject, OkerrExc
from myutils import dhms, md_escape
bot = telebot.TeleBot(settings.TGBOT_TOKEN)
started = time.time()
# updater = None
stop = False
log = None
commands_cnt = 0
main_rs = None
def msgargs(message):
return message.text.split(' ')[1:]
def myname():
try:
name = os.environ['HOSTNAME']
except KeyError:
name = socket.gethostname()
return name.split('.')[0]
# my indicators
op = OkerrProject()
hostname = myname()
uptimei = op.indicator("{}:telebot_uptime".format(hostname))
lastcmdi = op.indicator('{}:telebot_lastcmd'.format(hostname))
LOOP_TIME = int(getattr(settings, 'TGBOT_LOOP_TIME', 20*60))
def is_connection_usable():
try:
connection.connection.ping()
except Exception as e:
log.info("db connection check exception: {} {}".format(type(e), e))
return False
else:
return True
def db_up():
return
if not is_connection_usable():
log.info('pid:{} db connection not usable, close it'.format(os.getpid()))
connection.close()
def reg_command(message):
global commands_cnt
tgname = message.from_user.username
log.info('@{}: {}'.format(tgname, message.text))
try:
lastcmdi.update('OK', details='pid: {} @{}: {}'.format(os.getpid() ,tgname, message.text))
except OkerrExc as e:
log.error(e)
commands_cnt += 1
db_up()
def sighandler(signum, frame):
global stop
print("caught signal {}".format(signum))
stop = True
def unset_chat_id(chat_id):
try:
for rs in RemoteServer.all_rs():
rs.api_admin_tglink(chat_id = chat_id)
except Exception as e:
print(e)
def set_chat_id(email, tgname, chat_id):
try:
profile = None
log.info(f"set chat id email: {email} tgname: {tgname} chat_id: {chat_id}")
# find profile
if email:
# do not use tgname in this search!
profile = Profile.objects.get(user__email=email)
else:
if tgname:
# case-insensitive search for telegram_name
profile = Profile.objects.get(telegram_name = tgname.lower())
else:
profile = Profile.objects.get(telegram_name = str(chat_id))
log.info(f"got profile: {profile}")
"""
# verify profile
if profile.telegram_name.lower() != tgname.lower() and profile.telegram_name != str(chat_id):
if tgname:
return 'Set telegram name {} in profile'.format(tgname)
else:
return 'Set telegram name {} in profile'.format(chat_id)
"""
rs = RemoteServer(ci = profile.ci)
if tgname:
jr = rs.api_admin_tglink(email, tgname, chat_id)
else:
jr = rs.api_admin_tglink(email, chat_id, chat_id)
r = json.loads(jr)
# sync if needed
if rs.ci != myci():
for username in r['sync']:
data = rs.get_user(username)
ie = Impex()
ie.set_verbosity(0)
ie.preimport_cleanup(data)
ie.import_data(data)
return r['msg']
except Profile.DoesNotExist as e:
log.info('Not found profile for tg user {}. Try little later?'.format(tgname))
if tgname:
return "Telegram user with name '{}' not known in Okerr. Sorry. Please set this name in okerr profile first and try little later.".format(tgname)
else:
return "Telegram user with id {} not known in Okerr. Sorry. Please set this id in okerr profile first and try little later.".format(chat_id)
except Profile.MultipleObjectsReturned as e:
log.error('Multiple profiles for tg user {}'.format(tgname))
return "More then one telegram user '{}' in Okerr. Use /on <email> command.".format(tgname)
def get_reply_markup(chat_id):
try:
markup = telebot.types.ReplyKeyboardMarkup()
if main_rs.api_admin_chat_id(chat_id):
markup.row(
telebot.types.KeyboardButton('/help'),
telebot.types.KeyboardButton('/recheck')
),
markup.row(
telebot.types.KeyboardButton('/sum'),
)
else:
markup.row(
telebot.types.KeyboardButton('/on'),
telebot.types.KeyboardButton('/help')
)
return markup
except Exception as e:
print(e)
@bot.message_handler(commands=['help'])
def cmd_help(message):
reg_command(message)
chat_id = message.chat.id
try:
help_text = '''
[/help](/help) - This help
[/on](/on) - Subscribe to alerts
[/sum](/sum) - Quick summary
[/off](/off) - Unsubscribe from alerts
'''
bot.send_message(
chat_id=chat_id,
parse_mode = "Markdown",
reply_markup = get_reply_markup(chat_id),
text=help_text)
except Exception as e:
print("EXCEPTION: {} {}".format(type(e), e))
def cmd_debug(update, ctx):
bot = ctx.bot
args = ctx.args
reg_command(update, ctx)
chat_id = update.message.chat_id
tgname = update.message.from_user.username
log.info('debug @{} #{}'.format(tgname, chat_id))
bot.send_message(
chat_id=update.message.chat_id,
text="You are @{}, chat_id: {}".format(tgname, chat_id))
for p in Profile.objects.filter(telegram_name = tgname):
bot.send_message(
chat_id=update.message.chat_id,
text="Profile {} @{}, chat_id: {} ci: {}/{}".format(p.user.username, p.telegram_name, p.telegram_chat_id, p.ci, myci()))
@bot.message_handler(commands=['recheck'])
def cmd_recheck(message):
reg_command(message)
projects = list()
chat_id = message.chat.id
username = main_rs.api_admin_chat_id(chat_id)
if username is None:
tgname = message.from_user.username
error_msg = "chat id: {} tg name: {} not linked to any account".format(chat_id, tgname)
log.info(error_msg)
bot.send_message(
chat_id=chat_id,
text=error_msg,
reply_markup=get_reply_markup(chat_id))
return
project_list = main_rs.api_admin_member(username)
if project_list is None:
log.info('Failed to get project list for user {} from {}'.format(username, main_rs))
bot.send_message(
chat_id=chat_id,
text="Internal exception, please contact support",
reply_markup=get_reply_markup(chat_id))
return
for textid in project_list:
projects.append(textid)
if not projects:
log.info("no projects!")
bot.send_message(
chat_id=chat_id,
text="No projects",
reply_markup=get_reply_markup(chat_id))
return
for textid in projects:
url = main_rs.api_director(textid)
rs = RemoteServer(url=url)
l = rs.api_recheck(textid)
if l is None:
log.error('api_recheck for {} / {} returned None'.format(rs.name, p.get_textid()))
bot.send_message(
chat_id=chat_id,
parse_mode="Markdown",
reply_markup=get_reply_markup(chat_id),
text='Server {} for project {} unavailable at moment. Sorry. Try again later.'.format(rs.name,
p.get_textid()))
return
log.info("rechecked project {}: {} indicators".format(textid, len(l)))
if l:
# not empty list
msg = "Project {}: recheck: {}".format(textid, ' '.join(l[:5]))
else:
msg = "Project {}: nothing to recheck".format(textid)
bot.send_message(
chat_id=chat_id,
parse_mode="Markdown",
reply_markup=get_reply_markup(chat_id),
text=msg)
# end for project
@bot.message_handler(commands=['sum'])
def cmd_qsum(message):
reg_command(message)
reported = 0
projects = list()
chat_id = message.chat.id
username = main_rs.api_admin_chat_id(chat_id)
if username is None:
tgname = message.from_user.username
error_msg = "chat id: {} tg name: {} not linked to any account".format(chat_id, tgname)
log.info(error_msg)
bot.send_message(
chat_id=chat_id,
text=error_msg,
reply_markup = get_reply_markup(chat_id))
return
project_list = main_rs.api_admin_member(username)
if project_list is None:
log.info('Failed to get project list for user {} from {}'.format(username, main_rs))
bot.send_message(
chat_id=chat_id,
text="Internal exception, please contact support",
reply_markup = get_reply_markup(chat_id))
return
for textid in project_list:
projects.append(textid)
if not projects:
log.info("no projects!")
bot.send_message(
chat_id=chat_id,
text="No projects",
reply_markup = get_reply_markup(chat_id))
return
for textid in projects:
url = main_rs.api_director(textid)
rs = RemoteServer(url = url)
data = rs.api_admin_qsum(textid)
log.info("show project {}".format(textid))
#msg = 'zzzzz'
tpl = '''
Project *{}* ({})
Total {} (maintenance: {}, silent: {}, ERR: {})
'''
if data is None:
log.error('api_admin_qsum for {} / {} returned None'.format(rs.name, p.get_textid()))
bot.send_message(
chat_id=chat_id,
parse_mode = "Markdown",
reply_markup = get_reply_markup(chat_id),
text='Server {} for project {} unavailable at moment. Sorry. Try again later.'.format(rs.name, p.get_textid()))
return
msg = tpl.format(data['project'], data['textid'],
data['cnt']['total'],
data['cnt']['maintenance'],
data['cnt']['silent'],
data['cnt']['ERR'])
for i in data['ERR'][:5]:
try:
link = rs.reverse('okerr:ilocator', {'pid': data['textid'], 'iid': i['name']})
msg += '[{}]({}) = {} ({}) {} ago\n'.format(
md_escape(i['name']), link, i['status'], md_escape(i['details']), i['age'])
except Exception as e:
print(e)
if len(data['ERR']) > 5:
msg += '(Only first 5 of {} shown)\n'.format(len(data['ERR']))
bot.send_message(
chat_id=chat_id,
parse_mode = "Markdown",
reply_markup = get_reply_markup(chat_id),
text=msg)
# end for project
@bot.message_handler(commands=['info'])
def cmd_info(message):
reg_command(message)
chat_id=message.chat.id
tgname = message.from_user.username
uptime = time.time() - started
hostname = socket.gethostname()
msg = 'Hello {}!\nYour chat id is {}\nHostname: {}\nUptime: {}'.format(tgname, chat_id, hostname, dhms(uptime))
bot.send_message(
chat_id=chat_id,
# parse_mode = telegram.ParseMode.MARKDOWN,
reply_markup = get_reply_markup(chat_id),
text=msg)
@bot.message_handler(commands=['on'])
def cmd_on(message):
reg_command(message)
chat_id=message.chat.id
tgname = message.from_user.username
args = msgargs(message)
try:
email = args[0]
except IndexError:
email = None
log.info('set @{} #{} (email: {})'.format(tgname, chat_id, email))
msg = set_chat_id( email = email, tgname = tgname, chat_id = chat_id )
bot.send_message(
chat_id=chat_id,
# parse_mode = telegram.ParseMode.MARKDOWN,
reply_markup = get_reply_markup(chat_id),
text=msg)
@bot.message_handler(commands=['off'])
def cmd_off(message):
reg_command(message)
chat_id=message.chat.id
tgname = message.from_user.username
log.info('unset @{} #{}'.format(tgname, chat_id))
unset_chat_id(chat_id)
bot.send_message(
chat_id=chat_id,
text="Turned off on all okerr servers.",
reply_markup = get_reply_markup(chat_id))
def cmd_unknown(update):
reg_command(update)
bot.send_message(
chat_id=update.message.chat_id,
text="Sorry, I didn't understand that command.")
def error_callback(update, ctx):
bot = ctx.bot
log.error("tgbot {}: {}".format(ctx.error.__class__.__name__, ctx.error))
try:
pass
# raise ctx.error
except Unauthorized:
# remove update.message.chat_id from conversation list
pass
except BadRequest:
# handle malformed requests - read more below!
pass
except TimedOut:
# handle slow connection problems
pass
except NetworkError:
# handle other connection problems
pass
except ChatMigrated as e:
# the chat_id of a group has changed, use e.new_chat_id instead
pass
except TelegramError:
# handle all other telegram related errors
pass
@bot.message_handler(commands=['start'])
def cmd_start(message):
reg_command(message)
bot.reply_to(
message,
# parse_mode = telegram.ParseMode.MARKDOWN,
"Welcome to Okerr telegram bot!")
cmd_help(message)
def main():
#global updater, log
global log
global bot
global main_rs
started = datetime.datetime.now()
try:
def_server = getattr(settings, 'SERVER_URL')
except AttributeError:
def_server = None
parser = argparse.ArgumentParser(description='okerr telegram server.')
parser.add_argument('-s', '--server',
default=def_server, help='Remote okerr server URL')
parser.add_argument('-v', dest='verbose', action='store_true',
default=False, help='verbose mode')
args = parser.parse_args()
assert(settings.TGBOT_TOKEN)
main_rs = RemoteServer(url=args.server)
assert(main_rs)
signal.signal(signal.SIGINT, sighandler)
#logging.basicConfig(
# format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
# level=logging.DEBUG)
log = logging.getLogger('okerr-telebot')
out = logging.StreamHandler(sys.stdout)
out.setFormatter(logging.Formatter('%(asctime)s %(message)s',
datefmt='%Y/%m/%d %H:%M:%S'))
out.setLevel(logging.INFO)
log.addHandler(out)
err = logging.StreamHandler(sys.stderr)
err.setLevel(logging.ERROR)
log.addHandler(err)
if args.verbose:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
log.propagate = False
op.setlog(log)
log.info("Start polling (pid: {} started: {})...".format(os.getpid(), started.strftime("%Y/%m/%d %H:%M:%S")))
# updater.start_polling()
bot.infinity_polling()
log.error("END OF INFINITY (pid: {} now: {} age: {})".format(
os.getpid(),
datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"),
(datetime.datetime.now() - started)
))
"""
try:
bot.infinity_polling()
# bot.polling(none_stop=True)
except RequestException as e:
log.error('Caught request exceptions {}: {}'.format(type(e), e))
sys.exit(1)
print("stop polling")
while not stop:
# db_up()
uptime = time.time() - started
try:
uptimei.update('OK', 'pid: {} Uptime: {} cmds: {}'.format(os.getpid(), dhms(uptime), commands_cnt))
except OkerrExc as e:
log.error("update error: {}".format(str(e)))
log.info('tick-tock')
time.sleep(LOOP_TIME)
print("stopping bot.. please wait a little")
stop_time = time.time()
updater.stop()
print("stopped after {}s".format(int(time.time() - stop_time)))
print("Bye.")
"""
main()
print("After main")