Spaces:
Paused
Paused
import facebook | |
import requests | |
from func_ai import analyze_sentiment | |
GRAPH_API_URL = 'https://graph.facebook.com/v20.0' | |
def init_facebook_client(token): | |
print("Инициализация клиента Facebook.") | |
return facebook.GraphAPI(access_token=token) | |
def get_posts(page_id, page_access_token): | |
print(f"Получение постов для страницы {page_id}.") | |
url = f"{GRAPH_API_URL}/{page_id}/posts" | |
url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true" | |
params = { | |
"access_token": page_access_token, | |
"fields": "id,message", | |
"limit": 50 | |
} | |
params_ads = { | |
"access_token": page_access_token, | |
"fields": "id,message", | |
"limit": 150 | |
} | |
posts = [] | |
response = requests.get(url, params=params) | |
data = response.json() | |
if 'error' in data: | |
print(f"Ошибка при получении постов: {data['error']}") | |
posts.extend(data.get("data", [])) | |
print(f"Получено {len(data.get('data', []))} постов.") | |
response_ads = requests.get(url_ads, params=params_ads) | |
data_ads = response_ads.json() | |
if 'error' in data_ads: | |
print(f"Ошибка при получении рекламных постов: {data_ads['error']}") | |
posts.extend(data_ads.get("data", [])) | |
print(f"Получено {len(data_ads.get('data', []))} рекламных постов.") | |
return posts | |
def get_facebook_posts(graph): | |
print("Получение постов.") | |
params = { | |
'include_inline_create': 'true', | |
"limit": 150 | |
} | |
user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time') | |
user_posts = user_posts_data.get('data', []) | |
print(f"Найдено {len(user_posts)} пользовательских постов.") | |
try: | |
ads_posts_data = graph.get_object('me/ads_posts', **params) | |
ads_posts = ads_posts_data.get('data', []) | |
print(f"Найдено {len(ads_posts)} рекламных постов.") | |
except facebook.GraphAPIError as e: | |
print(f"Ошибка при получении рекламных постов: {e}") | |
ads_posts = [] | |
all_posts = user_posts + ads_posts | |
unique_posts_dict = {post['id']: post for post in all_posts} | |
unique_posts = list(unique_posts_dict.values()) | |
print(f"Всего уникальных постов: {len(unique_posts)}.") | |
return unique_posts | |
def get_comments_for_post(post_id, graph): | |
print(f"Получение комментариев для поста {post_id}.") | |
comments = [] | |
url = f'{post_id}/comments' | |
params = {'fields': 'id,message,is_hidden', 'limit': 10000} | |
try: | |
comments_data = graph.get_object(id=url, **params) | |
visible_comments = [comment for comment in comments_data.get('data', []) if not comment.get('is_hidden', False)] | |
comments.extend(visible_comments) | |
print(f"Найдено {len(visible_comments)} видимых комментариев для поста {post_id}.") | |
except facebook.GraphAPIError as e: | |
print(f"Ошибка при получении комментариев для поста {post_id}: {e}") | |
finally: | |
return comments | |
def filter_comments(comments, sentiments): | |
print("Фильтрация негативных комментариев.") | |
negative_comments = [] | |
for comment, sentiment in zip(comments, sentiments): | |
if sentiment['label'].lower() == 'negative': | |
print(f"Негативный комментарий найден: {comment['message']}") | |
negative_comments.append(comment) | |
return negative_comments | |
def hide_or_delete_comment(comment_id, graph, action): | |
print(f"Выбранное действие для комментария {comment_id}: {action}") | |
try: | |
if action == "Delete": | |
graph.request(f'{comment_id}', method='DELETE') | |
elif action == "Hide": | |
graph.request(f'{comment_id}', post_args={'is_hidden': True}, method='POST') | |
return True | |
except facebook.GraphAPIError as e: | |
print(f"Ошибка при скрытии/удалении комментария {comment_id}: {e}") | |
return False | |
def process_negative_comments_in_post(post_id, token, action): | |
graph = init_facebook_client(token) | |
comments_in_post = get_comments_for_post(post_id, graph) | |
if not comments_in_post: | |
print(f"Нет комментариев для поста {post_id}.") | |
return [] | |
processed_comment_ids = set() # Отслеживание обработанных комментариев | |
comments, comments_text, comments_to_process = [], [], [] | |
for comment in comments_in_post: | |
comment_id = comment['id'] | |
if comment_id in processed_comment_ids: | |
print(f"Комментарий {comment_id} уже обработан. Пропуск.") | |
continue | |
processed_comment_ids.add(comment_id) | |
comments_text.append(comment['message']) | |
comments_to_process.append(comment) | |
if not comments_to_process: | |
return [] | |
sentiments = analyze_sentiment(comments_text) | |
negative_comments = filter_comments(comments_to_process, sentiments) | |
for comment in negative_comments: | |
if hide_or_delete_comment(comment['id'], graph, action): | |
comments.append({ | |
'id': comment['id'], | |
'message': comment['message'] | |
}) | |
return comments | |
def process_negative_comments(token, action): | |
graph = init_facebook_client(token) | |
posts = get_facebook_posts(graph) | |
if not posts: | |
print("Нет постов для обработки.") | |
return [] | |
comments_per_post = [] | |
for post in posts: | |
post_id = post['id'] | |
post_message = post.get('message', '') | |
comments = process_negative_comments_in_post(post_id, token, action) | |
if comments != []: | |
comments_per_post.append({ | |
'post_id': post_id, | |
'post_message': post_message, | |
'comments': comments | |
}) | |
return comments_per_post | |
def get_page_id(page_access_token): | |
print("Получение ID страницы.") | |
url = f"{GRAPH_API_URL}/me" | |
params = { | |
"access_token": page_access_token, | |
"fields": "id,name" | |
} | |
response = requests.get(url, params=params) | |
data = response.json() | |
if 'error' in data: | |
print(f"Ошибка при получении ID страницы: {data['error']}") | |
return None | |
return data.get("id") | |
def get_comments(post_id, page_access_token): | |
print(f"Получение комментариев для поста {post_id}.") | |
url = f"{GRAPH_API_URL}/{post_id}/comments" | |
params = { | |
"access_token": page_access_token, | |
"fields": "id,from,message,is_hidden", | |
"limit": 150, | |
} | |
comments = [] | |
response = requests.get(url, params=params) | |
data = response.json() | |
if 'error' in data: | |
print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}") | |
comments.extend(data.get("data", [])) | |
print(f"Найдено {len(data.get('data', []))} комментариев.") | |
return comments | |
def has_page_replied(comment_id, page_id, page_access_token): | |
print(f"Проверка ответа на комментарий {comment_id}.") | |
url = f"{GRAPH_API_URL}/{comment_id}/comments" | |
params = { | |
"access_token": page_access_token, | |
"fields": "from{id},message", | |
} | |
try: | |
response = requests.get(url, params=params) | |
if response.status_code != 200: | |
print(f"Ошибка при запросе API: {response.status_code} - {response.text}") | |
return False | |
data = response.json() | |
if 'error' in data: | |
print(f"Ошибка при получении ответов на комментарий {comment_id}: {data['error']}") | |
return False | |
for reply in data.get("data", []): | |
reply_from = reply.get('from', {}) | |
reply_from_id = reply_from.get('id') | |
reply_message = reply.get('message', '') | |
print(f"Найдена реплика от пользователя: {reply_from_id}, сообщение: {reply_message}") | |
if reply_from_id == page_id: | |
print(f"Страница {page_id} уже ответила на комментарий {comment_id}.") | |
return True | |
else: | |
print(f"Страница {page_id} не ответила на комментарий {comment_id}.") | |
return False | |
except requests.exceptions.RequestException as e: | |
print(f"Ошибка при выполнении запроса: {e}") | |
return False | |
def get_unanswered_comments(page_access_token): | |
page_id = get_page_id(page_access_token) | |
if not page_id: | |
return [] | |
print(f"ID Страницы: {page_id}") | |
posts = get_posts(page_id, page_access_token) | |
posts_with_unanswered_comments = [] | |
for post in posts: | |
post_id = post['id'] | |
post_message = post.get('message', '') | |
print(f"Обработка поста: {post_id}") | |
comments = get_comments(post_id, page_access_token) | |
unanswered_comments = [] | |
for comment in comments: | |
if comment.get('is_hidden', False): | |
continue | |
comment_id = comment['id'] | |
print(f"Проверка комментария: {comment_id}") | |
if not has_page_replied(comment_id, page_id, page_access_token): | |
unanswered_comments.append(comment) | |
if unanswered_comments: | |
posts_with_unanswered_comments.append({ | |
'post_id': post_id, | |
'post_message': post_message, | |
'unanswered_comments': unanswered_comments | |
}) | |
return posts_with_unanswered_comments | |
def reply_comment(comment_id, message, token): | |
print(f"Отправка ответа на комментарий {comment_id}.") | |
url = f"{GRAPH_API_URL}/{comment_id}/comments" | |
params = { | |
'access_token': token, | |
'message': message | |
} | |
response = requests.post(url, params=params) | |
if response.status_code == 200: | |
print(f"Ответ успешно отправлен на комментарий {comment_id}.") | |
return True | |
else: | |
print(f"Ошибка при отправке ответа: {response.text}") | |
return False | |