Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SW-3093 #35

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 68 additions & 31 deletions whatsapp_chatbot_python/bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import json
import logging
import time
from typing import NoReturn, Optional
from requests import Response

from whatsapp_api_client_python.API import GreenAPI, GreenAPIError

Expand Down Expand Up @@ -43,9 +45,14 @@ def __init__(
self._update_settings()
else:
self.logger.log(logging.DEBUG, "Updating instance settings.")

self.api.account.setSettings(settings)

try:
response = self.api.account.setSettings(settings)
self.__handle_response(response)
except Exception as error:
if self.raise_errors:
raise GreenAPIBotError(error)
self.logger.log(logging.ERROR, error)

if bot_debug_mode:
if not delete_notifications_at_startup:
delete_notifications_at_startup = True
Expand All @@ -69,14 +76,15 @@ def run_forever(self) -> Optional[NoReturn]:
while True:
try:
response = self.api.receiving.receiveNotification()

self.__handle_response(response)
if not response.data:
continue
response = response.data

self.router.route_event(response["body"])

self.api.receiving.deleteNotification(response["receiptId"])
response = self.api.receiving.deleteNotification(response["receiptId"])
self.__handle_response(response)
except KeyboardInterrupt:
break
except Exception as error:
Expand All @@ -96,32 +104,38 @@ def run_forever(self) -> Optional[NoReturn]:

def _update_settings(self) -> Optional[NoReturn]:
self.logger.log(logging.DEBUG, "Checking current instance settings.")

settings = self.api.account.getSettings()

response = settings.data

incoming_webhook = response["incomingWebhook"]
outgoing_message_webhook = response["outgoingMessageWebhook"]
outgoing_api_message_webhook = response["outgoingAPIMessageWebhook"]
if (
incoming_webhook == "no"
and outgoing_message_webhook == "no"
and outgoing_api_message_webhook == "no"
):
self.logger.log(
logging.INFO, (
"All message notifications are disabled. "
"Enabling incoming and outgoing notifications. "
"Settings will be applied within 5 minutes."
try:
response = self.api.account.getSettings()
self.__handle_response(response)

settings = response.data

incoming_webhook = settings["incomingWebhook"]
outgoing_message_webhook = settings["outgoingMessageWebhook"]
outgoing_api_message_webhook = settings["outgoingAPIMessageWebhook"]
if (
incoming_webhook == "no"
and outgoing_message_webhook == "no"
and outgoing_api_message_webhook == "no"
):
self.logger.log(
logging.INFO, (
"All message notifications are disabled. "
"Enabling incoming and outgoing notifications. "
"Settings will be applied within 5 minutes."
)
)
)

self.api.account.setSettings({
"incomingWebhook": "yes",
"outgoingMessageWebhook": "yes",
"outgoingAPIMessageWebhook": "yes"
})
response = self.api.account.setSettings({
"incomingWebhook": "yes",
"outgoingMessageWebhook": "yes",
"outgoingAPIMessageWebhook": "yes"
})
self.__handle_response(response)
except Exception as error:
if self.raise_errors:
raise GreenAPIBotError(error)
self.logger.log(logging.ERROR, error)

def _delete_notifications_at_startup(self) -> Optional[NoReturn]:
self.api.session.headers["Connection"] = "keep-alive"
Expand All @@ -132,11 +146,12 @@ def _delete_notifications_at_startup(self) -> Optional[NoReturn]:

while True:
response = self.api.receiving.receiveNotification()

self.__handle_response(response)
if not response.data:
break

self.api.receiving.deleteNotification(response.data["receiptId"])
response = self.api.receiving.deleteNotification(response.data["receiptId"])
self.__handle_response(response)

self.api.session.headers["Connection"] = "close"

Expand All @@ -162,6 +177,28 @@ def __prepare_logger(self) -> None:
else:
self.logger.setLevel(logging.DEBUG)

def __handle_response(self, response: Response) -> Optional[NoReturn]:
status_code = response.status_code
if status_code != 200 or self.debug_mode:
data = json.dumps(
json.loads(response.text), ensure_ascii=False, indent=4
)

if status_code != 200:
error_message = (
f"Request was failed with status code: {status_code}."
f" Data: {data}"
)

if self.raise_errors:
raise GreenAPIError(error_message)
self.logger.log(logging.ERROR, error_message)

return None

self.logger.log(
logging.DEBUG, f"Request was successful with data: {data}"
)

class GreenAPIBot(Bot):
pass
Expand Down
Loading