From dcf2cbdbeec56a8196b2b4d34848c85ab1530583 Mon Sep 17 00:00:00 2001 From: Evgeny Zinoviev Date: Thu, 15 Apr 2021 16:34:56 +0300 Subject: initial --- README | 6 ++++++ main.py | 71 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 README create mode 100755 main.py diff --git a/README b/README new file mode 100644 index 0000000..906577a --- /dev/null +++ b/README @@ -0,0 +1,6 @@ +# log-checker + +USAGE + +main.py --token "YOUR_TELEGRAM_TOKEN" --chat-id "YOUR_TELEGRAM_CHAT_ID" --log-file "/var/log/your.log" + diff --git a/main.py b/main.py new file mode 100755 index 0000000..36cf5d9 --- /dev/null +++ b/main.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +import requests +import sys +import traceback +import json +import os + +from argparse import ArgumentParser + + +def readstate(file: str) -> dict: + if not os.path.exists(file): + default_state = {'seek': 0} + writestate(file, default_state) + return default_state + + with open(file, 'r') as f: + return json.loads(f.read()) + + +def writestate(file: str, state: dict): + with open(file, 'w') as f: + f.write(json.dumps(state)) + + +def main(): + # parse arguments + parser = ArgumentParser() + parser.add_argument('--log-file', + type=str, + help='A file to read from') + parser.add_argument('--state-file', + default=('%s/.log-checker.state' % os.getenv('HOME'))) + parser.add_argument('--token', + help='Telegram bot token') + parser.add_argument('--chat-id', + type=int, + help='Telegram chat id (with bot)') + + args = parser.parse_args() + + # read file + state = readstate(args.state_file) + with open(args.log_file, 'r') as f: + # jump to the latest readed position + f.seek(state['seek']) + + # read till the end of the file + content = f.read() + + # save new position + state['seek'] = f.tell() + writestate(args.state_file, state) + + # if got something, send it to telegram + if content != '': + print('sending: %s' % content) + r = requests.post('https://api.telegram.org/bot%s/sendMessage' % args.token, data={ + 'chat_id': args.chat_id, + 'text': content + }) + print(r.status_code) + print(r.text) + + +if __name__ == '__main__': + try: + main() + except: + traceback.print_exc() + sys.exit(1) \ No newline at end of file -- cgit v1.2.3