Python > Get post content if mentioned

Thanks for posting the link to fluent-discourse!

I’m currently trying to get up to speed with Python, so it’s possible there are better ways of approaching this than what I’m outlining here.

mention = client.notifications.json.get()

This is returning a dictionary of mentions for the username you set when you created the client. I am assuming that you set the username to UserA when you created the client.

To confirm that a dictionary is being returned, you can run:

print(type(mention))

That should return <class 'dict'>

You can see the dictionary’s keys by running:

print(list(mention))

That will return ['notifications', 'total_rows_notifications', 'seen_notification_id', 'load_more_notifications']

For your case, you want the values that are found under the notifications key:

notifications = mention['notifications']

If you then run type(notifications), you’ll see that it is a list. To get notifications that were triggered by mentions of UserA, you need to iterate through the list to find entries where the notification_type is set to 1. The easiest way to see the values for the Discourse notification types is to run Notification.types from your Discourse site’s rails console:

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

So to get “mention” notifications for the user whose username you’ve set for the client, try something like this (I’m testing this in the Python interpreter as I type it):

data = client.notifications.json.get()
notifications = data['notifications']
# Create an empty list object to store "mention" notifications
mentions = []
# Iterate through the `notifications` list to find all entries where the `notification_type` is set to `1`
for notification in notifications:
    if notification['notification_type'] == 1:
        mentions.append(notification)

That will create a list of notifications that were triggered by mentions. Each item in the list will be a dictionary. You can check it with something like:

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