summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEvgeny Zinoviev <me@ch1p.io>2021-04-15 16:34:56 +0300
committerEvgeny Zinoviev <me@ch1p.io>2021-04-15 16:34:56 +0300
commitdcf2cbdbeec56a8196b2b4d34848c85ab1530583 (patch)
tree4c5aabaef9382657f7b0ac0da9763efee9eaa525
initial
-rw-r--r--README6
-rwxr-xr-xmain.py71
2 files changed, 77 insertions, 0 deletions
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