简体   繁体   中英

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!

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM