File size: 8,861 Bytes
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
7e8b38a
 
 
f9c1865
97319cc
 
 
 
 
 
7e8b38a
97319cc
 
 
 
 
 
f9c1865
4117ebc
 
 
f9c1865
4117ebc
 
 
 
 
 
 
 
 
 
 
 
 
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4117ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9c1865
 
4117ebc
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05aac62
f9c1865
 
4117ebc
f9c1865
05aac62
f9c1865
05aac62
f9c1865
05aac62
f9c1865
 
05aac62
f9c1865
 
 
05aac62
 
f9c1865
05aac62
 
 
 
 
 
 
 
 
 
 
 
 
f9c1865
 
05aac62
 
f9c1865
 
05aac62
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4117ebc
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4117ebc
f9c1865
 
 
4117ebc
f9c1865
 
 
4117ebc
 
f9c1865
 
 
 
 
 
 
 
4117ebc
 
 
 
 
 
 
 
f9c1865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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():
        params = {
            'include_inline_create': 'true'  # Параметры запроса
        }
        graph = init_facebook_client(token)
        
        # Fetching user posts
        user_posts_data = graph.get_object(id='me/posts', fields='id,message,created_time')
        user_posts = user_posts_data.get('data', [])
    
        # Fetching ads posts
        ads_posts_data = graph.get_object('me/ads_posts', **params)
        ads_posts = ads_posts_data.get('data', [])
        
        # Combine the posts from both sources
        all_posts = user_posts + ads_posts
        
        return all_posts



    def get_comments_for_post(post_id):
        graph = init_facebook_client(token)
        comments = []
        url = f'{post_id}/comments'
        params = {'fields': 'id,message,is_hidden'}
        while True:
            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)
            if 'paging' in comments_data and 'next' in comments_data['paging']:
                url = comments_data['paging']['next']
                params = {}  # The 'next' URL already includes access token and fields
            else:
                break
        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_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 []

    hidden_comments_per_post = []
    for post in posts:
        post_id = post['id']
        post_message = post.get('message', '')
        comments = get_comments_for_post(post_id)
        if not comments:
            print(f"Нет комментариев для поста {post_id}.")
            continue

        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']
                })

        if hidden_comments:
            hidden_comments_per_post.append({
                'post_id': post_id,
                'post_message': post_message,
                'hidden_comments': hidden_comments
            })

    return hidden_comments_per_post


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"
    url_ads = f"{GRAPH_API_URL}/{page_id}/ads_posts?include_inline_create=true"
    params = {
        "access_token": page_access_token,
        "fields": "id,message"
    }
    
    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", []))
        
        # Обрабатываем посты с рекламы
        response_ads = requests.get(url_ads, params={"access_token": page_access_token, "fields": "id,message"})
        data_ads = response_ads.json()

        if 'error' in data_ads:
            print(f"Ошибка при получении рекламных постов: {data_ads['error']}")
            break
        
        # Добавляем рекламные посты в общий список
        posts.extend(data_ads.get("data", []))
        
        # Проверяем, есть ли следующие страницы для обычных постов
        if 'paging' in data and 'next' in data['paging']:
            url = data['paging']['next']
            # Удаляем параметры, так как они уже в URL
            params = {}  
        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 = {}
        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)
    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):
    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