Skip to content

Commit 6ea6771

Browse files
authored
Merge pull request #17 from green-api/dev
v0.7.0
2 parents d0798bc + 8f233e1 commit 6ea6771

5 files changed

Lines changed: 72 additions & 20 deletions

File tree

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ bot = GreenAPIBot(
4646
)
4747
```
4848

49+
### How to set up an instance
50+
51+
To start receiving incoming notifications, you need to set up an instance. Open the personal cabinet page at
52+
the [link](https://console.green-api.com/). Select an instance from the list and click on it. Click **Change**. In the *
53+
*Notifications** category, enable all notifications that you want to receive.
54+
4955
### How to start receiving and answering messages
5056

5157
To start receiving messages, you must create a handler function with one parameter (`notification`). The `notification`
@@ -60,6 +66,8 @@ brackets.
6066

6167
To start the bot, call the `bot.run_forever` function. You can stop the bot with the key combination Ctrl + C.
6268

69+
In this example, the bot will only answer the `message` message.
70+
6371
Link to example: [base.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/base.py).
6472

6573
```
@@ -82,6 +90,8 @@ You can receive not only incoming messages but also outgoing messages. You can a
8290
The body of the notification is in `notification.event`. In this example, we get the message type from the notification
8391
body.
8492

93+
In this example, the bot receives all incoming messages.
94+
8595
Link to example: [event.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/event.py).
8696

8797
```
@@ -163,6 +173,8 @@ command = ("help", "!/")
163173

164174
#### Example
165175

176+
In this example, the bot will send a photo in response to the `rates` command.
177+
166178
Link to example: [filters.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/filters.py).
167179

168180
```
@@ -316,6 +328,8 @@ To send a text message, you have to use the `notification.answer` method.
316328
To send a location, you have to use the `sending.sendLocation` method from `notification.api`.
317329
To send a message with a file, you have to use the `notification.answer_with_file` method.
318330

