4

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Rick Dearman
  • 356
  • 2
  • 12

1 Answers1

1

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

Sebastian
  • 5,721
  • 3
  • 43
  • 69
  • This does allow me to access the conversation, but not the content of the message. This seems to be buried in the last_status. Any suggestions on how to extract the content of the message? – Rick Dearman Mar 11 '23 at 09:02
  • I just tried it with one private message and I could see the content in the result. – Sebastian Mar 11 '23 at 19:43
  • 1
    Yes, I can see the content, just had to use regular expression to get the text out. But it is fine, it is working. I was hoping for a dict of dict. – Rick Dearman Mar 13 '23 at 18:05
  • adapted my answer. You can try "last_status.content" – Sebastian Mar 14 '23 at 07:52