Spaces:
Paused
Paused
Update func_facebook.py
Browse files- func_facebook.py +178 -195
func_facebook.py
CHANGED
@@ -1,133 +1,177 @@
|
|
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 |
|
8 |
-
def
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
60 |
return comments
|
61 |
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
|
|
|
|
|
|
75 |
graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST')
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
84 |
return []
|
85 |
|
86 |
-
hidden_comments_per_post = []
|
87 |
processed_comment_ids = set() # Отслеживание обработанных комментариев
|
|
|
88 |
|
89 |
-
for
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
if not comments:
|
94 |
-
print(f"Нет комментариев для поста {post_id}.")
|
95 |
continue
|
|
|
|
|
|
|
96 |
|
97 |
-
|
98 |
-
|
99 |
-
comments_to_process = []
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
if comment_id in processed_comment_ids:
|
104 |
-
print(f"Комментарий {comment_id} уже обработан. Пропуск.")
|
105 |
-
continue
|
106 |
-
processed_comment_ids.add(comment_id)
|
107 |
-
comments_text.append(comment['message'])
|
108 |
-
comments_to_process.append(comment)
|
109 |
|
110 |
-
|
111 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
112 |
|
113 |
-
|
114 |
-
negative_comments = filter_comments(comments_to_process, sentiments)
|
115 |
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
'message': comment['message']
|
121 |
-
})
|
122 |
|
123 |
-
if
|
124 |
-
|
125 |
'post_id': post_id,
|
126 |
'post_message': post_message,
|
127 |
-
'
|
128 |
})
|
129 |
-
|
130 |
-
return hidden_comments_per_post
|
131 |
|
132 |
|
133 |
def get_page_id(page_access_token):
|
@@ -145,53 +189,6 @@ def get_page_id(page_access_token):
|
|
145 |
return data.get("id")
|
146 |
|
147 |
|
148 |
-
def get_posts(page_id, page_access_token):
|
149 |
-
print(f"Получение постов для страницы {page_id}.")
|
150 |
-
url = f"{GRAPH_API_URL}/{page_id}/posts"
|
151 |
-
url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true"
|
152 |
-
params = {
|
153 |
-
"access_token": page_access_token,
|
154 |
-
"fields": "id,message",
|
155 |
-
"limit": 50
|
156 |
-
}
|
157 |
-
params_ads = {
|
158 |
-
"access_token": page_access_token,
|
159 |
-
"fields": "id,message",
|
160 |
-
"limit": 150
|
161 |
-
}
|
162 |
-
|
163 |
-
posts = []
|
164 |
-
|
165 |
-
while True:
|
166 |
-
response = requests.get(url, params=params)
|
167 |
-
data = response.json()
|
168 |
-
|
169 |
-
if 'error' in data:
|
170 |
-
print(f"Ошибка при получении постов: {data['error']}")
|
171 |
-
break
|
172 |
-
|
173 |
-
posts.extend(data.get("data", []))
|
174 |
-
print(f"Получено {len(data.get('data', []))} постов.")
|
175 |
-
|
176 |
-
response_ads = requests.get(url_ads, params=params_ads)
|
177 |
-
data_ads = response_ads.json()
|
178 |
-
|
179 |
-
if 'error' in data_ads:
|
180 |
-
print(f"Ошибка при получении рекламных постов: {data_ads['error']}")
|
181 |
-
break
|
182 |
-
|
183 |
-
posts.extend(data_ads.get("data", []))
|
184 |
-
print(f"Получено {len(data_ads.get('data', []))} рекламных постов.")
|
185 |
-
|
186 |
-
if 'paging' in data and 'next' in data['paging']:
|
187 |
-
url = data['paging']['next']
|
188 |
-
params = {}
|
189 |
-
else:
|
190 |
-
break
|
191 |
-
|
192 |
-
return posts
|
193 |
-
|
194 |
-
|
195 |
def get_comments(post_id, page_access_token):
|
196 |
print(f"Получение комментариев для поста {post_id}.")
|
197 |
url = f"{GRAPH_API_URL}/{post_id}/comments"
|
@@ -201,19 +198,13 @@ def get_comments(post_id, page_access_token):
|
|
201 |
"limit": 150,
|
202 |
}
|
203 |
comments = []
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
print(f"Найдено {len(data.get('data', []))} комментариев.")
|
212 |
-
if 'paging' in data and 'next' in data['paging']:
|
213 |
-
url = data['paging']['next']
|
214 |
-
params = {}
|
215 |
-
else:
|
216 |
-
break
|
217 |
return comments
|
218 |
|
219 |
|
@@ -224,34 +215,29 @@ def has_page_replied(comment_id, page_id, page_access_token):
|
|
224 |
"access_token": page_access_token,
|
225 |
"fields": "from{id},message",
|
226 |
}
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
print(f"Ошибка при запросе API: {response.status_code} - {response.text}")
|
232 |
-
return False
|
233 |
-
data = response.json()
|
234 |
-
if 'error' in data:
|
235 |
-
print(f"Ошибка при получении ответов на комментарий {comment_id}: {data['error']}")
|
236 |
-
return False
|
237 |
-
for reply in data.get("data", []):
|
238 |
-
reply_from = reply.get('from', {})
|
239 |
-
reply_from_id = reply_from.get('id')
|
240 |
-
reply_message = reply.get('message', '')
|
241 |
-
print(f"Найдена реплика от пользователя: {reply_from_id}, сообщение: {reply_message}")
|
242 |
-
if reply_from_id == page_id:
|
243 |
-
print(f"Страница {page_id} уже ответила на комментарий {comment_id}.")
|
244 |
-
return True
|
245 |
-
if 'paging' in data and 'next' in data['paging']:
|
246 |
-
url = data['paging']['next']
|
247 |
-
params = {}
|
248 |
-
else:
|
249 |
-
break
|
250 |
-
except requests.exceptions.RequestException as e:
|
251 |
-
print(f"Ошибка при выполнении запроса: {e}")
|
252 |
return False
|
253 |
-
|
254 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
255 |
|
256 |
|
257 |
def get_unanswered_comments(page_access_token):
|
@@ -303,6 +289,3 @@ def reply_comment(comment_id, message, token):
|
|
303 |
else:
|
304 |
print(f"Ошибка при отправке ответа: {response.text}")
|
305 |
return False
|
306 |
-
|
307 |
-
|
308 |
-
|
|
|
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 init_facebook_client(token):
|
10 |
+
print("Инициализация клиента Facebook.")
|
11 |
+
return facebook.GraphAPI(access_token=token)
|
12 |
+
|
13 |
+
|
14 |
+
def get_posts(page_id, page_access_token):
|
15 |
+
print(f"Получение постов для страницы {page_id}.")
|
16 |
+
url = f"{GRAPH_API_URL}/{page_id}/posts"
|
17 |
+
url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true"
|
18 |
+
params = {
|
19 |
+
"access_token": page_access_token,
|
20 |
+
"fields": "id,message",
|
21 |
+
"limit": 50
|
22 |
+
}
|
23 |
+
params_ads = {
|
24 |
+
"access_token": page_access_token,
|
25 |
+
"fields": "id,message",
|
26 |
+
"limit": 150
|
27 |
+
}
|
28 |
+
|
29 |
+
posts = []
|
30 |
+
|
31 |
+
response = requests.get(url, params=params)
|
32 |
+
data = response.json()
|
33 |
+
|
34 |
+
if 'error' in data:
|
35 |
+
print(f"Ошибка при получении постов: {data['error']}")
|
36 |
+
|
37 |
+
posts.extend(data.get("data", []))
|
38 |
+
print(f"Получено {len(data.get('data', []))} постов.")
|
39 |
+
|
40 |
+
response_ads = requests.get(url_ads, params=params_ads)
|
41 |
+
data_ads = response_ads.json()
|
42 |
+
|
43 |
+
if 'error' in data_ads:
|
44 |
+
print(f"Ошибка при получении рекламных постов: {data_ads['error']}")
|
45 |
+
|
46 |
+
posts.extend(data_ads.get("data", []))
|
47 |
+
print(f"Получено {len(data_ads.get('data', []))} рекламных постов.")
|
48 |
+
|
49 |
+
return posts
|
50 |
+
|
51 |
+
|
52 |
+
def get_facebook_posts(graph):
|
53 |
+
print("Получение постов.")
|
54 |
+
params = {
|
55 |
+
'include_inline_create': 'true',
|
56 |
+
"limit": 150
|
57 |
+
}
|
58 |
+
|
59 |
+
user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
|
60 |
+
user_posts = user_posts_data.get('data', [])
|
61 |
+
print(f"Найдено {len(user_posts)} пользовательских постов.")
|
62 |
+
|
63 |
+
try:
|
64 |
+
ads_posts_data = graph.get_object('me/ads_posts', **params)
|
65 |
+
ads_posts = ads_posts_data.get('data', [])
|
66 |
+
print(f"Найдено {len(ads_posts)} рекламных постов.")
|
67 |
+
except facebook.GraphAPIError as e:
|
68 |
+
print(f"Ошибка при получении рекламных постов: {e}")
|
69 |
+
ads_posts = []
|
70 |
+
|
71 |
+
all_posts = user_posts + ads_posts
|
72 |
+
unique_posts_dict = {post['id']: post for post in all_posts}
|
73 |
+
unique_posts = list(unique_posts_dict.values())
|
74 |
+
print(f"Всего уникальных постов: {len(unique_posts)}.")
|
75 |
+
|
76 |
+
return unique_posts
|
77 |
+
|
78 |
+
|
79 |
+
def get_comments_for_post(post_id, graph):
|
80 |
+
print(f"Получение комментариев для поста {post_id}.")
|
81 |
+
|
82 |
+
comments = []
|
83 |
+
url = f'{post_id}/comments'
|
84 |
+
params = {'fields': 'id,message,is_hidden', 'limit': 10000}
|
85 |
+
try:
|
86 |
+
comments_data = graph.get_object(id=url, **params)
|
87 |
+
visible_comments = [comment for comment in comments_data.get('data', []) if not comment.get('is_hidden', False)]
|
88 |
+
comments.extend(visible_comments)
|
89 |
+
print(f"Найдено {len(visible_comments)} видимых комментариев для поста {post_id}.")
|
90 |
+
except facebook.GraphAPIError as e:
|
91 |
+
print(f"Ошибка при получении комментариев для поста {post_id}: {e}")
|
92 |
+
finally:
|
93 |
return comments
|
94 |
|
95 |
+
|
96 |
+
def filter_comments(comments, sentiments):
|
97 |
+
print("Фильтрация негативных комментариев.")
|
98 |
+
negative_comments = []
|
99 |
+
for comment, sentiment in zip(comments, sentiments):
|
100 |
+
if sentiment['label'].lower() == 'negative':
|
101 |
+
print(f"Негативный комментарий найден: {comment['message']}")
|
102 |
+
negative_comments.append(comment)
|
103 |
+
return negative_comments
|
104 |
+
|
105 |
+
|
106 |
+
def hide_or_delete_comment(comment_id, graph, action):
|
107 |
+
print(f"Выбранное действие для комментария {comment_id}: {action}")
|
108 |
+
try:
|
109 |
+
if action == "Delete":
|
110 |
+
graph.request(f'{comment_id}', method='DELETE')
|
111 |
+
elif action == "Hide":
|
112 |
graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST')
|
113 |
+
return True
|
114 |
+
except facebook.GraphAPIError as e:
|
115 |
+
print(f"Ошибка при скрытии/удалении комментария {comment_id}: {e}")
|
116 |
+
return False
|
117 |
|
118 |
+
|
119 |
+
def process_negative_comments_in_post(post_id, token, action):
|
120 |
+
graph = init_facebook_client(token)
|
121 |
+
comments_in_post = get_comments_for_post(post_id, graph)
|
122 |
+
if not comments_in_post:
|
123 |
+
print(f"Нет комментариев для поста {post_id}.")
|
124 |
return []
|
125 |
|
|
|
126 |
processed_comment_ids = set() # Отслеживание обработанных комментариев
|
127 |
+
comments, comments_text, comments_to_process = [], [], []
|
128 |
|
129 |
+
for comment in comments_in_post:
|
130 |
+
comment_id = comment['id']
|
131 |
+
if comment_id in processed_comment_ids:
|
132 |
+
print(f"Комментарий {comment_id} уже обработан. Пропуск.")
|
|
|
|
|
133 |
continue
|
134 |
+
processed_comment_ids.add(comment_id)
|
135 |
+
comments_text.append(comment['message'])
|
136 |
+
comments_to_process.append(comment)
|
137 |
|
138 |
+
if not comments_to_process:
|
139 |
+
return []
|
|
|
140 |
|
141 |
+
sentiments = analyze_sentiment(comments_text)
|
142 |
+
negative_comments = filter_comments(comments_to_process, sentiments)
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
|
144 |
+
for comment in negative_comments:
|
145 |
+
if hide_or_delete_comment(comment['id'], graph, action):
|
146 |
+
comments.append({
|
147 |
+
'id': comment['id'],
|
148 |
+
'message': comment['message']
|
149 |
+
})
|
150 |
+
return comments
|
151 |
+
|
152 |
+
|
153 |
+
def process_negative_comments(token, action):
|
154 |
+
graph = init_facebook_client(token)
|
155 |
+
posts = get_facebook_posts(graph)
|
156 |
+
|
157 |
+
if not posts:
|
158 |
+
print("Нет ��остов для обработки.")
|
159 |
+
return []
|
160 |
|
161 |
+
comments_per_post = []
|
|
|
162 |
|
163 |
+
for post in posts:
|
164 |
+
post_id = post['id']
|
165 |
+
post_message = post.get('message', '')
|
166 |
+
comments = process_negative_comments_in_post(post_id, token, action)
|
|
|
|
|
167 |
|
168 |
+
if comments != []:
|
169 |
+
comments_per_post.append({
|
170 |
'post_id': post_id,
|
171 |
'post_message': post_message,
|
172 |
+
'comments': comments
|
173 |
})
|
174 |
+
return comments_per_post
|
|
|
175 |
|
176 |
|
177 |
def get_page_id(page_access_token):
|
|
|
189 |
return data.get("id")
|
190 |
|
191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
192 |
def get_comments(post_id, page_access_token):
|
193 |
print(f"Получение комментариев для поста {post_id}.")
|
194 |
url = f"{GRAPH_API_URL}/{post_id}/comments"
|
|
|
198 |
"limit": 150,
|
199 |
}
|
200 |
comments = []
|
201 |
+
response = requests.get(url, params=params)
|
202 |
+
data = response.json()
|
203 |
+
if 'error' in data:
|
204 |
+
print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}")
|
205 |
+
comments.extend(data.get("data", []))
|
206 |
+
print(f"Найдено {len(data.get('data', []))} комментариев.")
|
207 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
208 |
return comments
|
209 |
|
210 |
|
|
|
215 |
"access_token": page_access_token,
|
216 |
"fields": "from{id},message",
|
217 |
}
|
218 |
+
try:
|
219 |
+
response = requests.get(url, params=params)
|
220 |
+
if response.status_code != 200:
|
221 |
+
print(f"Ошибка при запросе API: {response.status_code} - {response.text}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
222 |
return False
|
223 |
+
data = response.json()
|
224 |
+
if 'error' in data:
|
225 |
+
print(f"Ошибка при получении ответов на комментарий {comment_id}: {data['error']}")
|
226 |
+
return False
|
227 |
+
for reply in data.get("data", []):
|
228 |
+
reply_from = reply.get('from', {})
|
229 |
+
reply_from_id = reply_from.get('id')
|
230 |
+
reply_message = reply.get('message', '')
|
231 |
+
print(f"Найдена реплика от пользователя: {reply_from_id}, сообщение: {reply_message}")
|
232 |
+
if reply_from_id == page_id:
|
233 |
+
print(f"Страница {page_id} уже ответила на комментарий {comment_id}.")
|
234 |
+
return True
|
235 |
+
else:
|
236 |
+
print(f"Страница {page_id} не ответила на комментарий {comment_id}.")
|
237 |
+
return False
|
238 |
+
except requests.exceptions.RequestException as e:
|
239 |
+
print(f"Ошибка при выполнении запроса: {e}")
|
240 |
+
return False
|
241 |
|
242 |
|
243 |
def get_unanswered_comments(page_access_token):
|
|
|
289 |
else:
|
290 |
print(f"Ошибка при отправке ответа: {response.text}")
|
291 |
return False
|
|
|
|
|
|