Skip to content

Commit

Permalink
SW-4576 Outgoing messages support
Browse files Browse the repository at this point in the history
  • Loading branch information
prostraction committed Dec 15, 2024
1 parent 51d1a1a commit bf7d3b9
Show file tree
Hide file tree
Showing 7 changed files with 79 additions and 14 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ from whatsapp_chatbot_python import GreenAPIBot, Notification

## Setup

Before launching the bot, you should enable incoming notifications in instance settings by using [SetSettings method](https://green-api.com/en/docs/api/account/SetSettings/).
Before launching the bot, you should remove Webhook Url (if set) from Personal Cabinet or by setting empty webhookUrl by using [SetSettings method](https://green-api.com/en/docs/api/account/SetSettings/). These settings will be enabled by bot automatically:


```json
Expand Down
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ from whatsapp_chatbot_python import GreenAPIBot, Notification

## Настройки

Перед запуском бота необходимо включить входящие уведомления в настройках экземпляра с помощью [метода SetSettings](https://green-api.com/en/docs/api/account/SetSettings/).
Перед запуском бота необходимо удалить (при наличии) адрес отправки уведомлений (URL) из личного кабинета или выставив пустой webhookUrl с помощью [метода SetSettings](https://green-api.com/en/docs/api/account/SetSettings/). Следующие настройки будут включены ботом автоматически:

```json
{
Expand Down
18 changes: 18 additions & 0 deletions examples/groups_filter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from whatsapp_chatbot_python import GreenAPIBot, Notification

bot = GreenAPIBot(
"1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345"
)

@bot.router.message()
def message_handler(notification: Notification) -> None:
if "@g.us" in notification.get_chat():
print("Incoming message", notification.get_id_message(), "in group chat", notification.get_chat(), "from", notification.get_sender())
notification.answer("Hello, group!")
# Add your implementation
if "@c.us" in notification.get_chat():
print("Incoming message", notification.get_id_message(), "in contact chat", notification.get_chat())
notification.answer("Hello, contact!")
# Add your implementation

bot.run_forever()
30 changes: 30 additions & 0 deletions examples/outgoing_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from whatsapp_chatbot_python import GreenAPIBot, Notification

bot = GreenAPIBot(
"1101000001", "d75b3a66374942c5b3c019c698abc2067e151558acbd412345"
)

# Handle message, which sent from this instance without API
@bot.router.outgoing_message()
def message_handler(notification: Notification) -> None:
print("Outgoing Message: ", notification.get_id_message())
print("Sender:", notification.get_sender())
print("Chat:", notification.get_chat())
print("Message Text:", notification.get_message_text())
print("Message:", notification.get_message_data())

# Handle message, which sent from this instance with API
@bot.router.outgoing_api_message()
def message_handler(notification: Notification) -> None:
print("Outgoing Message from API: ", notification.get_id_message())
print("Sender:", notification.get_sender())
print("Chat:", notification.get_chat())
print("Message Text:", notification.get_message_text())
print("Message:", notification.get_message_data())

# Handle status of any sent message from this instance (sent, delivired, read)
@bot.router.outgoing_message_status()
def message_handler(notification: Notification) -> None:
print("Status of message:", notification.get_id_message(), "is", notification.get_status_message())

bot.run_forever()
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="whatsapp-chatbot-python",
version="0.9.3",
version="0.9.4",
description=(
"This library helps you easily create"
" a Python chatbot with WhatsApp API."
Expand Down
37 changes: 27 additions & 10 deletions whatsapp_chatbot_python/manager/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,33 @@ def get_sender(self) -> Optional[str]:
return self.event["senderData"]["sender"]

def get_message_text(self) -> Optional[str]:
message_data = self.event["messageData"]

type_message = message_data["typeMessage"]
if type_message == "textMessage":
return message_data["textMessageData"]["textMessage"]
elif (
type_message == "extendedTextMessage"
or type_message == "quotedMessage"
):
return message_data["extendedTextMessageData"]["text"]
type_webhook = self.event["typeWebhook"]
if type_webhook != "outgoingMessageStatus":
message_data = self.event["messageData"]

type_message = message_data["typeMessage"]
if type_message == "textMessage":
return message_data["textMessageData"]["textMessage"]
elif (
type_message == "extendedTextMessage"
or type_message == "quotedMessage"
):
return message_data["extendedTextMessageData"]["text"]

def get_id_message(self) -> Optional[str]:
id_message = self.event['idMessage']
return id_message

def get_status_message(self) -> Optional[str]:
type_webhook = self.event["typeWebhook"]
if type_webhook == "outgoingMessageStatus":
return self.event["status"]

def get_message_data(self) -> Optional[str]:
type_webhook = self.event["typeWebhook"]
if type_webhook != "outgoingMessageStatus":
message_data = self.event["messageData"]
return message_data

def answer(
self,
Expand Down
2 changes: 1 addition & 1 deletion whatsapp_chatbot_python/manager/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def route_event(self, event: dict) -> None:
observer = self.observers.get(type_webhook)
if observer:
data = json.dumps(event, ensure_ascii=False, indent=4)

self.logger.log(
logging.DEBUG, (
f"Routing {type_webhook} event with data: {data}"
Expand Down

0 comments on commit bf7d3b9

Please sign in to comment.