2021-04-23 17:04:27 +02:00
|
|
|
import requests
|
|
|
|
|
|
|
|
from .abstract import AbstractPublisher
|
2021-07-05 21:44:11 +02:00
|
|
|
from .exceptions import (
|
|
|
|
InvalidBot,
|
|
|
|
InvalidCredentials,
|
|
|
|
InvalidEvent,
|
|
|
|
InvalidResponse,
|
|
|
|
)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
|
|
|
|
|
|
|
class TelegramPublisher(AbstractPublisher):
|
2021-07-05 21:44:11 +02:00
|
|
|
"""
|
|
|
|
Telegram publisher class.
|
|
|
|
"""
|
|
|
|
|
|
|
|
_conf = ("publisher", "telegram")
|
|
|
|
|
|
|
|
def post(self) -> None:
|
|
|
|
conf = self.conf
|
2021-04-23 17:04:27 +02:00
|
|
|
res = requests.post(
|
2021-07-05 21:44:11 +02:00
|
|
|
url=f"https://api.telegram.org/bot{conf.token}/sendMessage",
|
|
|
|
params={"chat_id": conf.chat_id, "text": self.message},
|
2021-04-23 17:04:27 +02:00
|
|
|
)
|
2021-07-05 21:44:11 +02:00
|
|
|
self._validate_response(res)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
2021-07-05 21:44:11 +02:00
|
|
|
def validate_credentials(self):
|
|
|
|
conf = self.conf
|
|
|
|
chat_id = conf.chat_id
|
|
|
|
token = conf.token
|
|
|
|
username = conf.username
|
|
|
|
err = []
|
|
|
|
if not chat_id:
|
|
|
|
err.append("chat ID")
|
|
|
|
if not token:
|
|
|
|
err.append("token")
|
|
|
|
if not username:
|
|
|
|
err.append("username")
|
|
|
|
if err:
|
|
|
|
self._log_error(
|
|
|
|
", ".join(err) + " is/are missing",
|
|
|
|
raise_error=InvalidCredentials,
|
|
|
|
)
|
2021-05-02 10:37:46 +02:00
|
|
|
|
|
|
|
res = requests.get(f"https://api.telegram.org/bot{token}/getMe")
|
|
|
|
data = self._validate_response(res)
|
|
|
|
|
|
|
|
if not username == data.get("result", {}).get("username"):
|
2021-07-05 21:44:11 +02:00
|
|
|
self._log_error(
|
|
|
|
"Found a different bot than the expected one",
|
|
|
|
raise_error=InvalidBot,
|
|
|
|
)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
2021-07-05 21:44:11 +02:00
|
|
|
def validate_event(self) -> None:
|
|
|
|
text = self.event.description
|
2021-04-23 17:04:27 +02:00
|
|
|
if not (text and text.strip()):
|
2021-07-05 21:44:11 +02:00
|
|
|
self._log_error("No text was found", raise_error=InvalidEvent)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
2021-05-02 10:37:46 +02:00
|
|
|
def _validate_response(self, res):
|
|
|
|
res.raise_for_status()
|
2021-04-23 17:04:27 +02:00
|
|
|
|
|
|
|
try:
|
|
|
|
data = res.json()
|
2021-07-05 21:44:11 +02:00
|
|
|
except Exception as e:
|
|
|
|
self._log_error(
|
|
|
|
f"Server returned invalid json data: {str(e)}",
|
|
|
|
raise_error=InvalidResponse,
|
|
|
|
)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
2021-05-02 10:37:46 +02:00
|
|
|
if not data.get("ok"):
|
2021-07-05 21:44:11 +02:00
|
|
|
self._log_error(
|
|
|
|
f"Invalid request (response: {data})",
|
|
|
|
raise_error=InvalidResponse,
|
|
|
|
)
|
2021-04-23 17:04:27 +02:00
|
|
|
|
|
|
|
return data
|
2021-07-05 21:44:11 +02:00
|
|
|
|
|
|
|
def validate_message(self) -> None:
|
|
|
|
# TODO implement
|
|
|
|
pass
|