Spaces:
Paused
Paused
Update func_facebook.py
Browse files- func_facebook.py +23 -19
func_facebook.py
CHANGED
@@ -1,37 +1,36 @@
|
|
1 |
import facebook
|
2 |
import requests
|
3 |
-
|
4 |
from func_ai import analyze_sentiment
|
5 |
|
6 |
GRAPH_API_URL = 'https://graph.facebook.com/v20.0'
|
7 |
|
8 |
-
|
9 |
def hide_negative_comments(token):
|
10 |
def init_facebook_client(token):
|
|
|
11 |
return facebook.GraphAPI(access_token=token)
|
12 |
|
13 |
def get_facebook_posts():
|
|
|
14 |
params = {
|
15 |
-
'include_inline_create': 'true'
|
16 |
}
|
17 |
graph = init_facebook_client(token)
|
18 |
|
19 |
-
# Fetching user posts
|
20 |
user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
|
21 |
user_posts = user_posts_data.get('data', [])
|
|
|
22 |
|
23 |
-
# Fetching ads posts
|
24 |
ads_posts_data = graph.get_object('me/ads_posts', **params)
|
25 |
ads_posts = ads_posts_data.get('data', [])
|
|
|
26 |
|
27 |
-
# Combine the posts from both sources
|
28 |
all_posts = user_posts + ads_posts
|
|
|
29 |
|
30 |
return all_posts
|
31 |
|
32 |
-
|
33 |
-
|
34 |
def get_comments_for_post(post_id):
|
|
|
35 |
graph = init_facebook_client(token)
|
36 |
comments = []
|
37 |
url = f'{post_id}/comments'
|
@@ -40,23 +39,25 @@ def hide_negative_comments(token):
|
|
40 |
comments_data = graph.get_object(id=url, **params)
|
41 |
visible_comments = [comment for comment in comments_data.get('data', []) if not comment.get('is_hidden', False)]
|
42 |
comments.extend(visible_comments)
|
|
|
43 |
if 'paging' in comments_data and 'next' in comments_data['paging']:
|
44 |
url = comments_data['paging']['next']
|
45 |
-
params = {}
|
46 |
else:
|
47 |
break
|
48 |
return comments
|
49 |
|
50 |
def filter_comments(comments, sentiments):
|
51 |
-
print("
|
52 |
negative_comments = []
|
53 |
for comment, sentiment in zip(comments, sentiments):
|
54 |
if sentiment['label'].lower() == 'negative':
|
55 |
-
print(f"
|
56 |
negative_comments.append(comment)
|
57 |
return negative_comments
|
58 |
|
59 |
def hide_comment(comment_id):
|
|
|
60 |
graph = init_facebook_client(token)
|
61 |
try:
|
62 |
graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST')
|
@@ -102,6 +103,7 @@ def hide_negative_comments(token):
|
|
102 |
|
103 |
|
104 |
def get_page_id(page_access_token):
|
|
|
105 |
url = f"{GRAPH_API_URL}/me"
|
106 |
params = {
|
107 |
"access_token": page_access_token,
|
@@ -116,6 +118,7 @@ def get_page_id(page_access_token):
|
|
116 |
|
117 |
|
118 |
def get_posts(page_id, page_access_token):
|
|
|
119 |
url = f"{GRAPH_API_URL}/{page_id}/posts"
|
120 |
url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true"
|
121 |
params = {
|
@@ -126,7 +129,6 @@ def get_posts(page_id, page_access_token):
|
|
126 |
posts = []
|
127 |
|
128 |
while True:
|
129 |
-
# Выполняем запрос для обычных постов
|
130 |
response = requests.get(url, params=params)
|
131 |
data = response.json()
|
132 |
|
@@ -134,10 +136,9 @@ def get_posts(page_id, page_access_token):
|
|
134 |
print(f"Ошибка при получении постов: {data['error']}")
|
135 |
break
|
136 |
|
137 |
-
# Добавляем обычные посты в общий список
|
138 |
posts.extend(data.get("data", []))
|
139 |
-
|
140 |
-
|
141 |
response_ads = requests.get(url_ads, params={"access_token": page_access_token, "fields": "id,message"})
|
142 |
data_ads = response_ads.json()
|
143 |
|
@@ -145,14 +146,12 @@ def get_posts(page_id, page_access_token):
|
|
145 |
print(f"Ошибка при получении рекламных постов: {data_ads['error']}")
|
146 |
break
|
147 |
|
148 |
-
# Добавляем рекламные посты в общий список
|
149 |
posts.extend(data_ads.get("data", []))
|
|
|
150 |
|
151 |
-
# Проверяем, есть ли следующие страницы для обычных постов
|
152 |
if 'paging' in data and 'next' in data['paging']:
|
153 |
url = data['paging']['next']
|
154 |
-
|
155 |
-
params = {}
|
156 |
else:
|
157 |
break
|
158 |
|
@@ -160,6 +159,7 @@ def get_posts(page_id, page_access_token):
|
|
160 |
|
161 |
|
162 |
def get_comments(post_id, page_access_token):
|
|
|
163 |
url = f"{GRAPH_API_URL}/{post_id}/comments"
|
164 |
params = {
|
165 |
"access_token": page_access_token,
|
@@ -173,6 +173,7 @@ def get_comments(post_id, page_access_token):
|
|
173 |
print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}")
|
174 |
break
|
175 |
comments.extend(data.get("data", []))
|
|
|
176 |
if 'paging' in data and 'next' in data['paging']:
|
177 |
url = data['paging']['next']
|
178 |
params = {}
|
@@ -182,6 +183,7 @@ def get_comments(post_id, page_access_token):
|
|
182 |
|
183 |
|
184 |
def has_page_replied(comment_id, page_id, page_access_token):
|
|
|
185 |
url = f"{GRAPH_API_URL}/{comment_id}/comments"
|
186 |
params = {
|
187 |
"access_token": page_access_token,
|
@@ -195,6 +197,7 @@ def has_page_replied(comment_id, page_id, page_access_token):
|
|
195 |
return False
|
196 |
for reply in data.get("data", []):
|
197 |
if reply['from']['id'] == page_id:
|
|
|
198 |
return True
|
199 |
if 'paging' in data and 'next' in data['paging']:
|
200 |
url = data['paging']['next']
|
@@ -240,6 +243,7 @@ def get_unanswered_comments(page_access_token):
|
|
240 |
|
241 |
|
242 |
def reply_comment(comment_id, message, token):
|
|
|
243 |
url = f"{GRAPH_API_URL}/{comment_id}/comments"
|
244 |
params = {
|
245 |
'access_token': token,
|
|
|
1 |
import facebook
|
2 |
import requests
|
|
|
3 |
from func_ai import analyze_sentiment
|
4 |
|
5 |
GRAPH_API_URL = 'https://graph.facebook.com/v20.0'
|
6 |
|
|
|
7 |
def hide_negative_comments(token):
|
8 |
def init_facebook_client(token):
|
9 |
+
print("Инициализация клиента Facebook.")
|
10 |
return facebook.GraphAPI(access_token=token)
|
11 |
|
12 |
def get_facebook_posts():
|
13 |
+
print("Получение постов.")
|
14 |
params = {
|
15 |
+
'include_inline_create': 'true'
|
16 |
}
|
17 |
graph = init_facebook_client(token)
|
18 |
|
|
|
19 |
user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
|
20 |
user_posts = user_posts_data.get('data', [])
|
21 |
+
print(f"Найдено {len(user_posts)} пользовательских постов.")
|
22 |
|
|
|
23 |
ads_posts_data = graph.get_object('me/ads_posts', **params)
|
24 |
ads_posts = ads_posts_data.get('data', [])
|
25 |
+
print(f"Найдено {len(ads_posts)} рекламных постов.")
|
26 |
|
|
|
27 |
all_posts = user_posts + ads_posts
|
28 |
+
print(f"Всего постов: {len(all_posts)}.")
|
29 |
|
30 |
return all_posts
|
31 |
|
|
|
|
|
32 |
def get_comments_for_post(post_id):
|
33 |
+
print(f"Получение комментариев для поста {post_id}.")
|
34 |
graph = init_facebook_client(token)
|
35 |
comments = []
|
36 |
url = f'{post_id}/comments'
|
|
|
39 |
comments_data = graph.get_object(id=url, **params)
|
40 |
visible_comments = [comment for comment in comments_data.get('data', []) if not comment.get('is_hidden', False)]
|
41 |
comments.extend(visible_comments)
|
42 |
+
print(f"Найдено {len(visible_comments)} видимых комментариев для поста {post_id}.")
|
43 |
if 'paging' in comments_data and 'next' in comments_data['paging']:
|
44 |
url = comments_data['paging']['next']
|
45 |
+
params = {}
|
46 |
else:
|
47 |
break
|
48 |
return comments
|
49 |
|
50 |
def filter_comments(comments, sentiments):
|
51 |
+
print("Фильтрация негативных комментариев.")
|
52 |
negative_comments = []
|
53 |
for comment, sentiment in zip(comments, sentiments):
|
54 |
if sentiment['label'].lower() == 'negative':
|
55 |
+
print(f"Негативный комментарий найден: {comment['message']}")
|
56 |
negative_comments.append(comment)
|
57 |
return negative_comments
|
58 |
|
59 |
def hide_comment(comment_id):
|
60 |
+
print(f"Скрытие комментария {comment_id}.")
|
61 |
graph = init_facebook_client(token)
|
62 |
try:
|
63 |
graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST')
|
|
|
103 |
|
104 |
|
105 |
def get_page_id(page_access_token):
|
106 |
+
print("Получение ID страницы.")
|
107 |
url = f"{GRAPH_API_URL}/me"
|
108 |
params = {
|
109 |
"access_token": page_access_token,
|
|
|
118 |
|
119 |
|
120 |
def get_posts(page_id, page_access_token):
|
121 |
+
print(f"Получение постов для страницы {page_id}.")
|
122 |
url = f"{GRAPH_API_URL}/{page_id}/posts"
|
123 |
url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true"
|
124 |
params = {
|
|
|
129 |
posts = []
|
130 |
|
131 |
while True:
|
|
|
132 |
response = requests.get(url, params=params)
|
133 |
data = response.json()
|
134 |
|
|
|
136 |
print(f"Ошибка при получении постов: {data['error']}")
|
137 |
break
|
138 |
|
|
|
139 |
posts.extend(data.get("data", []))
|
140 |
+
print(f"Получено {len(data.get('data', []))} постов.")
|
141 |
+
|
142 |
response_ads = requests.get(url_ads, params={"access_token": page_access_token, "fields": "id,message"})
|
143 |
data_ads = response_ads.json()
|
144 |
|
|
|
146 |
print(f"Ошибка при получении рекламных постов: {data_ads['error']}")
|
147 |
break
|
148 |
|
|
|
149 |
posts.extend(data_ads.get("data", []))
|
150 |
+
print(f"Получено {len(data_ads.get('data', []))} рекламных постов.")
|
151 |
|
|
|
152 |
if 'paging' in data and 'next' in data['paging']:
|
153 |
url = data['paging']['next']
|
154 |
+
params = {}
|
|
|
155 |
else:
|
156 |
break
|
157 |
|
|
|
159 |
|
160 |
|
161 |
def get_comments(post_id, page_access_token):
|
162 |
+
print(f"Получение комментариев для поста {post_id}.")
|
163 |
url = f"{GRAPH_API_URL}/{post_id}/comments"
|
164 |
params = {
|
165 |
"access_token": page_access_token,
|
|
|
173 |
print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}")
|
174 |
break
|
175 |
comments.extend(data.get("data", []))
|
176 |
+
print(f"Найдено {len(data.get('data', []))} комментариев.")
|
177 |
if 'paging' in data and 'next' in data['paging']:
|
178 |
url = data['paging']['next']
|
179 |
params = {}
|
|
|
183 |
|
184 |
|
185 |
def has_page_replied(comment_id, page_id, page_access_token):
|
186 |
+
print(f"Проверка ответа на комментарий {comment_id}.")
|
187 |
url = f"{GRAPH_API_URL}/{comment_id}/comments"
|
188 |
params = {
|
189 |
"access_token": page_access_token,
|
|
|
197 |
return False
|
198 |
for reply in data.get("data", []):
|
199 |
if reply['from']['id'] == page_id:
|
200 |
+
print(f"Страница {page_id} уже ответила на комментарий {comment_id}.")
|
201 |
return True
|
202 |
if 'paging' in data and 'next' in data['paging']:
|
203 |
url = data['paging']['next']
|
|
|
243 |
|
244 |
|
245 |
def reply_comment(comment_id, message, token):
|
246 |
+
print(f"Отправка ответа на комментарий {comment_id}.")
|
247 |
url = f"{GRAPH_API_URL}/{comment_id}/comments"
|
248 |
params = {
|
249 |
'access_token': token,
|