CajunTechie
CajunTechie

Reputation: 605

Get latest direct message from Twitter using python/Tweepy

I've just started using Tweepy and I'm trying to build a pretty simple bot that will use Twitter to automate a few things in my home (mostly for fun and to learn Tweepy). I've gone through the Tweepy docs and can't find out how to retrieve the latest direct message from my own account without knowing the message ID.

I'm assuming I can use the API.get_direct_messages() method but it requires a message ID (which I don't know). Can anyone clue me in to the proper way to do this? I'm using Python3

Thanks!

Upvotes: 1

Views: 4231

Answers (2)

Otieno
Otieno

Reputation: 707

From Tweepy Docs ~ "API.list_direct_messages([count][, cursor]) Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order."

my_dms = api.list_direct_messages()

To get the latest message object (both sent and received):

my_dms[0]

If you specifically want the last received message:

def get_last_received(my_dms):
    for dm in my_dms:
        if dm.message_create['target']['recipient_id'] == 'my_user_id':
            return dm  # We will return when we encounter the first received message object

get_last_received(my_dms)

Upvotes: 1

Chris
Chris

Reputation: 137159

You seem to have confused two different methods. The direct_messages() method (without get_) should give you a list of direct messages.

get_direct_message() (singular) returns a single direct message from its ID.

Upvotes: 1

Related Questions