Python > 멘션된 경우 게시물 내용 가져오기

fluent-discourse 링크를 올려주셔서 감사합니다!

현재 Python에 익숙해지는 중이라, 제가 여기서 설명하는 것보다 더 나은 접근 방식이 있을 수 있습니다.

mention = client.notifications.json.get()

이것은 client를 생성할 때 설정한 username에 대한 언급(mention) 목록을 사전(dictionary)으로 반환합니다. client를 생성할 때 username을 UserA로 설정했을 것으로 추정합니다.

사전이 반환되는지 확인하려면 다음을 실행할 수 있습니다:

print(type(mention))

그 결과는 <class 'dict'>가 되어야 합니다.

사전의 키를 확인하려면 다음을 실행할 수 있습니다:

print(list(mention))

이것은 ['notifications', 'total_rows_notifications', 'seen_notification_id', 'load_more_notifications']를 반환합니다.

사용자의 경우, notifications 키 아래에 있는 값이 필요합니다:

notifications = mention['notifications']

이때 type(notifications)을 실행하면 이것이 목록(list)임을 알 수 있습니다. UserA의 언급으로 인해 트리거된 알림을 가져오려면, notification_type이 1로 설정된 항목을 찾기 위해 목록을 반복(iterate)해야 합니다. Discourse 알림 유형의 값을 확인하는 가장 쉬운 방법은 Discourse 사이트의 rails 콘솔에서 Notification.types를 실행하는 것입니다:

 pry(main)> Notification.types
=> {:mentioned=>1,
 :replied=>2,
 :quoted=>3,
 :edited=>4,
 :liked=>5,
 ...

따라서 client에 설정한 사용자名的(username)을 가진 사용자의 “mention” 알림을 가져오려면 다음과 같은 것을 시도해 보세요(작성하면서 Python 인터프리터에서 테스트 중입니다):

data = client.notifications.json.get()
notifications = data['notifications']
# "mention" 알림을 저장할 빈 목록 객체 생성
mentions = []
# `notification_type`이 `1`로 설정된 모든 항목을 찾기 위해 `notifications` 목록 반복
for notification in notifications:
    if notification['notification_type'] == 1:
        mentions.append(notification)

이것은 언급으로 인해 트리거된 알림의 목록을 생성합니다. 목록의 각 항목은 사전이 될 것입니다. 다음과 같은 것으로 확인할 수 있습니다:

for mention in mentions:
    print(mention['topic_id'], mention['post_number'])