import os, json, urllib.request, urllib.parse
from pathlib import Path

env = Path('/root/.hermes/.env').read_text()
tok_line = [l for l in env.splitlines() if l.startswith('TELEGRAM_BOT_TOKEN=')][0]
TOKEN = tok_line.split('=', 1)[1].strip()
CHAT = '7377499346'

body = Path('/tmp/digest_output.md').read_text()
data = urllib.parse.urlencode({'chat_id': CHAT, 'text': body, 'parse_mode': 'Markdown', 'disable_web_page_preview': 'true'}).encode()
req = urllib.request.Request(
    f'https://api.telegram.org/bot{TOKEN}/sendMessage',
    data=data,
    method='POST',
)
try:
    with urllib.request.urlopen(req, timeout=15) as r:
        resp = json.loads(r.read().decode())
        print('SEND status:', r.status)
        print('ok:', resp.get('ok'))
        if resp.get('ok'):
            print('message_id:', resp['result']['message_id'])
        else:
            print('error:', resp)
except Exception as e:
    print('ERR:', e)