-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathAPI.py
More file actions
184 lines (147 loc) · 5.48 KB
/
API.py
File metadata and controls
184 lines (147 loc) · 5.48 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import json
import logging
from typing import Any, NoReturn, Optional
from requests import Response, Session
from requests.adapters import HTTPAdapter, Retry
from .response import Response as GreenAPIResponse
from .tools import (
account,
device,
groups,
journals,
marking,
queues,
receiving,
sending,
serviceMethods,
webhooks
)
class GreenApi:
host: str
media: str
idInstance: str
apiTokenInstance: str
def __init__(
self,
idInstance: str,
apiTokenInstance: str,
debug_mode: bool = False,
raise_errors: bool = False,
host: str = "https://api.green-api.com",
media: str = "https://media.green-api.com",
host_timeout: float = 180, # sec per retry
media_timeout: float = 10800, # sec per retry
):
self.host = host
self.media = media
self.debug_mode = debug_mode
self.raise_errors = raise_errors
# Change default values in init() if required
self.host_timeout = host_timeout
self.media_timeout = media_timeout
self.idInstance = idInstance
self.apiTokenInstance = apiTokenInstance
self.session = Session()
self.__prepare_session()
self.account = account.Account(self)
self.device = device.Device(self)
self.groups = groups.Groups(self)
self.journals = journals.Journals(self)
self.marking = marking.Marking(self)
self.queues = queues.Queues(self)
self.receiving = receiving.Receiving(self)
self.sending = sending.Sending(self)
self.serviceMethods = serviceMethods.ServiceMethods(self)
self.webhooks = webhooks.Webhooks(self)
self.logger = logging.getLogger("whatsapp-api-client-python")
self.__prepare_logger()
def request(
self,
method: str,
url: str,
payload: Optional[dict] = None,
files: Optional[dict] = None
) -> GreenAPIResponse:
url = url.replace("{{host}}", self.host)
url = url.replace("{{media}}", self.media)
url = url.replace("{{idInstance}}", self.idInstance)
url = url.replace("{{apiTokenInstance}}", self.apiTokenInstance)
headers = {
'User-Agent': 'GREEN-API_SDK_PY/1.0'
}
try:
if not files:
response = self.session.request(
method=method, url=url, json=payload, timeout=self.host_timeout, headers=headers
)
else:
response = self.session.request(
method=method, url=url, data=payload, files=files, timeout=self.media_timeout, headers=headers
)
except Exception as error:
error_message = f"Request was failed with error: {error}."
if self.raise_errors:
raise GreenAPIError(error_message)
self.logger.log(logging.CRITICAL, error_message)
return GreenAPIResponse(None, error_message)
self.__handle_response(response)
return GreenAPIResponse(response.status_code, response.text)
def raw_request(self, **arguments: Any) -> GreenAPIResponse:
try:
response = self.session.request(**arguments)
except Exception as error:
error_message = f"Request was failed with error: {error}."
if self.raise_errors:
raise GreenAPIError(error_message)
self.logger.log(logging.CRITICAL, error_message)
return GreenAPIResponse(None, error_message)
self.__handle_response(response)
return GreenAPIResponse(response.status_code, response.text)
def __handle_response(self, response: Response) -> Optional[NoReturn]:
status_code = response.status_code
if status_code != 200 or self.debug_mode:
try:
data = json.dumps(
json.loads(response.text), ensure_ascii=False, indent=4
)
except json.JSONDecodeError:
data = response.text
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}"
)
def __prepare_logger(self) -> None:
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
(
"%(asctime)s:%(name)s:"
"%(levelname)s:%(message)s"
), datefmt="%Y-%m-%d %H:%M:%S"
))
self.logger.addHandler(handler)
if not self.debug_mode:
self.logger.setLevel(logging.INFO)
else:
self.logger.setLevel(logging.DEBUG)
def __prepare_session(self) -> None:
self.session.headers["Connection"] = "close"
retry = Retry(
total=3,
backoff_factor=1.0,
allowed_methods=None,
status_forcelist=[429]
)
self.session.mount("http://", HTTPAdapter(max_retries=retry))
self.session.mount("https://", HTTPAdapter(max_retries=retry))
class GreenAPI(GreenApi):
pass
class GreenAPIError(Exception):
pass