Uniaff commited on
Commit
c422a27
·
verified ·
1 Parent(s): 28dbcf4

Update func_facebook.py

Browse files
Files changed (1) hide show
  1. 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 hide_negative_comments(token):
9
- def init_facebook_client(token):
10
- print("Инициализация клиента Facebook.")
11
- return facebook.GraphAPI(access_token=token)
12
-
13
- def get_facebook_posts():
14
- print("Получение постов.")
15
- params = {
16
- 'include_inline_create': 'true',
17
- "limit": 150
18
- }
19
- graph = init_facebook_client(token)
20
-
21
- user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
22
- user_posts = user_posts_data.get('data', [])
23
- print(f"Найдено {len(user_posts)} пользовательских постов.")
24
-
25
- try:
26
- ads_posts_data = graph.get_object('me/ads_posts', **params)
27
- ads_posts = ads_posts_data.get('data', [])
28
- print(f"Найдено {len(ads_posts)} рекламных постов.")
29
- except facebook.GraphAPIError as e:
30
- print(f"Ошибка при получении рекламных постов: {e}")
31
- ads_posts = []
32
-
33
- all_posts = user_posts + ads_posts
34
- unique_posts_dict = {post['id']: post for post in all_posts}
35
- unique_posts = list(unique_posts_dict.values())
36
- print(f"Всего уникальных постов: {len(unique_posts)}.")
37
-
38
- return unique_posts
39
-
40
- def get_comments_for_post(post_id):
41
- print(f"Получение комментариев для поста {post_id}.")
42
- graph = init_facebook_client(token)
43
- comments = []
44
- url = f'{post_id}/comments'
45
- params = {'fields': 'id,message,is_hidden', 'limit': 10000}
46
- while True:
47
- try:
48
- comments_data = graph.get_object(id=url, **params)
49
- except facebook.GraphAPIError as e:
50
- print(f"Ошибка при получении комментариев для поста {post_id}: {e}")
51
- break
52
- visible_comments = [comment for comment in comments_data.get('data', []) if not comment.get('is_hidden', False)]
53
- comments.extend(visible_comments)
54
- print(f"Найдено {len(visible_comments)} видимых комментариев для поста {post_id}.")
55
- if 'paging' in comments_data and 'next' in comments_data['paging']:
56
- url = comments_data['paging']['next']
57
- params = {}
58
- else:
59
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  return comments
61
 
62
- def filter_comments(comments, sentiments):
63
- print("Фильтрация негативных комментариев.")
64
- negative_comments = []
65
- for comment, sentiment in zip(comments, sentiments):
66
- if sentiment['label'].lower() == 'negative':
67
- print(f"Негативный комментарий найден: {comment['message']}")
68
- negative_comments.append(comment)
69
- return negative_comments
70
-
71
- def hide_comment(comment_id):
72
- print(f"Скрытие комментария {comment_id}.")
73
- graph = init_facebook_client(token)
74
- try:
 
 
 
 
75
  graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST')
76
- return True
77
- except facebook.GraphAPIError as e:
78
- print(f"Ошибка при скрытии комментария {comment_id}: {e}")
79
- return False
80
 
81
- posts = get_facebook_posts()
82
- if not posts:
83
- print("Нет постов для обработки.")
 
 
 
84
  return []
85
 
86
- hidden_comments_per_post = []
87
  processed_comment_ids = set() # Отслеживание обработанных комментариев
 
88
 
89
- for post in posts:
90
- post_id = post['id']
91
- post_message = post.get('message', '')
92
- comments = get_comments_for_post(post_id)
93
- if not comments:
94
- print(f"Нет комментариев для поста {post_id}.")
95
  continue
 
 
 
96
 
97
- hidden_comments = []
98
- comments_text = []
99
- comments_to_process = []
100
 
101
- for comment in comments:
102
- comment_id = comment['id']
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
- if not comments_to_process:
111
- continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
112
 
113
- sentiments = analyze_sentiment(comments_text)
114
- negative_comments = filter_comments(comments_to_process, sentiments)
115
 
116
- for comment in negative_comments:
117
- if hide_comment(comment['id']):
118
- hidden_comments.append({
119
- 'id': comment['id'],
120
- 'message': comment['message']
121
- })
122
 
123
- if hidden_comments:
124
- hidden_comments_per_post.append({
125
  'post_id': post_id,
126
  'post_message': post_message,
127
- 'hidden_comments': hidden_comments
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
- while True:
205
- response = requests.get(url, params=params)
206
- data = response.json()
207
- if 'error' in data:
208
- print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}")
209
- break
210
- comments.extend(data.get("data", []))
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
- while True:
228
- try:
229
- response = requests.get(url, params=params)
230
- if response.status_code != 200:
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
- print(f"Страница {page_id} не ответила на комментарий {comment_id}.")
254
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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