Get latest direct message from Twitter using python/Tweepy

被刻印的时光 ゝ 提交于 2020-07-22 21:33:08

问题


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!


回答1:


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.




回答2:


You can get all Twitter DMs sent to the authenticated user in the last 30 days. Here's the syntax, according to tweepy's official documentation;

API.list_direct_messages([count][, cursor])

Where count is the number of messages you want to retrieve and cursor breaks the results into pages.

Since you specifically needed the last message, you can have your count value as 1. This will return the last DM. You don't need to know it's ID to retrieve it.

last_dms = api.list_direct_messages(1)
for messages in last_dms:
    print(messages)

api.list_direct_messages() returns list of DirectMessageObjects, hence the need to use a loop to print the individual objects. That should solve your problem. But if you want to do more stuff with the DMs, you can extract information from the object returned to do whatever you want. Here's a sample DM object

*

DirectMessage(_api=, type='message_create', id='xxxxxxxxxxxxxxxxxx', created_timestamp='1587925077545', message_create={'target': {'recipient_id': 'xxxxxxxxx'}, 'sender_id': 'xxxxxxxxxxxxxxxxxxx', 'source_app_id': '258901', 'message_data': {'text': 'I love you', 'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': []}}})

*

The information in that object can be used to do a lot of stuff that I won't get to in this post. It's been long since the question was asked, but I hope this helps someone else. Adios!



来源:https://stackoverflow.com/questions/42603493/get-latest-direct-message-from-twitter-using-python-tweepy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!