How to get Mastodon direct messages using Mastodon.py

Question:

I am trying to get direct messages from my Mastodon account using Mastodon.py. I am able to get everything on the timeline, but can’t seem to return direct messages. Since direct messages are separate from the timeline (on the web interface), I am assuming there is some function other than timeline() I should be using. I looked into the status() function but I would need to already have the ID of the message to use it.

I have been searching the API documentation, but there doesn’t appear to be any function or method that is obvious to me.

My function currently looks like this:

def get_direct_messages(mastodon):                                                                           
    # Get all status messages from the user's timeline                                                       
    statuses = mastodon.timeline()                                                                           
    print(statuses)                                                                                          
    # Filter the status messages to only include direct messages                                             
    direct_messages = [status for status in statuses if status["visibility"] == "direct"]                    
                                                                                                             
    print (direct_messages)                                                                                  
                                                                                                             
    return direct_messages      

This will print out all the messages on the timeline, so I know the connection and everything is valid, but I’m just not doing something right.
print(statuses) shows timeline messages only, so I am sure this isn’t the right way to access direct messages.

Asked By: Rick Dearman

||

Answers:

Instead of mastodon.timeline() you want to call

mastodon.conversations()

To get the content of the conversations you can do

conversations = mastodon.conversations()
for c in conversations:
    print(c.last_status.content)

https://mastodonpy.readthedocs.io/en/stable/07_timelines.html#mastodon.Mastodon.conversations

Answered By: Sebastian
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.