331+
In this example, the bot only responds to commands from the list above.
332+
319333
Link to example: [full.py](https://github.com/green-api/whatsapp-chatbot-python/blob/master/examples/full.py).
320334

321335
```python

docs/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ bot = GreenAPIBot(
4545
)
4646
```
4747

48+
### Как настроить инстанс
49+
50+
Чтобы начать получать входящие уведомления, нужно настроить инстанс. Открываем страницу личного кабинета
51+
по [ссылке](https://console.green-api.com/). Выбираем инстанс из списка и кликаем на него. Нажимаем **Изменить**. В
52+
категории **Уведомления** включаем все что необходимо получать.
53+
4854
### Как начать получать сообщения и отвечать на них
4955

5056
Чтобы начать получать сообщения, вам нужно создать функцию-обработчик с одним параметром (`notification`).
@@ -59,6 +65,8 @@ bot = GreenAPIBot(
5965
Чтобы запустить бота, нужно вызвать функцию `bot.run_forever`.
6066
Остановить бота можно с помощью сочетания клавиш Ctrl + C.
6167

68+
В этом примере бот ответит только на сообщение `message`.
69+
6270
Ссылка на пример: [base.py](../examples/base.py).
6371

6472
```
@@ -80,6 +88,8 @@ bot.run_forever()
8088

8189
Тело уведомления находится в `notification.event`. В этом примере мы отправляем в консоль тело нового уведомления.
8290

91+
В этом примере бот получает все входящие сообщения.
92+
8393
Ссылка на пример: [event.py](../examples/event.py).
8494

8595
```
@@ -162,6 +172,8 @@ command = ("help", "!/")
162172

163173
#### Пример
164174

175+
В этом примере бот отправит фотографию в ответ на команду `rates`.
176+
165177
Ссылка на пример: [filters.py](../examples/filters.py).
166178

167179
```
@@ -315,6 +327,8 @@ bot.run_forever()
315327
Чтобы отправить место (локацию), нужно использовать метод `sending.sendLocation` из `notification.api`.
316328
Чтобы отправить сообщение с файлом, нужно использовать метод `notification.answer_with_file`.
317329

330+
В этом примере бот отвечает только на комманды из списка выше.
331+
318332
Ссылка на пример: [full.py](../examples/full.py).
319333

320334
```python

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
setup(
77
name="whatsapp-chatbot-python",
8-
version="0.6.0",
8+
version="0.7.0",
99
description=(
1010
"This library helps you easily create"
1111
" a Python chatbot with WhatsApp API."

whatsapp_chatbot_python/bot.py

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from typing import NoReturn, Optional
22

3-
from whatsapp_api_client_python.API import GreenApi
3+
from whatsapp_api_client_python.API import GreenApi, Response
44

55
from .manager.router import Router
66

@@ -18,7 +18,7 @@ def __init__(
1818
if not settings:
1919
self._update_settings()
2020
else:
21-
self.api.account.setSettings(settings)
21+
self.__validate_response(self.api.account.setSettings(settings))
2222

2323
if delete_notifications_at_startup:
2424
self._delete_notifications_at_startup()
@@ -29,23 +29,27 @@ def run_forever(self) -> Optional[NoReturn]:
2929
while True:
3030
try:
3131
response = self.api.receiving.receiveNotification()
32-
if response.error:
33-
raise GreenAPIError(response.error)
32+
33+
self.__validate_response(response)
3434

3535
if not response.data:
3636
continue
3737
response = response.data
3838

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

41-
self.api.receiving.deleteNotification(response["receiptId"])
41+
self.__validate_response(
42+
self.api.receiving.deleteNotification(
43+
response["receiptId"]
44+
)
45+
)
4246
except KeyboardInterrupt:
4347
break
4448

4549
def _update_settings(self) -> Optional[NoReturn]:
4650
settings = self.api.account.getSettings()
47-
if settings.error:
48-
raise GreenAPIError(settings.error)
51+
52+
self.__validate_response(settings)
4953

5054
response = settings.data
5155

@@ -57,22 +61,37 @@ def _update_settings(self) -> Optional[NoReturn]:
5761
and outgoing_message_webhook == "no"
5862
and outgoing_api_message_webhook == "no"
5963
):
60-
self.api.account.setSettings({
61-
"incomingWebhook": "yes",
62-
"outgoingMessageWebhook": "yes",
63-
"outgoingAPIMessageWebhook": "yes"
64-
})
64+
self.__validate_response(
65+
self.api.account.setSettings({
66+
"incomingWebhook": "yes",
67+
"outgoingMessageWebhook": "yes",
68+
"outgoingAPIMessageWebhook": "yes"
69+
})
70+
)
6571

6672
def _delete_notifications_at_startup(self) -> Optional[NoReturn]:
6773
while True:
6874
response = self.api.receiving.receiveNotification()
69-
if response.error:
70-
raise GreenAPIError(response.error)
75+
76+
self.__validate_response(response)
7177

7278
if not response.data:
7379
break
7480

75-
self.api.receiving.deleteNotification(response.data["receiptId"])
81+
self.__validate_response(
82+
self.api.receiving.deleteNotification(
83+
response.data["receiptId"]
84+
)
85+
)
86+
87+
@staticmethod
88+
def __validate_response(response: Response) -> Optional[NoReturn]:
89+
if response.code != 200:
90+
if response.error:
91+
raise GreenAPIError(response.error)
92+
raise GreenAPIError(
93+
f"GreenAPI error occurred with status code {response.code}"
94+
)
7695

7796

7897
class GreenAPI(GreenApi):

whatsapp_chatbot_python/filters.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from abc import ABC, abstractmethod
2-
from re import fullmatch
2+
from re import RegexFlag, fullmatch
33
from typing import Dict, List, Optional, TYPE_CHECKING, Type, Union
44

55
if TYPE_CHECKING:
@@ -75,15 +75,20 @@ def check_event(self, notification: "Notification") -> bool:
7575

7676

7777
class RegExpFilter(AbstractFilter):
78-
def __init__(self, pattern: str):
79-
self.pattern = pattern
78+
def __init__(self, pattern: str, flags: Union[RegexFlag, int] = 0):
79+
if isinstance(pattern, str):
80+
self.pattern = pattern
81+
self.flags = flags
82+
elif isinstance(pattern, tuple):
83+
if len(pattern) == 2:
84+
self.pattern, self.flags = pattern
8085

8186
def check_event(self, notification: "Notification") -> bool:
8287
text_message = notification.message_text
8388
if text_message is None:
8489
return False
8590

86-
if fullmatch(self.pattern, text_message):
91+
if fullmatch(self.pattern, text_message, self.flags):
8792
return True
8893
return False
8994

0 commit comments

Comments
 (0)