import requests import os from dotenv import load_dotenv load_dotenv() PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN') def send_message(recipient_id, message_text, image_url=None): if message_text: message_data = { 'recipient': {'id': recipient_id}, 'message': {'text': message_text} } call_send_api(message_data) if image_url: message_data = { 'recipient': {'id': recipient_id}, 'message': { 'attachment': { 'type': 'image', 'payload': {'url': image_url} } } } call_send_api(message_data) def call_send_api(message_data): url = 'https://graph.facebook.com/v11.0/me/messages' params = { 'access_token': PAGE_ACCESS_TOKEN } headers = { 'Content-Type': 'application/json' } response = requests.post(url, params=params, headers=headers, json=message_data) if response.status_code != 200: print(f'Failed to send message: {response.status_code}, {response.text}') def set_typing_on(recipient_id): message_data = { 'recipient': {'id': recipient_id}, 'sender_action': 'typing_on' } call_send_api(message_data) def set_typing_off(recipient_id): message_data = { 'recipient': {'id': recipient_id}, 'sender_action': 'typing_off' } call_send_api(message_data)