new_ads_obnova / func_facebook.py
Uniaff's picture
Rename func_facebook to func_facebook.py
2f513eb verified
raw
history blame
7.27 kB
import facebook
import requests
from func_ai import analyze_sentiment
GRAPH_API_URL = 'https://graph.facebook.com/v20.0'
def hide_negative_comments(token):
def init_facebook_client(token):
return facebook.GraphAPI(access_token=token)
def get_facebook_posts():
graph = init_facebook_client(token)
posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
return posts_data.get('data', [])
def get_comments_for_all_posts(posts):
all_comments = []
graph = init_facebook_client(token)
for post in posts:
comments_data = graph.get_object(id=f'{post["id"]}/comments', fields='message,created_time,id,is_hidden')
visible_comments = [comment for comment in comments_data.get('data', []) if
not comment.get('is_hidden', False)]
all_comments.extend(visible_comments)
return all_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_comment(comment_id):
graph = init_facebook_client(token)
try:
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
posts = get_facebook_posts()
if not posts:
print("Нет постов для обработки.")
return []
comments = get_comments_for_all_posts(posts)
if not comments:
print("Нет комментариев для обработки.")
return []
comments_text = [comment['message'] for comment in comments]
sentiments = analyze_sentiment(comments_text)
negative_comments = filter_comments(comments, sentiments)
hidden_comments = []
for comment in negative_comments:
if hide_comment(comment['id']):
hidden_comments.append({
'id': comment['id'],
'message': comment['message']
})
return hidden_comments
def get_facebook_comments(post_id, ACCESS_TOKEN):
print(f"Получаем комментарии для поста: {post_id}")
url = f"{GRAPH_API_URL}/{post_id}/comments"
params = {
'access_token': ACCESS_TOKEN,
'filter': 'stream'
}
response = requests.get(url, params=params)
if response.status_code == 200:
print("Комментарии успешно получены.")
return response.json().get('data', [])
else:
print(f"Ошибка при получении комментариев: {response.text}")
return []
def get_page_id(page_access_token):
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_posts(page_id, page_access_token):
url = f"{GRAPH_API_URL}/{page_id}/posts"
params = {
"access_token": page_access_token,
"fields": "id"
# Максимальное количество постов за запрос
}
posts = []
while True:
response = requests.get(url, params=params)
data = response.json()
if 'error' in data:
print(f"Ошибка при получении постов: {data['error']}")
break
posts.extend(data.get("data", []))
if 'paging' in data and 'next' in data['paging']:
url = data['paging']['next']
params = {} # Следующие запросы уже содержат все параметры в URL
else:
break
return posts
def get_comments(post_id, page_access_token):
url = f"{GRAPH_API_URL}/{post_id}/comments"
params = {
"access_token": page_access_token,
"fields": "id,from,message,is_hidden",
}
comments = []
while True:
response = requests.get(url, params=params)
data = response.json()
if 'error' in data:
print(f"Ошибка при получении комментариев к посту {post_id}: {data['error']}")
break
comments.extend(data.get("data", []))
if 'paging' in data and 'next' in data['paging']:
url = data['paging']['next']
params = {} # Следующие запросы уже содержат все параметры в URL
else:
break
return comments
def has_page_replied(comment_id, page_id, page_access_token):
url = f"{GRAPH_API_URL}/{comment_id}/comments"
params = {
"access_token": page_access_token,
"fields": "from{id}",
}
while True:
response = requests.get(url, params=params)
data = response.json()
if 'error' in data:
print(f"Ошибка при получении ответов на комментарий {comment_id}: {data['error']}")
return False
for reply in data.get("data", []):
if reply['from']['id'] == page_id:
return True
if 'paging' in data and 'next' in data['paging']:
url = data['paging']['next']
params = {}
else:
break
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)
unanswered_comments = []
for post in posts:
post_id = post['id']
print(f"Обработка поста: {post_id}")
comments = get_comments(post_id, page_access_token)
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)
return unanswered_comments
def reply_comment(comment_id, message, token):
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