Spaces:
Sleeping
Sleeping
imseldrith
commited on
Create helper/messenger_api.py
Browse files- helper/messenger_api.py +54 -0
helper/messenger_api.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import os
|
3 |
+
from dotenv import load_dotenv
|
4 |
+
|
5 |
+
load_dotenv()
|
6 |
+
|
7 |
+
PAGE_ACCESS_TOKEN = os.getenv('PAGE_ACCESS_TOKEN')
|
8 |
+
|
9 |
+
def send_message(recipient_id, message_text, image_url=None):
|
10 |
+
if message_text:
|
11 |
+
message_data = {
|
12 |
+
'recipient': {'id': recipient_id},
|
13 |
+
'message': {'text': message_text}
|
14 |
+
}
|
15 |
+
call_send_api(message_data)
|
16 |
+
|
17 |
+
if image_url:
|
18 |
+
message_data = {
|
19 |
+
'recipient': {'id': recipient_id},
|
20 |
+
'message': {
|
21 |
+
'attachment': {
|
22 |
+
'type': 'image',
|
23 |
+
'payload': {'url': image_url}
|
24 |
+
}
|
25 |
+
}
|
26 |
+
}
|
27 |
+
call_send_api(message_data)
|
28 |
+
|
29 |
+
def call_send_api(message_data):
|
30 |
+
url = 'https://graph.facebook.com/v11.0/me/messages'
|
31 |
+
params = {
|
32 |
+
'access_token': PAGE_ACCESS_TOKEN
|
33 |
+
}
|
34 |
+
headers = {
|
35 |
+
'Content-Type': 'application/json'
|
36 |
+
}
|
37 |
+
response = requests.post(url, params=params, headers=headers, json=message_data)
|
38 |
+
if response.status_code != 200:
|
39 |
+
print(f'Failed to send message: {response.status_code}, {response.text}')
|
40 |
+
|
41 |
+
def set_typing_on(recipient_id):
|
42 |
+
message_data = {
|
43 |
+
'recipient': {'id': recipient_id},
|
44 |
+
'sender_action': 'typing_on'
|
45 |
+
}
|
46 |
+
call_send_api(message_data)
|
47 |
+
|
48 |
+
def set_typing_off(recipient_id):
|
49 |
+
message_data = {
|
50 |
+
'recipient': {'id': recipient_id},
|
51 |
+
'sender_action': 'typing_off'
|
52 |
+
}
|
53 |
+
call_send_api(message_data)
|
54 |
+
|