summaryrefslogtreecommitdiff
path: root/src/home/telegram/telegram.py
blob: 9c7ea73cc7ceb476dee3e413097f7e20398632b3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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']