reworked validation

This commit is contained in:
Simone Robutti 2021-05-02 10:37:46 +02:00
parent a6a14d2689
commit fb00516d6c
2 changed files with 32 additions and 42 deletions

View File

@ -4,63 +4,51 @@ from .abstract import AbstractPublisher
class TelegramPublisher(AbstractPublisher): class TelegramPublisher(AbstractPublisher):
def post(self) -> bool: def post(self) -> bool:
chat_id = self.credentials['chat_id'] chat_id = self.credentials["chat_id"]
text = self.event['text'] text = self.event["text"]
token = self.credentials['token'] token = self.credentials["token"]
post_params_kwargs = self.event.get('post_params_kwargs') post_params_kwargs = self.event.get("post_params_kwargs")
res = requests.post( res = requests.post(
url=f'https://api.telegram.org/bot{token}/sendMessage', url=f"https://api.telegram.org/bot{token}/sendMessage",
params=dict(chat_id=chat_id, text=text, **post_params_kwargs) params=dict(chat_id=chat_id, text=text, **post_params_kwargs),
) )
data = self.__validate_response(res) return self._validate_response(res)
if data.get('__error'):
self.log_error(data['__error'])
return False
return True def _log_error_and_raise(self, message):
self.log_error(message)
raise ValueError(message)
def validate_credentials(self) -> bool: def validate_credentials(self) -> bool:
chat_id = self.credentials.get('chat_id') chat_id = self.credentials.get("chat_id")
token = self.credentials.get('token') token = self.credentials.get("token")
username = self.credentials.get('username') username = self.credentials.get("username")
if any(a is None for a in (chat_id, token, username)): if all([chat_id, token, username]):
self.log_error("Required info is missing") # TODO: add composable errors to highlight which credentials are missing
return False self._log_error_and_raise("Some credentials are missing")
res = requests.get(f'https://api.telegram.org/bot{token}/getMe') res = requests.get(f"https://api.telegram.org/bot{token}/getMe")
data = self.__validate_response(res) data = self._validate_response(res)
if data.get('__error'):
self.log_error(data['__error'])
return False
if not username == data.get('result', {}).get('username'): if not username == data.get("result", {}).get("username"):
self.log_error("Found a different bot than the expected one!") self._log_error_and_raise("Found a different bot than the expected one")
return False return data
return True
def validate_event(self) -> bool: def validate_event(self) -> bool:
text = self.event.get('text') text = self.event.get("text")
if not (text and text.strip()): if not (text and text.strip()):
self.log_error(f"No text was found!") self._log_error_and_raise("No text was found. Invalid event")
return False
return True
@staticmethod def _validate_response(self, res):
def __validate_response(res): res.raise_for_status()
try:
res.raise_for_status()
except requests.exceptions.HTTPError as e:
return {'__error': str(e)}
try: try:
data = res.json() data = res.json()
except ValueError: except ValueError as e:
return {'__error': "Server returned invalid json data"} self.log_error("Server returned invalid json data")
raise ValueError from e
if not data.get('ok'): if not data.get("ok"):
data['__error'] = f"Invalid request (response: {data})" raise ValueError(f"Invalid request (response: {data})")
return data return data

2
setup.cfg Normal file
View File

@ -0,0 +1,2 @@
[flake8]
max-line-length=120