diff --git a/requirements.txt b/requirements.txt index d150fee..c90d0c5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ requests==2.18.4 schedule==0.4.3 matplotlib==2.0.2 numpy==1.13.1 +matrix_client==0.1.0 diff --git a/targets.py b/targets.py new file mode 100644 index 0000000..cb553cf --- /dev/null +++ b/targets.py @@ -0,0 +1,76 @@ +import logging + +import requests + +from matrix_client.client import MatrixClient as MatrixApiClient +from matrix_client.errors import MatrixError + +class Client: + def send_image(self, target, path, name, content_type="image/png"): + raise NotImplementedError() + + def send_text(self, target, text): + raise NotImplementedError() + + +class MatrixClient(Client): + + def __init__(self, host, username, password): + self.client = MatrixApiClient(host) + self.client.login_with_password_no_sync(username=username, password=password) + self.log = logging.getLogger(__name__) + + def _get_room(self, target): + if target not in self.client.rooms: + try: + self.client.join_room(target) + except MatrixError as e: + self.log.error("could not join room '" + target + "'") + self.log.exception(e) + return None + return self.client.rooms[target] + + def send_image(self, target, path, name, content_type="image/png"): + """Send an image to a room + + Args: + target (str): The internal room id to post into + path (str/Path-like): The path to the image file + name (str): The name for the file in the room + content_type (str): Content-type of the image + """ + with open(path, "rb") as src: + data = src.read() + try: + mxc = self.client.api.media_upload(data, content_type) + except MatrixError as e: + self.log.exception(e) + return + room = self._get_room(target) + if room: + room.send_image(mxc['content_uri'], name) + + def send_text(self, target, text): + room = self._get_room(target) + if room: + room.send_text(text) + +class TelegramClient(Client): + + MESSAGE_URL = "https://api.telegram.org/bot{token}/sendMessage" + IMAGE_URL = "https://api.telegram.org/bot{token}/sendPhoto" + + def __init__(self, token): + self.text_url = self.MESSAGE_URL.format(token=token) + self.image_url = self.IMAGE_URL.format(token=token) + self.log = logging.getLogger(__name__) + + def send_image(self, target, path, name, content_type="image/png"): + files = {'photo': open(path, "rb")} + values = {"chat_id": target} + r = requests.post(self.image_url, files=files, data=values) + self.log.info("post photo: %s", r.status_code) + + def send_text(self, target, text): + response = requests.post(self.text_url, data={'chat_id': target, "text": text}) + self.log.info("post message: %s", response.status_code) \ No newline at end of file