Bit.ASICmon-p/telegrambot.py

126 lines
3.3 KiB
Python

from threading import Thread
from telegram import Bot, error
from asics import ASICs
from time import sleep
from mysql.connector import connect, Error
from macros import *
import os, json, asyncio
class TGThread(Thread):
conn = None
bot = None
asics = {}
def __init__(self, event, event2):
super(TGThread, self).__init__()
self.event = event
self.event2 = event2
async def sendmsg(self, msg):
return await self.bot.send_message(CONF.get('telegram', 'channel'), msg, 'MarkdownV2')
async def check(self):
msg = []
for i in self.asics.keys():
self.asics[i]['tooff'] -= 1
with self.conn.cursor(dictionary=True) as c:
c.execute(f"SELECT * FROM `laststate`")
for i in c.fetchall():
if not i['mac'] in self.asics.keys():
self.asics[i['mac']] = {}
self.asics[i['mac']]['alert'] = 0
msg.append(f"🟢 {i['location']} \| ASIC \"*{ASICs(i['type']).name}*\" `{i['ip']}` online\!")
self.asics[i['mac']]['tooff'] = 3
self.asics[i['mac']]['status'] = i['status']
if i['status'] == 'crit':
if CONF.get('telegram', 'crit-notify') and self.asics[i['mac']]['alert'] < 2:
msg.append(f"🔴 {i['location']} \| ASIC \"*{ASICs(i['type']).name}*\" `{i['ip']}` crit status\!")
self.asics[i['mac']]['alert'] = 2
elif i['status'] == 'warn':
if CONF.get('telegram', 'warn-notify') and self.asics[i['mac']]['alert'] < 1:
msg.append(f"🟡 {i['location']} \| ASIC \"*{ASICs(i['type']).name}*\" `{i['ip']}` warn status\!")
self.asics[i['mac']]['alert'] = 1
elif i['status'] == 'ok':
if CONF.get('telegram', 'normal-notify') and self.asics[i['mac']]['alert'] != 0:
msg.append(f"🟢 {i['location']} \| ASIC \"*{ASICs(i['type']).name}*\" `{i['ip']}` normal status\!")
self.asics[i['mac']]['alert'] = 0
if self.asics[i['mac']]['tooff'] <= 0:
msg.append(f"🔴 {i['location']} \| ASIC \"*{ASICs(i['type']).name}*\" `{i['ip']}` offline\!")
del self.asics[i['mac']]
if len(msg) > 0:
await self.sendmsg('\n'.join(msg))
async def runbot(self):
try:
res = await self.sendmsg('🟢 *Notify server online\!*')
INFO(f"Telegram channel ID: {res['chat']['id']}")
while 1:
if self.event.is_set():
SUCC('Telegram stopped!')
await self.sendmsg('🟡 Updating software\! Recommend check all running instances.')
break
await self.check()
await asyncio.sleep(15)
except error.Forbidden as e:
WARN(str(e))
except error.TimedOut as e:
WARN(str(e))
except Exception as e:
CRIT(str(e))
# os._exit(1)
async def stopalert(self):
while 1:
if self.event2.is_set():
await self.sendmsg('🔴 *Notify server offline\!*')
await asyncio.sleep(0.5)
async def main(self):
await asyncio.gather(self.stopalert(), self.runbot())
def run(self):
try:
if CONF.get('telegram', 'enable'):
SUCC('Telegram started!')
self.conn = connect(
host=CONF.get('db', 'host'),
user=CONF.get('db', 'user'),
password=CONF.get('db', 'password'),
database=CONF.get('db', 'name'))
self.conn.autocommit = True
self.bot = Bot(CONF.get('telegram', 'token'))
asyncio.run(self.main())
else:
while 1:
if self.event.is_set():
SUCC('Telegram stopped!')
break
sleep(5)
except Exception as e:
CRIT(str(e))
os._exit(1)