API
- 1 ответ
- 0 вопросов
1
Вклад в тег
from datetime import datetime
from json import dumps
import requests
import os
from whatsapp_api_client_python import API
instance = API.GreenAPI(
"instance_id", "api_token"
)
def main():
instance.webhooks.startReceivingNotifications(handler)
def handler(type_webhook: str, body: dict) -> None:
if type_webhook == "incomingMessageReceived":
incoming_message_received(body)
def get_notification_time(timestamp: int) -> str:
return str(datetime.fromtimestamp(timestamp))
def save_file(download_url: str, filename: str) -> None:
response = requests.get(download_url)
if response.status_code == 200:
with open(filename, 'wb') as file:
file.write(response.content)
print(f"File saved as {filename}")
else:
print(f"Failed to download file: {response.status_code}")
def incoming_message_received(body: dict) -> None:
timestamp = body["timestamp"]
time = get_notification_time(timestamp)
data = dumps(body, ensure_ascii=False, indent=4)
# Full notification log
print(f"New incoming message at {time} with data: {data}", end="\n\n")
chat_id = body["senderData"]["chatId"]
message_type = body["messageData"]["typeMessage"]
acceptable_types = ("imageMessage", "videoMessage", "documentMessage", "audioMessage")
# chat_id.endswith("@g.us"): all group chats
# chat_id == "xxx@g.us" : one group chat, you can get this id with GetContacts method
if chat_id.endswith("@g.us") and message_type in acceptable_types:
download_url = body["messageData"]["fileMessageData"]["downloadUrl"]
filename = os.path.basename(body["messageData"]["fileMessageData"]["fileName"])
save_file(download_url, filename)
if __name__ == '__main__':
main()