diff options
-rwxr-xr-x | src/esp32cam_capture_diff_node.py | 12 | ||||
-rw-r--r-- | src/home/telegram/__init__.py | 1 | ||||
-rw-r--r-- | src/home/telegram/aio.py | 18 | ||||
-rw-r--r-- | src/home/telegram/telegram.py | 46 | ||||
-rw-r--r-- | src/home/util.py | 47 | ||||
-rwxr-xr-x | src/ipcam_server.py | 5 | ||||
-rwxr-xr-x | src/openwrt_log_analyzer.py | 5 | ||||
-rwxr-xr-x | test/test_record_upload.py | 2 | ||||
-rw-r--r-- | test/test_telegram_aio_send_photo.py | 31 |
9 files changed, 113 insertions, 54 deletions
diff --git a/src/esp32cam_capture_diff_node.py b/src/esp32cam_capture_diff_node.py index 38cb5b2..4363e9e 100755 --- a/src/esp32cam_capture_diff_node.py +++ b/src/esp32cam_capture_diff_node.py @@ -3,6 +3,7 @@ import asyncio import logging import os.path import tempfile +import home.telegram.aio as telegram from home.config import config from home.camera.esp32 import WebClient @@ -53,12 +54,19 @@ class ESP32CamCaptureDiffNode: self.nextpic = 1 if self.nextpic == 2 else 2 if not self.first: - score = await pyssim(filename, os.path.join(self.directory, self.getfilename())) - logger.debug(f'pyssim: diff={score}') + second_filename = os.path.join(self.directory, self.getfilename()) + score = await pyssim(filename, second_filename) + logger.debug(f'pyssim: score={score}') if score < config['pyssim']['threshold']: logger.info(f'score = {score}, informing central server') send_datagram(stringify([config['node']['name'], 2]), self.server_addr) + # send to telegram + if 'telegram' in config: + await telegram.send_message(f'pyssim: score={score}') + await telegram.send_photo(filename) + await telegram.send_photo(second_filename) + self.first = False logger.debug('capture: done') diff --git a/src/home/telegram/__init__.py b/src/home/telegram/__init__.py new file mode 100644 index 0000000..8565b40 --- /dev/null +++ b/src/home/telegram/__init__.py @@ -0,0 +1 @@ +from .telegram import send_message, send_photo
\ No newline at end of file diff --git a/src/home/telegram/aio.py b/src/home/telegram/aio.py new file mode 100644 index 0000000..fc87c1c --- /dev/null +++ b/src/home/telegram/aio.py @@ -0,0 +1,18 @@ +import functools +import asyncio + +from .telegram import ( + send_message as _send_message_sync, + send_photo as _send_photo_sync +) + + +async def send_message(*args, **kwargs): + loop = asyncio.get_event_loop() + return await loop.run_in_executor(None, functools.partial(_send_message_sync, *args, **kwargs)) + + +async def send_photo(*args, **kwargs): + loop = asyncio.get_event_loop() + return await loop.run_in_executor(None, functools.partial(_send_photo_sync, *args, **kwargs)) + diff --git a/src/home/telegram/telegram.py b/src/home/telegram/telegram.py new file mode 100644 index 0000000..9c7ea73 --- /dev/null +++ b/src/home/telegram/telegram.py @@ -0,0 +1,46 @@ +import requests +import logging + +from ..config import config + + +_logger = logging.getLogger(__name__) + + +def send_message(text: str, + parse_mode: str = None, + disable_web_page_preview: bool = False): + data, token = _send_telegram_data(text, parse_mode, disable_web_page_preview) + req = requests.post('https://api.telegram.org/bot%s/sendMessage' % token, data=data) + return req.json() + + +def send_photo(filename: str): + data = { + 'chat_id': config['telegram']['chat_id'], + } + token = config['telegram']['token'] + + url = f'https://api.telegram.org/bot{token}/sendPhoto' + with open(filename, "rb") as fd: + req = requests.post(url, data=data, files={"photo": fd}) + return req.json() + + +def _send_telegram_data(text: str, + parse_mode: str = None, + disable_web_page_preview: bool = False) -> tuple[dict, str]: + data = { + 'chat_id': config['telegram']['chat_id'], + 'text': text + } + + if parse_mode is not None: + data['parse_mode'] = parse_mode + elif 'parse_mode' in config['telegram']: + data['parse_mode'] = config['telegram']['parse_mode'] + + if disable_web_page_preview or 'disable_web_page_preview' in config['telegram']: + data['disable_web_page_preview'] = 1 + + return data, config['telegram']['token'] diff --git a/src/home/util.py b/src/home/util.py index 4e47f49..9dd84f6 100644 --- a/src/home/util.py +++ b/src/home/util.py @@ -1,17 +1,13 @@ -import functools import json import socket import time -import requests import subprocess import traceback import logging import string import random -import asyncio from enum import Enum -from .config import config from datetime import datetime from typing import Tuple, Optional @@ -100,49 +96,6 @@ def send_datagram(message: str, addr: Addr) -> None: sock.sendto(message.encode(), addr) -def send_telegram(text: str, - parse_mode: str = None, - disable_web_page_preview: bool = False): - data, token = _send_telegram_data(text, parse_mode, disable_web_page_preview) - r = requests.post('https://api.telegram.org/bot%s/sendMessage' % token, data=data) - if r.status_code != 200: - logger.error(r.text) - raise RuntimeError("telegram returned %d" % r.status_code) - - -async def send_telegram_aio(text: str, - parse_mode: str = None, - disable_web_page_preview: bool = False): - loop = asyncio.get_event_loop() - data, token = _send_telegram_data(text, parse_mode, disable_web_page_preview) - r = await loop.run_in_executor(None, - functools.partial(requests.post, - 'https://api.telegram.org/bot%s/sendMessage' % token, - data=data)) - if r.status_code != 200: - logger.error(r.text) - raise RuntimeError("telegram returned %d" % r.status_code) - - -def _send_telegram_data(text: str, - parse_mode: str = None, - disable_web_page_preview: bool = False) -> tuple[dict, str]: - data = { - 'chat_id': config['telegram']['chat_id'], - 'text': text - } - - if parse_mode is not None: - data['parse_mode'] = parse_mode - elif 'parse_mode' in config['telegram']: - data['parse_mode'] = config['telegram']['parse_mode'] - - if disable_web_page_preview or 'disable_web_page_preview' in config['telegram']: - data['disable_web_page_preview'] = 1 - - return data, config['telegram']['token'] - - def format_tb(exc) -> Optional[list[str]]: tb = traceback.format_tb(exc.__traceback__) if not tb: diff --git a/src/ipcam_server.py b/src/ipcam_server.py index 306f1c5..9e72e68 100755 --- a/src/ipcam_server.py +++ b/src/ipcam_server.py @@ -3,11 +3,12 @@ import logging import os import asyncio import time +import home.telegram.aio as telegram from apscheduler.schedulers.asyncio import AsyncIOScheduler from home.config import config -from home.util import parse_addr, send_telegram_aio +from home.util import parse_addr from home import http from home.database.sqlite import SQLiteBase from home.camera import util as camutil @@ -362,7 +363,7 @@ async def motion_notify_tg(camera: int, text += f'\nFragment: <b>{duration}s</b>, {dt1.strftime(fmt)}-{dt2.strftime(fmt)} ' text += _tg_links(TelegramLinkType.FRAGMENT, camera, f'{dt1.strftime(datetime_format)}__{dt2.strftime(datetime_format)}.mp4') - await send_telegram_aio(text) + await telegram.send_message(text) def _tg_links(link_type: TelegramLinkType, diff --git a/src/openwrt_log_analyzer.py b/src/openwrt_log_analyzer.py index f6d6413..bdfeb6c 100755 --- a/src/openwrt_log_analyzer.py +++ b/src/openwrt_log_analyzer.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 +import home.telegram as telegram + from home.config import config from home.database import BotsDatabase, SimpleState -from home.util import send_telegram """ config.toml example: @@ -44,7 +45,7 @@ def main(mac: str, title: str) -> int: max_id = log.id text = '\n'.join(map(lambda s: str(s), data)) - send_telegram(f'<b>{title}</b>\n\n' + text) + telegram.send_message(f'<b>{title}</b>\n\n' + text) return max_id diff --git a/test/test_record_upload.py b/test/test_record_upload.py index a0c3faf..cbd3ca2 100755 --- a/test/test_record_upload.py +++ b/test/test_record_upload.py @@ -4,7 +4,7 @@ import sys import os.path sys.path.extend([ os.path.realpath( - os.path.join(os.path.dirname(os.path.join(__file__)), '..', '..') + os.path.join(os.path.dirname(os.path.join(__file__)), '..') ) ]) diff --git a/test/test_telegram_aio_send_photo.py b/test/test_telegram_aio_send_photo.py new file mode 100644 index 0000000..705e534 --- /dev/null +++ b/test/test_telegram_aio_send_photo.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +import asyncio +import sys +import os.path +sys.path.extend([ + os.path.realpath( + os.path.join(os.path.dirname(os.path.join(__file__)), '..') + ) +]) + +import src.home.telegram.aio as telegram + +from src.home.config import config + + +async def main(): + await telegram.send_message(f'test message') + await telegram.send_photo('/tmp/3.jpg') + await telegram.send_photo('/tmp/4.jpg') + + +if __name__ == '__main__': + config.load('test_telegram_aio_send_photo') + + loop = asyncio.get_event_loop() + asyncio.ensure_future(main()) + + try: + loop.run_forever() + except KeyboardInterrupt: + pass |