5 min read

Building a Python Script to Monitor Hikvision NVR and Notify via Telegram

Learn how to create a Python script to monitor Hikvision NVR email alerts for camera connection loss and send instant notifications via a Telegram bot. Enhance your security system with automation and stay informed in real-time. Perfect for surveillance enthusiasts and IT professionals.

Introduction

In the dynamic realm of surveillance and security systems, keeping a vigilant eye on camera connections holds immense importance. This blog post is your guide to crafting a Python script that actively monitors Hikvision Network Video Recorder (NVR) email alerts and dispatches timely notifications through a Telegram bot. Let's delve into the world of automation that can significantly enhance your security setup while offering peace of mind.

Requirements

To embark on this journey, you'll need:

  • Familiarity with Python programming
  • A functioning Hikvision NVR with configured email alerts
  • A Telegram bot with an associated token
  • Basic knowledge of IMAP and SMTP protocols

Step 1: Setting Up a Telegram Bot

Start by creating a Telegram bot and acquiring its unique token from BotFather. BotFather is Telegram's official bot that helps you manage and create bots on the platform. Follow the steps in the official BotFather setup guide to create your bot and obtain the required token.

This token will serve as the key to interfacing with the Telegram API for sending notifications.

Step 2: Configuring Hikvision NVR Email Alerts

Configure your Hikvision NVR to dispatch email alerts whenever camera connections falter. To set up email alerts in your Hikvision NVR, follow the instructions provided in the Hikvision NVR Email Setup Guide. This comprehensive guide will walk you through the process, ensuring that your NVR is configured to send email alerts to the designated address.

This process necessitates specifying the designated email address for receiving alerts.

Step 3: Writing the Python Script

Begin by writing the Python script that will enable the monitoring of Hikvision NVR email alerts and the dispatch of notifications through a Telegram bot. The script is designed to automate the process and provide you with timely updates regarding camera connection issues.

#!/usr/bin/python3
import email, imaplib, requests
BOT_TOKEN = "00000000:asdasdasdqwdasda-RY"
CHAT_ID = "-123456789"
EMAIL_RECEIVER = 'notifications@email.com'
PWD = 'very_strong_password'
conn = imaplib.IMAP4_SSL("imap.email.com")
conn.login(EMAIL_RECEIVER, PWD)
conn.select('Inbox')
resp, items = conn.search(None, '(FROM "notifications@email.com")')
items = items[0].split()
for emailid in items:
    resp, data = conn.fetch(emailid, '(RFC822)')
    if resp == 'OK':
        email_body = data[0][1].decode('utf-8')
        mail = email.message_from_string(email_body)
        if "Video Signal Lost On Channel" in mail["Subject"]:
            camera_message = f"Camera Message: {mail['Subject']}"
            url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage?CHAT_ID={CHAT_ID}&text={camera_message}"
            print(requests.get(url).json())
    conn.store(emailid, '+FLAGS', '\\Deleted')
conn.close()

Code Breakdown

1. Shebang and Import

#!/usr/bin/python3
import email, imaplib, re, requests

The shebang at the beginning indicates that this script should be executed using the Python 3 interpreter. It imports necessary modules: email for handling email messages, imaplib for connecting to the IMAP email server, re for regular expressions, and requests for making HTTP requests.

2. Configuration

BOT_TOKEN = "00000000:asdasdasdqwdasda-RY"
CHAT_ID = "-123456789"
EMAIL_RECEIVER = 'notifications@email.com'
PWD = 'very_strong_password'

These are configuration constants that store your Telegram bot token (BOT_TOKEN), the chat ID where you want to send notifications (CHAT_ID), the email address to monitor (EMAIL_RECEIVER), and the password for that email account (PWD).

3. IMAP Connection

conn = imaplib.IMAP4_SSL("imap.email.com")
conn.login(EMAIL_RECEIVER, PWD)
conn.select('Inbox')

This part establishes a secure IMAP connection to the email server, logs in using the provided email and password, and selects the "Inbox" folder for further operations.

4. Email Retrieval and Processing

resp, items = conn.search(None, '(FROM "notifications@email.com")')
items = items[0].split()
for emailid in items:
    resp, data = conn.fetch(emailid, '(RFC822)')
    if resp == 'OK':
        email_body = data[0][1].decode('utf-8')
        mail = email.message_from_string(email_body)
        if mail["Subject"].find("Video Signal Lost On Channel") > 0:
            # ...

This section retrieves emails from the inbox that are sent from the specified email address. It iterates through the retrieved emails, decodes the email content from bytes to a string, and then checks if the subject contains the text "Video Signal Lost On Channel".

5. Regular Expression Matching

regex1 = r'8bit([\S\s]*?)--#boundary#'
b = re.findall(regex1, str(mail), re.DOTALL)
if b:
    b = [item.replace("\r\n", "\n") for item in b]
    for i in b:
        cameraMessage = "{i}"
        url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage?CHAT_ID={CHAT_ID}&text={cameraMessage}"
        print(requests.get(url).json())

If the subject matches, this section uses a regular expression (regex1) to extract specific information from the email content. It then constructs a URL for the Telegram bot API to send a message containing the extracted information to the specified chat. The requests.get(url).json() part sends the message to the Telegram bot.

6. Email Deletion and Connection Closure

conn.store(emailid, '+FLAGS', '\\Deleted')
conn.close()

After processing an email, it marks it as deleted using store() and then closes the IMAP connection.

This code snippet essentially automates the process of monitoring camera system notifications for signal loss and notifying the user via a Telegram bot. Keep in mind that you need to ensure the accuracy of the provided constants and adapt the code to your specific setup.

Conclusion

In this tutorial, we've explored how to leverage Python scripting to automate the monitoring of Hikvision NVR email alerts. By integrating a Telegram bot, you can receive instant notifications about camera connection issues, enhancing your security setup's effectiveness. Empower your surveillance system with automation and stay ahead of potential security challenges.

By following these steps, you can build a powerful Python script that acts as a vigilant guardian for your Hikvision NVR, ensuring that you're always informed about any camera connection losses.

Remember, security is paramount, and automation can be your ally in maintaining a robust surveillance setup. Stay proactive and stay secure with your customized Python script and Telegram bot integration.