How to stop worrying and start living

Monitoring the work of the organization using docker and telegram bot

Many would like to know if something suddenly happens to their website, store, etc., especially if it does not require money, time, or effort. But this is quite easy to do: after spending quite a bit of free time, we will create a docker container that will periodically make queries to the database, calculate some metrics based on them, compare them with threshold values ​​and, if these thresholds are exceeded, notify interested parties.





The first step is to start a bot. You can google how to do this in 5 minutes. For example, there was an article here recently . Also, our bot needs permission to add it to groups if more than one person is planning to receive messages. To do this, when creating a bot, you need to write the BotFather command "/ setjoingroups". After that, in fact, you need to create a group, add our bot and everyone interested in receiving messages to it.





pytelegrambotapi , CHAT_ID , , , , Β«/startΒ». . , , , CHAT_ID :





import logging

import telebot

bot = telebot.TeleBot(TOKEN)
chat_id = CHAT_ID
logger = telebot.logger
telebot.logger.setLevel(logging.DEBUG)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, ',    /start')
bot.polling()
      
      



:





bot.send_message(chat_id=CHAT_ID, text=TEXT)
      
      



, . , . , , - .





, . pymysql. :






import datetime
import os
from contextlib import closing
import pymysql
from pymysql.cursors import DictCursor
from constants import *

class Monitor:
    
def __init__(self):
        self.starttime = datetime.datetime.today()
        self.port = 3306
        self.host = os.environ.get('MYSQL_HOST')
        self.user = os.environ.get('USER')
        self.password = os.environ.get('MYSQL_PWD')
        self.db_name = 'backend'

def sms_log(self):
    with closing(pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password,db=self.db_name, charset='utf8', cursorclass=DictCursor)) as connection:
        end_time = datetime.datetime.today()
        start_time = end_time - datetime.timedelta(minutes=TIME_PERIOD)
        st_time = start_time.strftime('%Y-%m-%d %H:%M:%S')        
        end_time = end_time.strftime('%Y-%m-%d %H:%M:%S')
        with connection.cursor() as cursor:
            query = f"SELECT COUNT(*) FROM sms_log WHERE created_at BETWEEN '{st_time}' AND '{end_time}'"
            cursor.execute(query)
            for row in cursor:
                result = row['COUNT(*)']
                if result < SMS_COUNT_ALERT:
                    return f" {TIME_PERIOD}   \
            f"{start_time.strftime('%H:%M')} " \
                 f"  {result} , : {SMS_COUNT_ALERT}"
      
      



, , , . :






def main():
    bot = telebot.TeleBot(TOKEN)
    chat_id = CHAT_ID
    logger = telebot.logger
    telebot.logger.setLevel(logging.DEBUG)  
    monitor = Monitor()
    while True:
        """ 
             15 (TIME_PERIOD) . 
        """
      result = monitor.sms_log()
      if result:
            bot.send_message(
            chat_id=chat_id, 
            text=result,
            disable_notification=not monitor.is_day()
        )

      . . .

      sleep(TIME_PERIOD*60)
      
      



, , :





disable_notification=not monitor.is_day()
      
      







@staticmethod
def is_day():
    if 9 <= (datetime.datetime.today()).hour <= 23:
        return True
    else:
        return False
      
      



.





, , - , .





:





FROM python:3.6-alpine

COPY requirements.txt requirements.txt

RUN python -m venv venv
RUN venv/bin/pip install -r requirements.txt
RUN apk add bash

COPY src src
COPY .gitignore .gitignore
COPY boot.sh boot.sh

CMD ["bash", "./boot.sh"]
      
      



requirements.txt:





PyMySQL==1.0.2
pyTelegramBotAPI==3.7.6
      
      



boot.sh:





#!/bin/sh
source venv/bin/activate
exec python ./src/bot.py
      
      



You can skip installing bash and replace it with /bin/sh



, I'm more used to it when debugging, but on combat conditions it's superfluous. You can also choose a newer image, but this one will do just fine.





Now you need to build it:





docker build -t bot:latest .
      
      



And run by passing environment variables to connect to the database in the command:





docker run --name bot -d -e USER= -e MYSQL_HOST= -e \
MYSQL_PWD= bot:latest
      
      



And you can wait for messages. Well, or not to wait, it all depends on the metrics. Business for half a day maximum. However, by spending them, we get round-the-clock monitoring of the system. Almost for nothing.





Then you can, for example, configure the transfer of calculated metrics to Zabbix or a similar tool for logging, graphs, reports, and more.








All Articles