Thursday, October 14, 2021

Motion + Telegram

Quick and dirty Motion + Telegram setup.

Camera config

 on_movie_end /home/djhedges/send_telegram.py %f


BotFarther

Send /newbot to @BotFarther to generate bot API key.

Create chat group with new bot.

Send a getUpdates request by modifying the script below to find the chat id.

Telegram Script

#!/usr/bin/python3


import os

import requests

import subprocess

import sys


API_KEY = ''

CHAT_ID = ''



def GenerateThumbnail(filepath):

    output_path = filepath[:-3] + '.jpg'

    ff_mpeg_cmd = ['ffmpeg', '-i', filepath, '-ss', '00:00:00.000', '-vframes', '1', output_path]

    subprocess.call(ff_mpeg_cmd)

    return output_path



def PostRequest(method, data, files):

    url = f'https://api.telegram.org/bot{API_KEY}/{method}'

    return requests.post(url=url, data=data, files=files, timeout=1000)



def SendVideo(filepath):

    thumbnail_path = GenerateThumbnail(filepath)

    with open(thumbnail_path, 'rb') as thumbnail_file:

        with open(filepath, 'rb') as video_file:

            response = PostRequest(

                    'sendVideo', {

                        'text': 'test',

                        'chat_id': CHAT_ID},

                    {'thumb': (os.path.basename(thumbnail_path), thumbnail_file),

                     'video': (os.path.basename(filepath), video_file)})



def main():

    filepath = sys.argv[1]

    if filepath.endswith('mp4'):

        SendVideo(filepath)



if __name__ == '__main__':

    main()


No comments: