diff --git a/examples/python/whatsapp_echo_bot.py b/examples/python/whatsapp_echo_bot.py index da04514a..79bb5058 100644 --- a/examples/python/whatsapp_echo_bot.py +++ b/examples/python/whatsapp_echo_bot.py @@ -1,4 +1,6 @@ +import random from pprint import pprint +from time import sleep import requests from flask import Flask @@ -49,6 +51,30 @@ def send_seen(chat_id, message_id, participant): ) response.raise_for_status() +def start_typing(chat_id): + response = requests.post( + "http://localhost:3000/api/startTyping", + json={ + "session": "default", + "chatId": chat_id, + }, + ) + response.raise_for_status() + +def stop_typing(chat_id): + response = requests.post( + "http://localhost:3000/api/stopTyping", + json={ + "session": "default", + "chatId": chat_id, + }, + ) + response.raise_for_status() + +def typing(chat_id, seconds): + start_typing(chat_id=chat_id) + sleep(seconds) + stop_typing(chat_id=chat_id) @app.route("/") def whatsapp_echo(): @@ -69,7 +95,12 @@ def whatsapp_webhook(): # Payload that we've got payload = data["payload"] # The text - text = payload["body"] + text = payload.get("body") + if not text: + # We can't process non-text messages yet + print("No text in message") + print(payload) + return "OK" # Number in format 1231231231@c.us or @g.us for group chat_id = payload["from"] # Message ID - false_11111111111@c.us_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA @@ -79,9 +110,13 @@ def whatsapp_webhook(): # IMPORTANT - Always send seen before sending new message send_seen(chat_id=chat_id, message_id=message_id, participant=participant) + # Send a text back via WhatsApp HTTP API + typing(chat_id=chat_id, seconds=random.random() * 3) send_message(chat_id=chat_id, text=text) + # OR reply on the message + typing(chat_id=chat_id, seconds=random.random() * 3) reply(chat_id=chat_id, message_id=message_id, text=text) # Send OK back